blob: 64b7aec4681bae4468eecd651973527da30ddf85 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
François Gaffie11d30102018-11-02 16:09:09 +0100125void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000130 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000131 status != OK) {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700132 ALOGE("Error %d while setting connected state %d for device %s",
133 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 device->getDeviceTypeAddr().toString(false).c_str());
135 }
François Gaffie44481e72016-04-20 07:49:57 +0200136}
137
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100138status_t AudioPolicyManager::setDeviceConnectionStateInt(
139 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
140 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100141 if (port.ext.getTag() != AudioPortExt::device) {
142 return BAD_VALUE;
143 }
144 audio_devices_t device_type;
145 std::string device_address;
146 if (status_t status = aidl2legacy_AudioDevice_audio_device(
147 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
148 status != OK) {
149 return status;
150 };
151 const char* device_name = port.name.c_str();
152 // connect/disconnect only 1 device at a time
153 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
154 return BAD_VALUE;
155
156 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
157 device_type, device_address.c_str(), device_name, encodedFormat,
158 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000159 if (device == nullptr) {
160 return INVALID_OPERATION;
161 }
162 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
163 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
164 }
165 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100166}
167
François Gaffie11d30102018-11-02 16:09:09 +0100168status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800169 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100170 const char* device_address,
171 const char* device_name,
172 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800173 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100174 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
175 status == OK) {
176 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
177 } else {
178 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
179 return status;
180 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181}
Paul McLeane743a472015-01-28 11:07:31 -0800182
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
184 audio_policy_dev_state_t state)
185{
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700187 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700188 SortedVector <audio_io_handle_t> outputs;
189
François Gaffie11d30102018-11-02 16:09:09 +0100190 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 // save a copy of the opened output descriptors before any output is opened or closed
193 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
194 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100195
196 bool wasLeUnicastActive = isLeUnicastActive();
197
Eric Laurente552edb2014-03-10 17:42:56 -0700198 switch (state)
199 {
200 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800201 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700202 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100203 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700204 return INVALID_OPERATION;
205 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800206 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700207 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700208
Eric Laurente552edb2014-03-10 17:42:56 -0700209 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200210 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700211 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700212 }
213
François Gaffie44481e72016-04-20 07:49:57 +0200214 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
215 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200217
François Gaffie11d30102018-11-02 16:09:09 +0100218 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
219 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200220
jiabinc0048632023-04-27 22:04:31 +0000221 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700222
223 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 return INVALID_OPERATION;
225 }
François Gaffie2110e042015-03-24 08:41:51 +0100226
jiabin1c4794b2020-05-05 10:08:05 -0700227 // Populate encapsulation information when a output device is connected.
228 device->setEncapsulationInfoFromHal(mpClientInterface);
229
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 // outputs should never be empty here
231 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
232 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700236 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700237 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700238 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700240 return INVALID_OPERATION;
241 }
242
François Gaffie11d30102018-11-02 16:09:09 +0100243 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700244
jiabinc0048632023-04-27 22:04:31 +0000245 // Notify the HAL to prepare to disconnect device
246 broadcastDeviceConnectionState(
247 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700248
Eric Laurente552edb2014-03-10 17:42:56 -0700249 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100250 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700251
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100252 mOutputs.clearSessionRoutesForDevice(device);
253
François Gaffie11d30102018-11-02 16:09:09 +0100254 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100255
jiabinc0048632023-04-27 22:04:31 +0000256 // Send Disconnect to HALs
257 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
258
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800259 // Reset active device codec
260 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
261
Kriti Dangef6be8f2020-11-05 11:58:19 +0100262 // remove device from mReportedFormatsMap cache
263 mReportedFormatsMap.erase(device);
264
jiabina84c3d32022-12-02 18:59:55 +0000265 // remove preferred mixer configurations
266 mPreferredMixerAttrInfos.erase(device->getId());
267
Eric Laurente552edb2014-03-10 17:42:56 -0700268 } break;
269
270 default:
François Gaffie11d30102018-11-02 16:09:09 +0100271 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700272 return BAD_VALUE;
273 }
274
Eric Laurent736a1022019-03-27 18:28:46 -0700275 // Propagate device availability to Engine
276 setEngineDeviceConnectionState(device, state);
277
Eric Laurentae970022019-01-29 14:25:04 -0800278 // No need to evaluate playback routing when connecting a remote submix
279 // output device used by a dynamic policy of type recorder as no
280 // playback use case is affected.
281 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700282 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800283 for (audio_io_handle_t output : outputs) {
284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800285 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
286 if (policyMix != nullptr
287 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000288 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800289 doCheckForDeviceAndOutputChanges = false;
290 break;
291 }
292 }
293 }
294
295 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700296 // outputs must be closed after checkOutputForAllStrategies() is executed
297 if (!outputs.isEmpty()) {
298 for (audio_io_handle_t output : outputs) {
299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100300 // close unused outputs after device disconnection or direct outputs that have
301 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200302 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200303 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200305 (desc->mDirectOpenCount == 0))
306 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
307 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200308 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 closeOutput(output);
310 }
Eric Laurente552edb2014-03-10 17:42:56 -0700311 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700312 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
313 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700314 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800316 };
317
318 if (doCheckForDeviceAndOutputChanges) {
319 checkForDeviceAndOutputChanges(checkCloseOutputs);
320 } else {
321 checkCloseOutputs();
322 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100323 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100324 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700325 const DeviceVector activeMediaDevices =
326 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000327 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700328 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700329 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530330 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
331 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100332 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // do not force device change on duplicated output because if device is 0, it will
334 // also force a device 0 for the two outputs it is duplicated to which may override
335 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100336 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100337 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700338 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // always force when disconnecting (a non-duplicated device)
340 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
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();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700377 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700378 } // end if is output device
379
Eric Laurente552edb2014-03-10 17:42:56 -0700380 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700381 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100382 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700383 switch (state)
384 {
385 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700386 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700387 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100388 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700389 return INVALID_OPERATION;
390 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700391
392 if (mAvailableInputDevices.add(device) < 0) {
393 return NO_MEMORY;
394 }
395
François Gaffie44481e72016-04-20 07:49:57 +0200396 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
397 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000398 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200399
Eric Laurent0dd51852019-04-19 18:18:58 -0700400 if (checkInputsForDevice(device, state) != NO_ERROR) {
401 mAvailableInputDevices.remove(device);
402
jiabinc0048632023-04-27 22:04:31 +0000403 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100404
405 mHwModules.cleanUpForDevice(device);
406
Eric Laurentd4692962014-05-05 18:13:44 -0700407 return INVALID_OPERATION;
408 }
409
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700413 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700414 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100415 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700416 return INVALID_OPERATION;
417 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700418
François Gaffie11d30102018-11-02 16:09:09 +0100419 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700420
jiabinc0048632023-04-27 22:04:31 +0000421 // Notify the HAL to prepare to disconnect device
422 broadcastDeviceConnectionState(
423 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700424
François Gaffie11d30102018-11-02 16:09:09 +0100425 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700426
427 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100428
jiabinc0048632023-04-27 22:04:31 +0000429 // Set Disconnect to HALs
430 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
431
Kriti Dangef6be8f2020-11-05 11:58:19 +0100432 // remove device from mReportedFormatsMap cache
433 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700434 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700435
436 default:
François Gaffie11d30102018-11-02 16:09:09 +0100437 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700438 return BAD_VALUE;
439 }
440
Eric Laurent736a1022019-03-27 18:28:46 -0700441 // Propagate device availability to Engine
442 setEngineDeviceConnectionState(device, state);
443
Eric Laurent0dd51852019-04-19 18:18:58 -0700444 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700445 // As the input device list can impact the output device selection, update
446 // getDeviceForStrategy() cache
447 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700448
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100449 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200450 // Reconnect Audio Source
451 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
452 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
453 checkAudioSourceForAttributes(attributes);
454 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700455 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100456 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700457 }
458
Eric Laurentb52c1522014-05-20 11:27:36 -0700459 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700460 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700461 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700462
François Gaffie11d30102018-11-02 16:09:09 +0100463 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700464 return BAD_VALUE;
465}
466
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100467status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
468 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800469 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700470 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
471 devDescr->setName(device_name);
472 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100473}
474
Eric Laurent736a1022019-03-27 18:28:46 -0700475void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
476 audio_policy_dev_state_t state) {
477
478 // the Engine does not have to know about remote submix devices used by dynamic audio policies
479 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
480 return;
481 }
482 mEngine->setDeviceConnectionState(device, state);
483}
484
485
Eric Laurente0720872014-03-11 09:30:41 -0700486audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100487 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700488{
Eric Laurent634b7142016-04-20 13:48:02 -0700489 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800490 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
491 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700492 (strlen(device_address) != 0)/*matchAddress*/);
493
494 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100495 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700496 device, device_address);
497 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
498 }
François Gaffie53615e22015-03-19 09:24:12 +0100499
Eric Laurent3a4311c2014-03-17 12:00:47 -0700500 DeviceVector *deviceVector;
501
Eric Laurente552edb2014-03-10 17:42:56 -0700502 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700503 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700504 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700505 deviceVector = &mAvailableInputDevices;
506 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100507 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700509 }
Eric Laurent634b7142016-04-20 13:48:02 -0700510
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 return (deviceVector->getDevice(
512 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700513 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800514}
515
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
517 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 const char *device_name,
519 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800521 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
522 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800524 // connect/disconnect only 1 device at a time
525 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
526
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700528 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800530 // Nothing to do: device is not connected
531 return NO_ERROR;
532 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800534
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700535 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800536 // configure codecs.
537 // Handle two specific cases by sending a set parameter to
538 // configure A2DP codecs. No need to toggle device state.
539 // Case 1: A2DP active device switches from primary to primary
540 // module
541 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100542 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700543 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800544 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
545 if (availablePrimaryOutputDevices().contains(devDesc) &&
546 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100547 bool isA2dp = audio_is_a2dp_out_device(device);
548 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
549 : String8(AudioParameter::keyReconfigLeSupported);
550 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800551 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100552 int isReconfigSupported;
553 repliedParameters.getInt(supportKey, isReconfigSupported);
554 if (isReconfigSupported) {
555 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
556 : String8(AudioParameter::keyReconfigLe);
557 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800558 param.add(key, String8("true"));
559 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
560 devDesc->setEncodedFormat(encodedFormat);
561 return NO_ERROR;
562 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700563 }
564 }
cnx421bd2dcc42020-07-11 14:58:44 +0800565 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000566 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800567 for (size_t i = 0; i < mOutputs.size(); i++) {
568 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000569 // mute media strategies to avoid sending the music tail into
570 // the earpiece or headset.
571 if (desc->isStrategyActive(musicStrategy)) {
572 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
573 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
574 tempRecommendedMuteDuration : desc->latency() * 4;
575 if (muteWaitMs < tempMuteDurationMs) {
576 muteWaitMs = tempMuteDurationMs;
577 }
578 }
cnx421bd2dcc42020-07-11 14:58:44 +0800579 setStrategyMute(musicStrategy, true, desc);
580 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
581 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
582 nullptr, true /*fromCache*/).types());
583 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000584 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
585 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
586 // happens after the actual device switch.
587 if (muteWaitMs > 0) {
588 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
589 usleep(muteWaitMs * 1000);
590 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800591 // Toggle the device state: UNAVAILABLE -> AVAILABLE
592 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100593 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800594 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800595 device_address, device_name,
596 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800597 if (status != NO_ERROR) {
598 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
599 status);
600 return status;
601 }
602
603 status = setDeviceConnectionState(device,
604 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800605 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800606 if (status != NO_ERROR) {
607 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
608 status);
609 return status;
610 }
611
612 return NO_ERROR;
613}
614
Pattydd807582021-11-04 21:01:03 +0800615status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
616 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800617{
Pattydd807582021-11-04 21:01:03 +0800618 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800619 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800620 std::unordered_set<audio_format_t> formatSet;
621 sp<HwModule> primaryModule =
622 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700623 if (primaryModule == nullptr) {
624 ALOGE("%s() unable to get primary module", __func__);
625 return NO_INIT;
626 }
Pattydd807582021-11-04 21:01:03 +0800627
628 DeviceTypeSet audioDeviceSet;
629
630 switch(device) {
631 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
632 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
633 break;
634 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800635 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
636 break;
637 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
638 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800639 break;
640 default:
641 ALOGE("%s() device type 0x%08x not supported", __func__, device);
642 return BAD_VALUE;
643 }
644
jiabin9a3361e2019-10-01 09:38:30 -0700645 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800646 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800647 for (const auto& device : declaredDevices) {
648 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800649 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800650 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800651 return status;
652}
653
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100654DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
655{
656 DeviceVector rxSinkdevices{};
657 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
658 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
659 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
660 auto rxSinkDevice = rxSinkdevices.itemAt(0);
661 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
662 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
663 // retrieve Rx Source device descriptor
664 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
665 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
666
667 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
668 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
669 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
670 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
671 return DeviceVector(rxSinkDevice);
672 }
673 }
674 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
675 // the device returned is not necessarily reachable via this output
676 // (filter later by setOutputDevices())
677 return getNewOutputDevices(mPrimaryOutput, fromCache);
678}
679
680status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
681{
François Gaffiedb1755b2023-09-01 11:50:35 +0200682 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100683 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
684 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
685 }
686 return INVALID_OPERATION;
687}
688
689status_t AudioPolicyManager::updateCallRoutingInternal(
690 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700691{
692 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100693 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700694 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200695 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700696 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100697 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700698 }
François Gaffie11d30102018-11-02 16:09:09 +0100699
Francois Gaffie716e1432019-01-14 16:58:59 +0100700 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100701 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200702
703 disconnectTelephonyAudioSource(mCallRxSourceClient);
704 disconnectTelephonyAudioSource(mCallTxSourceClient);
705
706 if (rxDevices.isEmpty()) {
707 ALOGW("%s() no selected output device", __func__);
708 return INVALID_OPERATION;
709 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000710 if (txSourceDevice == nullptr) {
711 ALOGE("%s() selected input device not available", __func__);
712 return INVALID_OPERATION;
713 }
François Gaffiec005e562018-11-06 15:04:49 +0100714
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100715 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100716 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700717
François Gaffie9eb18552018-11-05 10:33:26 +0100718 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700719 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100720 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700721 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100722 // retrieve Rx Source and Tx Sink device descriptors
723 sp<DeviceDescriptor> rxSourceDevice =
724 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
725 String8(),
726 AUDIO_FORMAT_DEFAULT);
727 sp<DeviceDescriptor> txSinkDevice =
728 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
729 String8(),
730 AUDIO_FORMAT_DEFAULT);
731
732 // RX and TX Telephony device are declared by Primary Audio HAL
733 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
734 (telephonyRxModule->getHalVersionMajor() >= 3)) {
735 if (rxSourceDevice == 0 || txSinkDevice == 0) {
736 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100737 ALOGE("%s() no telephony Tx and/or RX device", __func__);
738 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100739 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100740 // createAudioPatchInternal now supports both HW / SW bridging
741 createRxPatch = true;
742 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100743 } else {
744 // If the RX device is on the primary HW module, then use legacy routing method for
745 // voice calls via setOutputDevice() on primary output.
746 // Otherwise, create two audio patches for TX and RX path.
747 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
748 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700749 // If the TX device is also on the primary HW module, setOutputDevice() will take care
750 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100751 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
752 (txSinkDevice != 0);
753 }
754 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
755 // Otherwise, create two audio patches for TX and RX path.
756 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200757 if (!hasPrimaryOutput()) {
758 ALOGW("%s() no primary output available", __func__);
759 return INVALID_OPERATION;
760 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530761 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700762 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200763 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800764 // If the TX device is on the primary HW module but RX device is
765 // on other HW module, SinkMetaData of telephony input should handle it
766 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700767 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700768 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100769 // terminate active capture if on the same HW module as the call TX source device
770 // FIXME: would be better to refine to only inputs whose profile connects to the
771 // call TX device but this information is not in the audio patch and logic here must be
772 // symmetric to the one in startInput()
773 for (const auto& activeDesc : mInputs.getActiveInputs()) {
774 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
775 closeActiveClients(activeDesc);
776 }
777 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200778 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800779 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100780 if (waitMs != nullptr) {
781 *waitMs = muteWaitMs;
782 }
783 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800784}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700785
Mikhail Naganov100f0122018-11-29 11:22:16 -0800786bool AudioPolicyManager::isDeviceOfModule(
787 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
788 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
789 if (module != 0) {
790 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
791 .indexOf(devDesc) != NAME_NOT_FOUND
792 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
793 .indexOf(devDesc) != NAME_NOT_FOUND;
794 }
795 return false;
796}
797
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200798void AudioPolicyManager::connectTelephonyRxAudioSource()
799{
Francois Gaffie601801d2021-06-22 13:27:39 +0200800 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200801 const struct audio_port_config source = {
802 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
803 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
804 };
805 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100806
807 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
808 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
809 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
810 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200811 ALOGE_IF(mCallRxSourceClient == nullptr,
812 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200813}
814
Francois Gaffie601801d2021-06-22 13:27:39 +0200815void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200816{
Francois Gaffie601801d2021-06-22 13:27:39 +0200817 if (clientDesc == nullptr) {
818 return;
819 }
820 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
821 "%s error stopping audio source", __func__);
822 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200823}
824
825void AudioPolicyManager::connectTelephonyTxAudioSource(
826 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
827 uint32_t delayMs)
828{
Francois Gaffie601801d2021-06-22 13:27:39 +0200829 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200830 if (srcDevice == nullptr || sinkDevice == nullptr) {
831 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
832 return;
833 }
834 PatchBuilder patchBuilder;
835 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
836 ALOGV("%s between source %s and sink %s", __func__,
837 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200838 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200839 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
840
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200841 struct audio_port_config source = {};
842 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100843 mCallTxSourceClient = new SourceClientDescriptor(
844 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
845 mCommunnicationStrategy, toVolumeSource(aa), true);
846 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
847
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200848 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
849 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200850 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
851 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200852 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
853 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200854 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200855 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200856}
857
Eric Laurente0720872014-03-11 09:30:41 -0700858void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700859{
860 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100861 // store previous phone state for management of sonification strategy below
862 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100863 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100864
865 if (mEngine->setPhoneState(state) != NO_ERROR) {
866 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700867 return;
868 }
François Gaffie2110e042015-03-24 08:41:51 +0100869 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700870 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700871 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700872 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800873 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700874 }
875
François Gaffie2110e042015-03-24 08:41:51 +0100876 /**
877 * Switching to or from incall state or switching between telephony and VoIP lead to force
878 * routing command.
879 */
Eric Laurent74b71512019-11-06 17:21:57 -0800880 bool force = ((isStateInCall(oldState) != isStateInCall(state))
881 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700882
883 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700884 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700885
Eric Laurente552edb2014-03-10 17:42:56 -0700886 int delayMs = 0;
887 if (isStateInCall(state)) {
888 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100889 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
890 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700891 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700892 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700893 // mute media and sonification strategies and delay device switch by the largest
894 // latency of any output where either strategy is active.
895 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100896 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
897 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
898 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700899 (delayMs < (int)desc->latency()*2)) {
900 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700901 }
François Gaffiec005e562018-11-06 15:04:49 +0100902 setStrategyMute(musicStrategy, true, desc);
903 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
904 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
905 nullptr, true /*fromCache*/).types());
906 setStrategyMute(sonificationStrategy, true, desc);
907 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
908 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
909 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700910 }
911 }
912
François Gaffiedb1755b2023-09-01 11:50:35 +0200913 if (state == AUDIO_MODE_IN_CALL) {
914 (void)updateCallRouting(false /*fromCache*/, delayMs);
915 } else {
916 if (oldState == AUDIO_MODE_IN_CALL) {
917 disconnectTelephonyAudioSource(mCallRxSourceClient);
918 disconnectTelephonyAudioSource(mCallTxSourceClient);
919 }
920 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100921 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
922 // force routing command to audio hardware when ending call
923 // even if no device change is needed
924 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
925 rxDevices = mPrimaryOutput->devices();
926 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530927 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700928 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700929 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700930
jiabin3ff8d7d2022-12-13 06:27:44 +0000931 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700932 // reevaluate routing on all outputs in case tracks have been started during the call
933 for (size_t i = 0; i < mOutputs.size(); i++) {
934 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100935 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200936 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
937 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000938 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
939 // If the device is using preferred mixer attributes, the output need to reopen
940 // with default configuration when the new selected devices are different from
941 // current routing devices.
942 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
943 continue;
944 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530945 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200946 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700947 }
948 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000949 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700950
Eric Laurent96d1dda2022-03-14 17:14:19 +0100951 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
952
Eric Laurente552edb2014-03-10 17:42:56 -0700953 if (isStateInCall(state)) {
954 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700955 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800956 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700957 }
958
959 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100960 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
961 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700962}
963
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700964audio_mode_t AudioPolicyManager::getPhoneState() {
965 return mEngine->getPhoneState();
966}
967
Eric Laurente0720872014-03-11 09:30:41 -0700968void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100969 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700970{
François Gaffie2110e042015-03-24 08:41:51 +0100971 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700972 if (config == mEngine->getForceUse(usage)) {
973 return;
974 }
Eric Laurente552edb2014-03-10 17:42:56 -0700975
François Gaffie2110e042015-03-24 08:41:51 +0100976 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
977 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
978 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700979 }
François Gaffie2110e042015-03-24 08:41:51 +0100980 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
981 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
982 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700983
984 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700985 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800986
Eric Laurent22fcda22019-05-17 16:28:47 -0700987 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
988 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800989 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700990 }
991
Eric Laurentdc462862016-07-19 12:29:53 -0700992 //FIXME: workaround for truncated touch sounds
993 // to be removed when the problem is handled by system UI
994 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700995 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
996 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
997 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700998
999 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001000 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001001}
1002
Eric Laurente0720872014-03-11 09:30:41 -07001003void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001004{
1005 ALOGV("setSystemProperty() property %s, value %s", property, value);
1006}
1007
Dorin Drimusecc9f422022-03-09 17:57:40 +01001008// Find an MSD output profile compatible with the parameters passed.
1009// When "directOnly" is set, restrict search to profiles for direct outputs.
1010sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1011 const DeviceVector& devices,
1012 uint32_t samplingRate,
1013 audio_format_t format,
1014 audio_channel_mask_t channelMask,
1015 audio_output_flags_t flags,
1016 bool directOnly)
1017{
1018 flags = getRelevantFlags(flags, directOnly);
1019
1020 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1021 if (msdModule != nullptr) {
1022 // for the msd module check if there are patches to the output devices
1023 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1024 HwModuleCollection modules;
1025 modules.add(msdModule);
1026 return searchCompatibleProfileHwModules(
1027 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1028 flags, directOnly);
1029 }
1030 }
1031 return nullptr;
1032}
1033
Michael Chana94fbb22018-04-24 14:31:19 +10001034// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1035// search to profiles for direct outputs.
1036sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001037 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001038 uint32_t samplingRate,
1039 audio_format_t format,
1040 audio_channel_mask_t channelMask,
1041 audio_output_flags_t flags,
1042 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001043{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001044 flags = getRelevantFlags(flags, directOnly);
1045
1046 return searchCompatibleProfileHwModules(
1047 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1048}
1049
1050audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1051 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001052 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001053 // only retain flags that will drive the direct output profile selection
1054 // if explicitly requested
1055 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001056 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001057 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1058 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001059 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001060 return flags;
1061}
Eric Laurent861a6282015-05-18 15:40:16 -07001062
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1064 const HwModuleCollection& hwModules,
1065 const DeviceVector& devices,
1066 uint32_t samplingRate,
1067 audio_format_t format,
1068 audio_channel_mask_t channelMask,
1069 audio_output_flags_t flags,
1070 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001071 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001072 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001073 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001074 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001075 samplingRate, NULL /*updatedSamplingRate*/,
1076 format, NULL /*updatedFormat*/,
1077 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001078 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001079 continue;
1080 }
1081 // reject profiles not corresponding to a device currently available
1082 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1083 continue;
1084 }
1085 // reject profiles if connected device does not support codec
1086 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1087 continue;
1088 }
1089 if (!directOnly) {
1090 return curProfile;
1091 }
1092
1093 // when searching for direct outputs, if several profiles are compatible, give priority
1094 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001095 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001096 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001097 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001098 }
1099 profile = curProfile;
1100 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1101 break;
1102 }
Eric Laurente552edb2014-03-10 17:42:56 -07001103 }
1104 }
Eric Laurent861a6282015-05-18 15:40:16 -07001105 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001106}
1107
Eric Laurentfa0f6742021-08-17 18:39:44 +02001108sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001109 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001110{
1111 for (const auto& hwModule : mHwModules) {
1112 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001113 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001114 continue;
1115 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001116 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001117 // reject profiles not corresponding to a device currently available
1118 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1119 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1120 continue;
1121 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001122 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1123 != devices.size()) {
1124 continue;
1125 }
1126 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001127 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1128 return curProfile;
1129 }
1130 }
1131 return nullptr;
1132}
1133
Eric Laurentf4e63452017-11-06 19:31:46 +00001134audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001135{
François Gaffiec005e562018-11-06 15:04:49 +01001136 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001137
1138 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1139 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1140 // format, flags, etc. This may result in some discrepancy for functions that utilize
1141 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1142 // and AudioSystem::getOutputSamplingRate().
1143
François Gaffie11d30102018-11-02 16:09:09 +01001144 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001145 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1146 if (stream == AUDIO_STREAM_MUSIC &&
1147 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1148 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1149 }
1150 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001151
François Gaffie11d30102018-11-02 16:09:09 +01001152 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1153 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001154 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001155}
1156
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001157status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1158 const audio_attributes_t *srcAttr,
1159 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001160{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001161 if (srcAttr != NULL) {
1162 if (!isValidAttributes(srcAttr)) {
1163 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1164 __func__,
1165 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1166 srcAttr->tags);
1167 return BAD_VALUE;
1168 }
1169 *dstAttr = *srcAttr;
1170 } else {
1171 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1172 ALOGE("%s: invalid stream type", __func__);
1173 return BAD_VALUE;
1174 }
François Gaffiec005e562018-11-06 15:04:49 +01001175 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001176 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001177
1178 // Only honor audibility enforced when required. The client will be
1179 // forced to reconnect if the forced usage changes.
1180 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001181 dstAttr->flags = static_cast<audio_flags_mask_t>(
1182 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001183 }
1184
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001185 return NO_ERROR;
1186}
1187
Kevin Rocard153f92d2018-12-18 18:33:28 -08001188status_t AudioPolicyManager::getOutputForAttrInt(
1189 audio_attributes_t *resultAttr,
1190 audio_io_handle_t *output,
1191 audio_session_t session,
1192 const audio_attributes_t *attr,
1193 audio_stream_type_t *stream,
1194 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001195 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001196 audio_output_flags_t *flags,
1197 audio_port_handle_t *selectedDeviceId,
1198 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001199 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001200 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001201 bool *isSpatialized,
1202 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001203{
François Gaffiec005e562018-11-06 15:04:49 +01001204 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001205 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001206 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001207 const sp<DeviceDescriptor> requestedDevice =
1208 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1209
Eric Laurent8a1095a2019-11-08 14:44:16 -08001210 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001211 *isSpatialized = false;
1212
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001213 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1214 if (status != NO_ERROR) {
1215 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001216 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001217 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001218 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001219 }
François Gaffiec005e562018-11-06 15:04:49 +01001220 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001221
François Gaffiec005e562018-11-06 15:04:49 +01001222 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1223 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001224
Oscar Azucena873d10f2023-01-12 18:34:42 -08001225 bool usePrimaryOutputFromPolicyMixes = false;
1226
Kevin Rocard153f92d2018-12-18 18:33:28 -08001227 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1228 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1229 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001230 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001231 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1232 .channel_mask = config->channel_mask,
1233 .format = config->format,
1234 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001235 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001236 mAvailableOutputDevices, requestedDevice, primaryMix,
1237 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001238 if (status != OK) {
1239 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001240 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001241
Kevin Rocard153f92d2018-12-18 18:33:28 -08001242 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001243 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1244 && !audio_is_linear_pcm(config->format)) {
1245 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001246 return BAD_VALUE;
1247 }
1248 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001249 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001250 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1251 primaryMix->mDeviceAddress,
1252 AUDIO_FORMAT_DEFAULT);
1253 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001254 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001255 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1256 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001257 // if a direct output can be opened to deliver the track's multi-channel content to the
1258 // output rather than being downmixed by the primary output, then use this direct
1259 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1260 // mix.
1261 bool tryDirectForChannelMask = policyDesc != nullptr
1262 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1263 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001264 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001265 audio_io_handle_t newOutput;
1266 status = openDirectOutput(
1267 *stream, session, config,
1268 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001269 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001270 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001271 policyDesc = mOutputs.valueFor(newOutput);
1272 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001273 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001274 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001275 policyDesc = nullptr;
1276 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001277 }
1278 if (policyDesc != nullptr) {
1279 policyDesc->mPolicyMix = primaryMix;
1280 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001281 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1282 : AUDIO_PORT_HANDLE_NONE;
1283 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1284 // Remove direct flag as it is not on a direct output.
1285 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1286 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001287
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001288 ALOGV("getOutputForAttr() returns output %d", *output);
1289 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1290 *outputType = API_OUT_MIX_PLAYBACK;
1291 } else {
1292 *outputType = API_OUTPUT_LEGACY;
1293 }
1294 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001295 } else {
1296 if (policyMixDevice != nullptr) {
1297 ALOGE("%s, try to use primary mix but no output found", __func__);
1298 return INVALID_OPERATION;
1299 }
1300 // Fallback to default engine selection as the selected primary mix device is not
1301 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001302 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001303 }
François Gaffiec005e562018-11-06 15:04:49 +01001304 // Virtual sources must always be dynamicaly or explicitly routed
1305 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1306 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1307 return BAD_VALUE;
1308 }
1309 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1310 // in order to let the choice of the order to future vendor engine
1311 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001312
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001313 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001314 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001315 }
1316
Nadav Barb2f18162018-07-18 13:01:53 +03001317 // Set incall music only if device was explicitly set, and fallback to the device which is
1318 // chosen by the engine if not.
1319 // FIXME: provide a more generic approach which is not device specific and move this back
1320 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001321 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001322 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001323 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001324 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001325 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001326 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001327 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001328 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001329 }
1330 }
1331
François Gaffiec005e562018-11-06 15:04:49 +01001332 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1333 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1334 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001335
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001336 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001337 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001338 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001339 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001340 ALOGV("%s() Using MSD devices %s instead of devices %s",
1341 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001342 } else {
1343 *output = AUDIO_IO_HANDLE_NONE;
1344 }
1345 }
1346 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001347 sp<PreferredMixerAttributesInfo> info = nullptr;
1348 if (outputDevices.size() == 1) {
1349 info = getPreferredMixerAttributesInfo(
1350 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001351 mEngine->getProductStrategyForAttributes(*resultAttr),
1352 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001353 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1354 // and it is currently active.
1355 if (info != nullptr && info->getUid() != uid &&
1356 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1357 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001358 info = nullptr;
1359 }
1360 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001361 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001362 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001363 // The client will be active if the client is currently preferred mixer owner and the
1364 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001365 *isBitPerfect = (info != nullptr
1366 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001367 && info->getUid() == uid
1368 && *output != AUDIO_IO_HANDLE_NONE
1369 // When bit-perfect output is selected for the preferred mixer attributes owner,
1370 // only need to consider the config matches.
1371 && mOutputs.valueFor(*output)->isConfigurationMatched(
1372 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001373 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001374 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001375 AudioProfileVector profiles;
1376 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1377 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001378 const auto channels = profiles[0]->getChannels();
1379 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1380 config->channel_mask = *channels.begin();
1381 }
1382 const auto sampleRates = profiles[0]->getSampleRates();
1383 if (!sampleRates.empty() &&
1384 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1385 config->sample_rate = *sampleRates.begin();
1386 }
jiabinf1c73972022-04-14 16:28:52 -07001387 config->format = profiles[0]->getFormat();
1388 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001389 return INVALID_OPERATION;
1390 }
Paul McLeanaa981192015-03-21 09:55:15 -07001391
François Gaffiec005e562018-11-06 15:04:49 +01001392 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001393 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001394 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001395 *selectedDeviceId = outputDevice->getId();
1396 break;
1397 }
1398 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001399
Eric Laurent8a1095a2019-11-08 14:44:16 -08001400 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1401 *outputType = API_OUTPUT_TELEPHONY_TX;
1402 } else {
1403 *outputType = API_OUTPUT_LEGACY;
1404 }
1405
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001406 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1407
1408 return NO_ERROR;
1409}
1410
1411status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1412 audio_io_handle_t *output,
1413 audio_session_t session,
1414 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001415 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001416 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001417 audio_output_flags_t *flags,
1418 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001419 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001420 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001421 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001422 bool *isSpatialized,
1423 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001424{
1425 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1426 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1427 return INVALID_OPERATION;
1428 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001429 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001430 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001431 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001432 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001433 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001434 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001435 const sp<DeviceDescriptor> requestedDevice =
1436 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1437
1438 // Prevent from storing invalid requested device id in clients
1439 const audio_port_handle_t sanitizedRequestedPortId =
1440 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1441 *selectedDeviceId = sanitizedRequestedPortId;
1442
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001443 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001444 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001445 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1446 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001447 if (status != NO_ERROR) {
1448 return status;
1449 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001450 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001451 if (secondaryOutputs != nullptr) {
1452 for (auto &secondaryMix : secondaryMixes) {
1453 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1454 if (outputDesc != nullptr &&
1455 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1456 secondaryOutputs->push_back(outputDesc->mIoHandle);
1457 weakSecondaryOutputDescs.push_back(outputDesc);
1458 }
1459 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001460 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001461
Eric Laurent8fc147b2018-07-22 19:13:55 -07001462 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001463 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001464 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001465 };
jiabin4ef93452019-09-10 14:29:54 -07001466 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001467
Eric Laurentc209fe42020-06-05 18:11:23 -07001468 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001469 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001470 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001471 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001472 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001473 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001474 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001475 std::move(weakSecondaryOutputDescs),
1476 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001477 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001478
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001479 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1480 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001481
Eric Laurente83b55d2014-11-14 10:06:21 -08001482 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001483}
1484
Eric Laurentc529cf62020-04-17 18:19:10 -07001485status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1486 audio_session_t session,
1487 const audio_config_t *config,
1488 audio_output_flags_t flags,
1489 const DeviceVector &devices,
1490 audio_io_handle_t *output) {
1491
1492 *output = AUDIO_IO_HANDLE_NONE;
1493
1494 // skip direct output selection if the request can obviously be attached to a mixed output
1495 // and not explicitly requested
1496 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1497 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1498 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1499 return NAME_NOT_FOUND;
1500 }
1501
1502 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1503 // This prevents creating an offloaded track and tearing it down immediately after start
1504 // when audioflinger detects there is an active non offloadable effect.
1505 // FIXME: We should check the audio session here but we do not have it in this context.
1506 // This may prevent offloading in rare situations where effects are left active by apps
1507 // in the background.
1508 sp<IOProfile> profile;
1509 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1510 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1511 profile = getProfileForOutput(
1512 devices, config->sample_rate, config->format, config->channel_mask,
1513 flags, true /* directOnly */);
1514 }
1515
1516 if (profile == nullptr) {
1517 return NAME_NOT_FOUND;
1518 }
1519
1520 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1521 for (size_t i = 0; i < mOutputs.size(); i++) {
1522 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1523 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1524 // reuse direct output if currently open by the same client
1525 // and configured with same parameters
1526 if ((config->sample_rate == desc->getSamplingRate()) &&
1527 (config->format == desc->getFormat()) &&
1528 (config->channel_mask == desc->getChannelMask()) &&
1529 (session == desc->mDirectClientSession)) {
1530 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001531 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001532 mOutputs.keyAt(i), session);
1533 *output = mOutputs.keyAt(i);
1534 return NO_ERROR;
1535 }
1536 }
1537 }
1538
1539 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001540 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1541 return NAME_NOT_FOUND;
1542 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1543 // MMAP gracefully handles lack of an exclusive track resource by mixing
1544 // above the audio framework. For AAudio to know that the limit is reached,
1545 // return an error.
1546 return NAME_NOT_FOUND;
1547 } else {
1548 // Close outputs on this profile, if available, to free resources for this request
1549 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1550 const auto desc = mOutputs.valueAt(i);
1551 if (desc->mProfile == profile) {
1552 closeOutput(desc->mIoHandle);
1553 }
1554 }
1555 }
1556 }
1557
1558 // Unable to close streams to find free resources for this request
1559 if (!profile->canOpenNewIo()) {
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 Yao4c3af932024-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 Yao4c3af932024-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 Yao923b3a02024-04-05 22:50:56 +00002090 const bool hasOrphanHaptic =
2091 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002092 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2093 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2094 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002095
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002096 for (audio_io_handle_t output : outputs) {
2097 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002098 // matching criteria values in priority order for current output
2099 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002100
Eric Laurent16c66dd2019-05-01 17:54:10 -07002101 if (outputDesc->isDuplicated()) {
2102 continue;
2103 }
2104 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2105 continue;
2106 }
Eric Laurent8838a382014-09-08 16:44:28 -07002107
Eric Laurent16c66dd2019-05-01 17:54:10 -07002108 // If haptic channel is specified, use the haptic output if present.
2109 // When using haptic output, same audio format and sample rate are required.
2110 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002111 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao923b3a02024-04-05 22:50:56 +00002112 // skip if haptic channel specified but output does not support it, or output support haptic
2113 // but there is no haptic channel requested AND no orphan haptic effect exist
2114 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2115 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002116 continue;
2117 }
Shunkai Yao923b3a02024-04-05 22:50:56 +00002118 // In the case of audio-coupled-haptic playback, there is no format conversion and
2119 // resampling in the framework, same format/channel/sampleRate for client and the output
2120 // thread is required. In the case of HapticGenerator effect, do not require format
2121 // matching.
2122 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2123 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002124 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao923b3a02024-04-05 22:50:56 +00002125 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002126 }
2127
2128 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002129 const int matchingFunctionalFlags =
2130 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2131 const int totalFunctionalFlags =
2132 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2133 // Prefer matching functional flags, but subtract unnecessary functional flags.
2134 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002135
2136 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002137 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2138 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002139 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2140 channelCount <= outputChannelCount) {
2141 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002142 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2143 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002144 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002145 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002146 currentMatchCriteria[3] = outputChannelCount;
2147 }
2148
2149 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002150 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002151 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002152 }
2153
2154 // performance flags match
2155 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2156
2157 // format match
2158 if (format != AUDIO_FORMAT_INVALID) {
2159 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002160 PolicyAudioPort::kFormatDistanceMax -
2161 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002162 }
2163
2164 // primary output match
2165 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2166
2167 // compare match criteria by priority then value
2168 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2169 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2170 bestMatchCriteria = currentMatchCriteria;
2171 bestOutput = output;
2172
2173 std::stringstream result;
2174 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2175 std::ostream_iterator<int>(result, " "));
2176 ALOGV("%s new bestOutput %d criteria %s",
2177 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002178 }
2179 }
2180
Eric Laurent16c66dd2019-05-01 17:54:10 -07002181 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002182}
2183
Eric Laurent8fc147b2018-07-22 19:13:55 -07002184status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002185{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002186 ALOGV("%s portId %d", __FUNCTION__, portId);
2187
2188 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2189 if (outputDesc == 0) {
2190 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002191 return BAD_VALUE;
2192 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002193 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002194
Eric Laurent8fc147b2018-07-22 19:13:55 -07002195 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002196 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002197
Eric Laurent733ce942017-12-07 12:18:25 -08002198 status_t status = outputDesc->start();
2199 if (status != NO_ERROR) {
2200 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002201 }
2202
Eric Laurent97ac8712018-07-27 18:59:02 -07002203 uint32_t delayMs;
2204 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002205
2206 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002207 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002208 if (status == DEAD_OBJECT) {
2209 sp<SwAudioOutputDescriptor> desc =
2210 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2211 if (desc == nullptr) {
2212 // This is not common, it may indicate something wrong with the HAL.
2213 ALOGE("%s unable to open output with default config", __func__);
2214 return status;
2215 }
2216 desc->mUsePreferredMixerAttributes = true;
2217 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002218 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002219 }
jiabina84c3d32022-12-02 18:59:55 +00002220
2221 // If the client is the first one active on preferred mixer parameters, reopen the output
2222 // if the current mixer parameters doesn't match the preferred one.
2223 if (outputDesc->devices().size() == 1) {
2224 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2225 outputDesc->devices()[0]->getId(), client->strategy());
2226 if (info != nullptr && info->getUid() == client->uid()) {
2227 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2228 info->getConfigBase(), info->getFlags())) {
2229 stopSource(outputDesc, client);
2230 outputDesc->stop();
2231 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2232 config.channel_mask = info->getConfigBase().channel_mask;
2233 config.sample_rate = info->getConfigBase().sample_rate;
2234 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002235 sp<SwAudioOutputDescriptor> desc =
2236 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2237 if (desc == nullptr) {
2238 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002239 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002240 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002241 // Intentionally return error to let the client side resending request for
2242 // creating and starting.
2243 return DEAD_OBJECT;
2244 }
2245 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002246 if (info->getActiveClientCount() == 1 &&
2247 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2248 // If it is first bit-perfect client, reroute all clients that will be routed to
2249 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2250 PortHandleVector clientsToInvalidate;
2251 for (size_t i = 0; i < mOutputs.size(); i++) {
2252 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002253 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002254 continue;
2255 }
2256 for (const auto& c : mOutputs[i]->getClientIterable()) {
2257 clientsToInvalidate.push_back(c->portId());
2258 }
2259 }
2260 if (!clientsToInvalidate.empty()) {
2261 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2262 __func__);
2263 mpClientInterface->invalidateTracks(clientsToInvalidate);
2264 }
2265 }
jiabina84c3d32022-12-02 18:59:55 +00002266 }
2267 }
2268
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002269 if (client->hasPreferredDevice()) {
2270 // playback activity with preferred device impacts routing occurred, inform upper layers
2271 mpClientInterface->onRoutingUpdated();
2272 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002273 if (delayMs != 0) {
2274 usleep(delayMs * 1000);
2275 }
2276
2277 return status;
2278}
2279
Eric Laurent96d1dda2022-03-14 17:14:19 +01002280bool AudioPolicyManager::isLeUnicastActive() const {
2281 if (isInCall()) {
2282 return true;
2283 }
2284 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2285}
2286
2287bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2288 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2289 return false;
2290 }
2291 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2292 ALOGV("%s active %d", __func__, active);
2293 return active;
2294}
2295
Eric Laurent97ac8712018-07-27 18:59:02 -07002296status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2297 const sp<TrackClientDescriptor>& client,
2298 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002299{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002300 // cannot start playback of STREAM_TTS if any other output is being used
2301 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002302
2303 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002304 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002305 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002306 auto clientStrategy = client->strategy();
2307 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002308 if (stream == AUDIO_STREAM_TTS) {
2309 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002310 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002311 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002312 return INVALID_OPERATION;
2313 } else {
2314 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2315 }
2316 } else {
2317 // some playback other than beacon starts
2318 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2319 }
2320
Eric Laurent77305a62016-07-25 16:39:22 -07002321 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002322 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002323 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002324
François Gaffie11d30102018-11-02 16:09:09 +01002325 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002326 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002327 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002328 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002329 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002330 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002331 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002332 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002333 } else {
2334 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002335 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002336 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2337 AUDIO_FORMAT_DEFAULT);
2338 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2339 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002340 }
2341
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002342 // requiresMuteCheck is false when we can bypass mute strategy.
2343 // It covers a common case when there is no materially active audio
2344 // and muting would result in unnecessary delay and dropped audio.
2345 const uint32_t outputLatencyMs = outputDesc->latency();
2346 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002347 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002348
Eric Laurente552edb2014-03-10 17:42:56 -07002349 // increment usage count for this stream on the requested output:
2350 // NOTE that the usage count is the same for duplicated output and hardware output which is
2351 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002352 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002353
2354 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002355 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002356 // Preferred device may be exclusive, use only if no other active clients on this output
2357 devices = DeviceVector(
2358 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2359 } else {
2360 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2361 }
François Gaffie11d30102018-11-02 16:09:09 +01002362 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002363 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002364 }
2365 }
Eric Laurente552edb2014-03-10 17:42:56 -07002366
François Gaffiec005e562018-11-06 15:04:49 +01002367 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002368 selectOutputForMusicEffects();
2369 }
2370
François Gaffie1c878552018-11-22 16:53:21 +01002371 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002372 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002373 if (devices.isEmpty()) {
2374 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002375 }
François Gaffiec005e562018-11-06 15:04:49 +01002376 bool shouldWait =
2377 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2378 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2379 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002380 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002381 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002382 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002383 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002384 // An output has a shared device if
2385 // - managed by the same hw module
2386 // - supports the currently selected device
2387 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002388 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002389
Eric Laurent77305a62016-07-25 16:39:22 -07002390 // force a device change if any other output is:
2391 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002392 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002393 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002394 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002395 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002396 // change the device currently selected by the other output.
2397 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002398 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002399 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002400 force = true;
2401 }
2402 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002403 // a notification so that audio focus effect can propagate, or that a mute/unmute
2404 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002405 const uint32_t latencyMs = desc->latency();
2406 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2407
2408 if (shouldWait && isActive && (waitMs < latencyMs)) {
2409 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002410 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002411
2412 // Require mute check if another output is on a shared device
2413 // and currently active to have proper drain and avoid pops.
2414 // Note restoring AudioTracks onto this output needs to invoke
2415 // a volume ramp if there is no mute.
2416 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002417 }
2418 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002419
jiabin3ff8d7d2022-12-13 06:27:44 +00002420 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2421 // If the output is open with preferred mixer attributes, but the routed device is
2422 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2423 // changed.
2424 return DEAD_OBJECT;
2425 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002426 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302427 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2428 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002429
Eric Laurente552edb2014-03-10 17:42:56 -07002430 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002431 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002432 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002433 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002434 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002435 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002436 outputDesc->useHwGain() /*force*/)) {
2437 // request AudioService to reinitialize the volume curves asynchronously
2438 ALOGE("checkAndSetVolume failed, requesting volume range init");
2439 mpClientInterface->onVolumeRangeInitRequest();
2440 };
Eric Laurente552edb2014-03-10 17:42:56 -07002441
2442 // update the outputs if starting an output with a stream that can affect notification
2443 // routing
2444 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002445
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002446 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002447 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002448 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002449 }
Eric Laurentdc462862016-07-19 12:29:53 -07002450
2451 if (waitMs > muteWaitMs) {
2452 *delayMs = waitMs - muteWaitMs;
2453 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002454
2455 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2456 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2457 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2458 // change occurs after the MixerThread starts and causes a stream volume
2459 // glitch.
2460 //
2461 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002462 }
Eric Laurentdc462862016-07-19 12:29:53 -07002463
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002464 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002465 mEngine->getForceUse(
2466 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002467 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002468 }
2469
Eric Laurent97ac8712018-07-27 18:59:02 -07002470 // Automatically enable the remote submix input when output is started on a re routing mix
2471 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002472 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2473 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002474 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2475 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2476 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002477 "remote-submix",
2478 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002479 }
2480
Eric Laurent96d1dda2022-03-14 17:14:19 +01002481 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2482
Eric Laurente552edb2014-03-10 17:42:56 -07002483 return NO_ERROR;
2484}
2485
Eric Laurent96d1dda2022-03-14 17:14:19 +01002486void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2487 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2488 bool isUnicastActive = isLeUnicastActive();
2489
2490 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002491 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002492 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2493 for (size_t i = 0; i < mOutputs.size(); i++) {
2494 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2495 if (desc != ignoredOutput && desc->isActive()
2496 && ((isUnicastActive &&
2497 !desc->devices().
2498 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2499 || (wasUnicastActive &&
2500 !desc->devices().getDevicesFromTypes(
2501 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2502 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2503 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002504 if (desc->mUsePreferredMixerAttributes && force) {
2505 // If the device is using preferred mixer attributes, the output need to reopen
2506 // with default configuration when the new selected devices are different from
2507 // current routing devices.
2508 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2509 continue;
2510 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302511 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002512 // re-apply device specific volume if not done by setOutputDevice()
2513 if (!force) {
2514 applyStreamVolumes(desc, newDevices.types(), delayMs);
2515 }
2516 }
2517 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002518 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002519 }
2520}
2521
Eric Laurent8fc147b2018-07-22 19:13:55 -07002522status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002523{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002524 ALOGV("%s portId %d", __FUNCTION__, portId);
2525
2526 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2527 if (outputDesc == 0) {
2528 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002529 return BAD_VALUE;
2530 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002531 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002532
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002533 if (client->hasPreferredDevice(true)) {
2534 // playback activity with preferred device impacts routing occurred, inform upper layers
2535 mpClientInterface->onRoutingUpdated();
2536 }
2537
Eric Laurent97ac8712018-07-27 18:59:02 -07002538 ALOGV("stopOutput() output %d, stream %d, session %d",
2539 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002540
Eric Laurent97ac8712018-07-27 18:59:02 -07002541 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002542
Eric Laurent733ce942017-12-07 12:18:25 -08002543 if (status == NO_ERROR ) {
2544 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002545 } else {
2546 return status;
2547 }
2548
2549 if (outputDesc->devices().size() == 1) {
2550 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2551 outputDesc->devices()[0]->getId(), client->strategy());
2552 if (info != nullptr && info->getUid() == client->uid()) {
2553 info->decreaseActiveClient();
2554 if (info->getActiveClientCount() == 0) {
2555 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2556 }
2557 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002558 }
2559 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002560}
2561
Eric Laurent97ac8712018-07-27 18:59:02 -07002562status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2563 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002564{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002565 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002566 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002567 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002568 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002569
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002570 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2571
François Gaffie1c878552018-11-22 16:53:21 +01002572 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2573 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002574 // Automatically disable the remote submix input when output is stopped on a
2575 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002576 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002577 if (isSingleDeviceType(
2578 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002579 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002580 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002581 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2582 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002583 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002584 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002585 }
2586 }
2587 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002588 if (client->hasPreferredDevice(true) &&
2589 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002590 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002591 forceDeviceUpdate = true;
2592 }
2593
Eric Laurente552edb2014-03-10 17:42:56 -07002594 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002595 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002596
Eric Laurente552edb2014-03-10 17:42:56 -07002597 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002598 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002599 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002600 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002601
2602 // If the routing does not change, if an output is routed on a device using HwGain
2603 // (aka setAudioPortConfig) and there are still active clients following different
2604 // volume group(s), force reapply volume
2605 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2606 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2607
Eric Laurente552edb2014-03-10 17:42:56 -07002608 // delay the device switch by twice the latency because stopOutput() is executed when
2609 // the track stop() command is received and at that time the audio track buffer can
2610 // still contain data that needs to be drained. The latency only covers the audio HAL
2611 // and kernel buffers. Also the latency does not always include additional delay in the
2612 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302613 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002614 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002615
2616 // force restoring the device selection on other active outputs if it differs from the
2617 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002618 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002619 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002620 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002621 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002622 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002623 desc->isActive() &&
2624 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002625 (newDevices != desc->devices())) {
2626 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2627 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002628
jiabin3ff8d7d2022-12-13 06:27:44 +00002629 if (desc->mUsePreferredMixerAttributes && force) {
2630 // If the device is using preferred mixer attributes, the output need to
2631 // reopen with default configuration when the new selected devices are
2632 // different from current routing devices.
2633 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2634 continue;
2635 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302636 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002637
Eric Laurent57de36c2016-09-28 16:59:11 -07002638 // re-apply device specific volume if not done by setOutputDevice()
2639 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002640 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002641 }
Eric Laurente552edb2014-03-10 17:42:56 -07002642 }
2643 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002644 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002645 // update the outputs if stopping one with a stream that can affect notification routing
2646 handleNotificationRoutingForStream(stream);
2647 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002648
2649 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2650 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002651 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002652 }
2653
François Gaffiec005e562018-11-06 15:04:49 +01002654 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002655 selectOutputForMusicEffects();
2656 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002657
2658 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2659
Eric Laurente552edb2014-03-10 17:42:56 -07002660 return NO_ERROR;
2661 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002662 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002663 return INVALID_OPERATION;
2664 }
2665}
2666
jiabinbce0c1d2020-10-05 11:20:18 -07002667bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002668{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002669 ALOGV("%s portId %d", __FUNCTION__, portId);
2670
2671 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2672 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002673 // If an output descriptor is closed due to a device routing change,
2674 // then there are race conditions with releaseOutput from tracks
2675 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2676 // destroyed shortly thereafter.
2677 //
2678 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002679 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002680 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002681 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002682
2683 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002684
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302685 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2686 if (outputDesc->isClientActive(client)) {
2687 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2688 stopOutput(portId);
2689 }
2690
Eric Laurent8fc147b2018-07-22 19:13:55 -07002691 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2692 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002693 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002694 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002695 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002696 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002697 if (--outputDesc->mDirectOpenCount == 0) {
2698 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002699 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002700 }
2701 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302702
Andy Hung39efb7a2018-09-26 15:39:28 -07002703 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002704 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2705 // The output is pending reopened to query dynamic profiles and
2706 // there is no active clients
2707 closeOutput(outputDesc->mIoHandle);
2708 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2709 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2710 if (newOutputDesc == nullptr) {
2711 ALOGE("%s failed to open output", __func__);
2712 }
2713 return true;
2714 }
2715 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002716}
2717
Eric Laurentcaf7f482014-11-25 17:50:47 -08002718status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2719 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002720 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002721 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002722 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002723 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002724 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002725 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002726 input_type_t *inputType,
2727 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002728{
François Gaffiec005e562018-11-06 15:04:49 +01002729 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002730 "flags %#x attributes=%s requested device ID %d",
2731 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2732 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002733
Eric Laurentad2e7b92017-09-14 20:06:42 -07002734 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002735 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002736 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002737 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002738 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002739 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002740 sp<RecordClientDescriptor> clientDesc;
2741 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002742 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002743 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002744
2745 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2746 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2747 return INVALID_OPERATION;
2748 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002749
Francois Gaffie716e1432019-01-14 16:58:59 +01002750 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2751 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002752 }
2753
Paul McLean466dc8e2015-04-17 13:15:36 -06002754 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002755 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002756 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002757
Eric Laurentad2e7b92017-09-14 20:06:42 -07002758 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2759 // possible
2760 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2761 *input != AUDIO_IO_HANDLE_NONE) {
2762 ssize_t index = mInputs.indexOfKey(*input);
2763 if (index < 0) {
2764 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2765 status = BAD_VALUE;
2766 goto error;
2767 }
2768 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002769 RecordClientVector clients = inputDesc->getClientsForSession(session);
2770 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002771 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2772 status = BAD_VALUE;
2773 goto error;
2774 }
2775 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2776 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002777 // corresponds to a new client and is only permitted from the same UID.
2778 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002779 if (clients.size() > 1) {
2780 for (const auto& client : clients) {
2781 // The client map is ordered by key values (portId) and portIds are allocated
2782 // incrementaly. So the first client in this list is the one opened by audio flinger
2783 // when the mmap stream is created and should be ignored as it does not correspond
2784 // to an actual client
2785 if (client == *clients.cbegin()) {
2786 continue;
2787 }
2788 if (uid != client->uid() && !client->isSilenced()) {
2789 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2790 uid, client->portId(), client->uid());
2791 status = INVALID_OPERATION;
2792 goto error;
2793 }
Eric Laurent331679c2018-04-16 17:03:16 -07002794 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002795 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002796 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002797 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002798
Eric Laurentfecbceb2021-02-09 14:46:43 +01002799 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002800 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002801 }
2802
2803 *input = AUDIO_IO_HANDLE_NONE;
2804 *inputType = API_INPUT_INVALID;
2805
Francois Gaffie716e1432019-01-14 16:58:59 +01002806 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002807 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002808 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002809 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002810 ALOGW("%s could not find input mix for attr %s",
2811 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002812 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002813 }
jiabinc1de2df2019-05-07 14:26:40 -07002814 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2815 String8(attr->tags + strlen("addr=")),
2816 AUDIO_FORMAT_DEFAULT);
2817 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002818 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002819 __func__, attributes.source, attributes.tags);
2820 status = BAD_VALUE;
2821 goto error;
2822 }
2823
Kevin Rocard25f9b052019-02-27 15:08:54 -08002824 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2825 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2826 } else {
2827 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2828 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002829 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002830 if (explicitRoutingDevice != nullptr) {
2831 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002832 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002833 // Prevent from storing invalid requested device id in clients
2834 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002835 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002836 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2837 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002838 }
François Gaffie11d30102018-11-02 16:09:09 +01002839 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002840 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002841 status = BAD_VALUE;
2842 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002843 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002844 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2845 *inputType = API_INPUT_MIX_CAPTURE;
2846 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002847 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2848 // there is an external policy, but this input is attached to a mix of recorders,
2849 // meaning it receives audio injected into the framework, so the recorder doesn't
2850 // know about it and is therefore considered "legacy"
2851 *inputType = API_INPUT_LEGACY;
2852 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002853 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002854 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002855 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002856 } else {
2857 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002858 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002859
Eric Laurent599c7582015-12-07 18:05:55 -08002860 }
2861
François Gaffiec005e562018-11-06 15:04:49 +01002862 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002863 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002864 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002865 AudioProfileVector profiles;
2866 status_t ret = getProfilesForDevices(
2867 DeviceVector(device), profiles, flags, true /*isInput*/);
2868 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002869 const auto channels = profiles[0]->getChannels();
2870 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2871 config->channel_mask = *channels.begin();
2872 }
2873 const auto sampleRates = profiles[0]->getSampleRates();
2874 if (!sampleRates.empty() &&
2875 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2876 config->sample_rate = *sampleRates.begin();
2877 }
jiabinf1c73972022-04-14 16:28:52 -07002878 config->format = profiles[0]->getFormat();
2879 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002880 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002881 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002882
Eric Laurent8f42ea12018-08-08 09:08:25 -07002883exit:
2884
François Gaffiec005e562018-11-06 15:04:49 +01002885 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2886 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002887
Francois Gaffie716e1432019-01-14 16:58:59 +01002888 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002889 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002890 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002891
Mikhail Naganov2996f672019-04-18 12:29:59 -07002892 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002893 requestedDeviceId, attributes.source, flags,
2894 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002895 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002896 // Move (if found) effect for the client session to its input
2897 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002898 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002899
2900 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2901 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002902
Eric Laurent599c7582015-12-07 18:05:55 -08002903 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002904
2905error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002906 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002907}
2908
2909
François Gaffie11d30102018-11-02 16:09:09 +01002910audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002911 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002912 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002913 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002914 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002915 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002916{
2917 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002918 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002919 bool isSoundTrigger = false;
2920
François Gaffiec005e562018-11-06 15:04:49 +01002921 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002922 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2923 if (index >= 0) {
2924 input = mSoundTriggerSessions.valueFor(session);
2925 isSoundTrigger = true;
2926 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2927 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2928 } else {
2929 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002930 }
François Gaffiec005e562018-11-06 15:04:49 +01002931 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002932 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002933 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002934 }
2935
Carter Hsua3abb402021-10-26 11:11:20 +08002936 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2937 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2938 }
2939
Eric Laurentfe231122017-11-17 17:48:06 -08002940 // sampling rate and flags may be updated by getInputProfile
2941 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2942 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002943 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002944 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002945 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002946 // find a compatible input profile (not necessarily identical in parameters)
2947 sp<IOProfile> profile = getInputProfile(
2948 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2949 if (profile == nullptr) {
2950 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002951 }
jiabin2fd710d2022-05-02 23:20:22 +00002952
Glenn Kasten05ddca52016-02-11 08:17:12 -08002953 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002954 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002955 if (samplingRate == 0) {
2956 samplingRate = profileSamplingRate;
2957 }
Eric Laurente552edb2014-03-10 17:42:56 -07002958
Eric Laurent322b4d22015-04-03 15:57:54 -07002959 if (profile->getModuleHandle() == 0) {
2960 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002961 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002962 }
2963
Eric Laurentec376dc2021-04-08 20:41:22 +02002964 // Reuse an already opened input if a client with the same session ID already exists
2965 // on that input
2966 for (size_t i = 0; i < mInputs.size(); i++) {
2967 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2968 if (desc->mProfile != profile) {
2969 continue;
2970 }
2971 RecordClientVector clients = desc->clientsList();
2972 for (const auto &client : clients) {
2973 if (session == client->session()) {
2974 return desc->mIoHandle;
2975 }
2976 }
2977 }
2978
Eric Laurent3974e3b2017-12-07 17:58:43 -08002979 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002980 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002981 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002982 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002983 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002984 continue;
2985 }
2986 // if sound trigger, reuse input if used by other sound trigger on same session
2987 // else
2988 // reuse input if active client app is not in IDLE state
2989 //
2990 RecordClientVector clients = desc->clientsList();
2991 bool doClose = false;
2992 for (const auto& client : clients) {
2993 if (isSoundTrigger != client->isSoundTrigger()) {
2994 continue;
2995 }
2996 if (client->isSoundTrigger()) {
2997 if (session == client->session()) {
2998 return desc->mIoHandle;
2999 }
3000 continue;
3001 }
3002 if (client->active() && client->appState() != APP_STATE_IDLE) {
3003 return desc->mIoHandle;
3004 }
3005 doClose = true;
3006 }
3007 if (doClose) {
3008 closeInput(desc->mIoHandle);
3009 } else {
3010 i++;
3011 }
3012 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003013 }
3014
Eric Laurentfe231122017-11-17 17:48:06 -08003015 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003016
Eric Laurentfe231122017-11-17 17:48:06 -08003017 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3018 lConfig.sample_rate = profileSamplingRate;
3019 lConfig.channel_mask = profileChannelMask;
3020 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003021
François Gaffie11d30102018-11-02 16:09:09 +01003022 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003023
3024 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003025 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003026 (profileSamplingRate != lConfig.sample_rate) ||
3027 !audio_formats_match(profileFormat, lConfig.format) ||
3028 (profileChannelMask != lConfig.channel_mask)) {
3029 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003030 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003031 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003032 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003033 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003034 }
Eric Laurent599c7582015-12-07 18:05:55 -08003035 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003036 }
3037
Eric Laurentc722f302014-12-10 11:21:49 -08003038 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003039
Eric Laurent599c7582015-12-07 18:05:55 -08003040 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003041 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003042
Eric Laurent599c7582015-12-07 18:05:55 -08003043 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003044}
3045
Eric Laurent4eb58f12018-12-07 16:41:02 -08003046status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003047{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003048 ALOGV("%s portId %d", __FUNCTION__, portId);
3049
3050 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3051 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003052 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003053 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003054 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003055 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003056 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003057 if (client->active()) {
3058 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3059 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003060 }
3061
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 audio_session_t session = client->session();
3063
Eric Laurent4eb58f12018-12-07 16:41:02 -08003064 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003065
Eric Laurent4eb58f12018-12-07 16:41:02 -08003066 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003067
Eric Laurent4eb58f12018-12-07 16:41:02 -08003068 status_t status = inputDesc->start();
3069 if (status != NO_ERROR) {
3070 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003071 }
Eric Laurente552edb2014-03-10 17:42:56 -07003072
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003073 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003074 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003075 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003076
Eric Laurent8f42ea12018-08-08 09:08:25 -07003077 // indicate active capture to sound trigger service if starting capture from a mic on
3078 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003079 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003080 if (device != nullptr) {
3081 status = setInputDevice(input, device, true /* force */);
3082 } else {
3083 ALOGW("%s no new input device can be found for descriptor %d",
3084 __FUNCTION__, inputDesc->getId());
3085 status = BAD_VALUE;
3086 }
Eric Laurente552edb2014-03-10 17:42:56 -07003087
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003088 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003089 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003090 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003091 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003092 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3093 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003094 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003095 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003096
François Gaffie11d30102018-11-02 16:09:09 +01003097 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3098 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003099 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003100 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003101 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003102
Eric Laurent8f42ea12018-08-08 09:08:25 -07003103 // automatically enable the remote submix output when input is started if not
3104 // used by a policy mix of type MIX_TYPE_RECORDERS
3105 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003106 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003107 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003108 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003109 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003110 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3111 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003112 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003113 if (address != "") {
3114 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3115 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003116 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003117 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003118 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003119 } else if (status != NO_ERROR) {
3120 // Restore client activity state.
3121 inputDesc->setClientActive(client, false);
3122 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003123 }
3124
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003125 ALOGV("%s input %d source = %d status = %d exit",
3126 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003127
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003128 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003129}
3130
Eric Laurent8fc147b2018-07-22 19:13:55 -07003131status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003132{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003133 ALOGV("%s portId %d", __FUNCTION__, portId);
3134
3135 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3136 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003137 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003138 return BAD_VALUE;
3139 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003140 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003141 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003142 if (!client->active()) {
3143 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003144 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003145 }
Carter Hsue6139d52021-07-08 10:30:20 +08003146 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003147 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003148
Eric Laurent8f42ea12018-08-08 09:08:25 -07003149 inputDesc->stop();
3150 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003151 auto current_source = inputDesc->source();
3152 setInputDevice(input, getNewInputDevice(inputDesc),
3153 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003154 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003155 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003156 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003157 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003158 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3159 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003160 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003161 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003162
3163 // automatically disable the remote submix output when input is stopped if not
3164 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003165 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003166 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003167 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003168 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003169 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3170 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003171 }
3172 if (address != "") {
3173 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3174 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003175 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003176 }
3177 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003178 resetInputDevice(input);
3179
3180 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3181 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003182 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3183 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003184 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003185 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003186 }
3187 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003188 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003189 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003190}
3191
Eric Laurent8fc147b2018-07-22 19:13:55 -07003192void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003193{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003194 ALOGV("%s portId %d", __FUNCTION__, portId);
3195
3196 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3197 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003198 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003199 return;
3200 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003201 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003202 audio_io_handle_t input = inputDesc->mIoHandle;
3203
Eric Laurent8f42ea12018-08-08 09:08:25 -07003204 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003205
Andy Hung39efb7a2018-09-26 15:39:28 -07003206 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003207
3208 // If no more clients are present in this session, park effects to an orphan chain
3209 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3210 if (clientsOnSession.size() == 0) {
3211 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3212 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003213 if (inputDesc->getClientCount() > 0) {
3214 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003215 return;
3216 }
3217
Eric Laurent05b90f82014-08-27 15:32:29 -07003218 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003219 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003220 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003221}
3222
Eric Laurent8f42ea12018-08-08 09:08:25 -07003223void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003224{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003225 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003226
3227 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003228 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003229 }
3230}
3231
Eric Laurent8f42ea12018-08-08 09:08:25 -07003232void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3233{
3234 stopInput(portId);
3235 releaseInput(portId);
3236}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003237
Eric Laurent0dd51852019-04-19 18:18:58 -07003238void AudioPolicyManager::checkCloseInputs() {
3239 // After connecting or disconnecting an input device, close input if:
3240 // - it has no client (was just opened to check profile) OR
3241 // - none of its supported devices are connected anymore OR
3242 // - one of its clients cannot be routed to one of its supported
3243 // devices anymore. Otherwise update device selection
3244 std::vector<audio_io_handle_t> inputsToClose;
3245 for (size_t i = 0; i < mInputs.size(); i++) {
3246 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3247 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003248 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003249 inputsToClose.push_back(mInputs.keyAt(i));
3250 } else {
3251 bool close = false;
3252 for (const auto& client : input->clientsList()) {
3253 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003254 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3255 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003256 if (!input->supportedDevices().contains(device)) {
3257 close = true;
3258 break;
3259 }
3260 }
3261 if (close) {
3262 inputsToClose.push_back(mInputs.keyAt(i));
3263 } else {
3264 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3265 }
3266 }
3267 }
3268
3269 for (const audio_io_handle_t handle : inputsToClose) {
3270 ALOGV("%s closing input %d", __func__, handle);
3271 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003272 }
Eric Laurentd4692962014-05-05 18:13:44 -07003273}
3274
François Gaffie251c7f02018-11-07 10:41:08 +01003275void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003276{
3277 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003278 if (indexMin < 0 || indexMax < 0) {
3279 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3280 return;
3281 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003282 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003283
3284 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003285 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3286 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003287 continue;
3288 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003289 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003290 }
Eric Laurente552edb2014-03-10 17:42:56 -07003291}
3292
Eric Laurente0720872014-03-11 09:30:41 -07003293status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003294 int index,
3295 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003296{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003297 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003298 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3299 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3300 return NO_ERROR;
3301 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003302 ALOGV("%s: stream %s attributes=%s", __func__,
3303 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003304 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003305}
3306
Eric Laurente0720872014-03-11 09:30:41 -07003307status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003308 int *index,
3309 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003310{
François Gaffiec005e562018-11-06 15:04:49 +01003311 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3312 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003313 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003314 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003315 deviceTypes = mEngine->getOutputDevicesForStream(
3316 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003317 }
jiabin9a3361e2019-10-01 09:38:30 -07003318 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003319}
3320
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003321status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003322 int index,
3323 audio_devices_t device)
3324{
3325 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003326 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3327 if (group == VOLUME_GROUP_NONE) {
3328 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003329 return BAD_VALUE;
3330 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003331 ALOGV("%s: group %d matching with %s index %d",
3332 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003333 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003334 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003335 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003336 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3337 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3338 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3339 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003340 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3341
3342 status = setVolumeCurveIndex(index, device, curves);
3343 if (status != NO_ERROR) {
3344 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3345 return status;
3346 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003347
jiabin9a3361e2019-10-01 09:38:30 -07003348 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003349 auto curCurvAttrs = curves.getAttributes();
3350 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3351 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003352 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003353 } else if (!curves.getStreamTypes().empty()) {
3354 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003355 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003356 } else {
3357 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3358 return BAD_VALUE;
3359 }
jiabin9a3361e2019-10-01 09:38:30 -07003360 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3361 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003362
François Gaffiecfe17322018-11-07 13:41:29 +01003363 // update volume on all outputs and streams matching the following:
3364 // - The requested stream (or a stream matching for volume control) is active on the output
3365 // - The device (or devices) selected by the engine for this stream includes
3366 // the requested device
3367 // - For non default requested device, currently selected device on the output is either the
3368 // requested device or one of the devices selected by the engine for this stream
3369 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3370 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003371 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003372 for (size_t i = 0; i < mOutputs.size(); i++) {
3373 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003374 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003375
jiabin9a3361e2019-10-01 09:38:30 -07003376 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3377 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003378 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003379
3380 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003381 continue;
3382 }
3383 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3384 curDevices.find(device) == curDevices.end()) {
3385 continue;
3386 }
3387 bool applyVolume = false;
3388 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3389 curSrcDevices.insert(device);
3390 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003391 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3392 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003393 } else {
3394 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3395 }
3396 if (!applyVolume) {
3397 continue; // next output
3398 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003399 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3400 // If a higher priority strategy is active, and the output is routed to a device with a
3401 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003402 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003403 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003404 // If the volume source is active with higher priority source, ensure at least Sw Muted
3405 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003406 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3407 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3408 false /*preferredDevice*/);
3409 if (activeClients.empty()) {
3410 continue;
3411 }
3412 bool isPreempted = false;
3413 bool isHigherPriority = productStrategy < strategy;
3414 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003415 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003416 ALOGV("%s: Strategy=%d (\nrequester:\n"
3417 " group %d, volumeGroup=%d attributes=%s)\n"
3418 " higher priority source active:\n"
3419 " volumeGroup=%d attributes=%s) \n"
3420 " on output %zu, bailing out", __func__, productStrategy,
3421 group, group, toString(attributes).c_str(),
3422 client->volumeSource(), toString(client->attributes()).c_str(), i);
3423 applyVolume = false;
3424 isPreempted = true;
3425 break;
3426 }
3427 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003428 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003429 applyVolume = true;
3430 }
3431 }
3432 if (isPreempted || applyVolume) {
3433 break;
3434 }
3435 }
3436 if (!applyVolume) {
3437 continue; // next output
3438 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003439 }
François Gaffieed91f582020-01-31 10:35:37 +01003440 //FIXME: workaround for truncated touch sounds
3441 // delayed volume change for system stream to be removed when the problem is
3442 // handled by system UI
3443 status_t volStatus = checkAndSetVolume(
3444 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003445 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003446 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3447 if (volStatus != NO_ERROR) {
3448 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003449 }
3450 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003451
3452 // update voice volume if the an active call route exists
3453 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3454 && (curSrcDevices.find(
3455 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3456 != curSrcDevices.end())) {
3457 bool isVoiceVolSrc;
3458 bool isBtScoVolSrc;
3459 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3460 isVoiceVolSrc, isBtScoVolSrc, __func__)
3461 && (isVoiceVolSrc || isBtScoVolSrc)) {
3462 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3463 }
3464 }
3465
François Gaffiecfe17322018-11-07 13:41:29 +01003466 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3467 return status;
3468}
3469
François Gaffieaaac0fd2018-11-22 17:56:39 +01003470status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003471 audio_devices_t device,
3472 IVolumeCurves &volumeCurves)
3473{
3474 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3475 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003476 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3477 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003478 (index > volumeCurves.getVolumeIndexMax())) {
3479 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3480 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3481 return BAD_VALUE;
3482 }
3483 if (!audio_is_output_device(device)) {
3484 return BAD_VALUE;
3485 }
3486
3487 // Force max volume if stream cannot be muted
3488 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3489
François Gaffieaaac0fd2018-11-22 17:56:39 +01003490 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003491 volumeCurves.addCurrentVolumeIndex(device, index);
3492 return NO_ERROR;
3493}
3494
3495status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3496 int &index,
3497 audio_devices_t device)
3498{
3499 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3500 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003501 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003502 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003503 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003504 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003505 }
jiabin9a3361e2019-10-01 09:38:30 -07003506 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003507}
3508
3509status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3510 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003511 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003512{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003513 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003514 return BAD_VALUE;
3515 }
jiabin9a3361e2019-10-01 09:38:30 -07003516 index = curves.getVolumeIndex(deviceTypes);
3517 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003518 return NO_ERROR;
3519}
3520
3521status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3522 int &index)
3523{
3524 index = getVolumeCurves(attr).getVolumeIndexMin();
3525 return NO_ERROR;
3526}
3527
3528status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3529 int &index)
3530{
3531 index = getVolumeCurves(attr).getVolumeIndexMax();
3532 return NO_ERROR;
3533}
3534
Eric Laurent36829f92017-04-07 19:04:42 -07003535audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003536{
3537 // select one output among several suitable for global effects.
3538 // The priority is as follows:
3539 // 1: An offloaded output. If the effect ends up not being offloadable,
3540 // AudioFlinger will invalidate the track and the offloaded output
3541 // will be closed causing the effect to be moved to a PCM output.
3542 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003543 // 3: The primary output
3544 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003545
François Gaffiec005e562018-11-06 15:04:49 +01003546 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3547 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003548 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003549
Eric Laurent36829f92017-04-07 19:04:42 -07003550 if (outputs.size() == 0) {
3551 return AUDIO_IO_HANDLE_NONE;
3552 }
Eric Laurente552edb2014-03-10 17:42:56 -07003553
Eric Laurent36829f92017-04-07 19:04:42 -07003554 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3555 bool activeOnly = true;
3556
3557 while (output == AUDIO_IO_HANDLE_NONE) {
3558 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3559 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3560 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3561
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003562 for (audio_io_handle_t output : outputs) {
3563 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003564 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003565 continue;
3566 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003567 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3568 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003569 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003570 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003571 }
3572 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003573 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003574 }
3575 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003576 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003577 }
3578 }
3579 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3580 output = outputOffloaded;
3581 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3582 output = outputDeepBuffer;
3583 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3584 output = outputPrimary;
3585 } else {
3586 output = outputs[0];
3587 }
3588 activeOnly = false;
3589 }
3590
3591 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003592 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3593 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003594 mMusicEffectOutput = output;
3595 }
3596
3597 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003598 return output;
3599}
3600
Eric Laurent36829f92017-04-07 19:04:42 -07003601audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3602{
3603 return selectOutputForMusicEffects();
3604}
3605
Eric Laurente0720872014-03-11 09:30:41 -07003606status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003607 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003608 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003609 int session,
3610 int id)
3611{
François Gaffie541fd402023-11-29 17:16:38 +01003612 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003613 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003614 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003615 index = mInputs.indexOfKey(io);
3616 if (index < 0) {
3617 ALOGW("registerEffect() unknown io %d", io);
3618 return INVALID_OPERATION;
3619 }
Eric Laurente552edb2014-03-10 17:42:56 -07003620 }
3621 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003622 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3623 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3624 || strategy == PRODUCT_STRATEGY_NONE));
3625 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003626}
3627
Eric Laurentc241b0d2018-11-28 09:08:49 -08003628status_t AudioPolicyManager::unregisterEffect(int id)
3629{
3630 if (mEffects.getEffect(id) == nullptr) {
3631 return INVALID_OPERATION;
3632 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003633 if (mEffects.isEffectEnabled(id)) {
3634 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3635 setEffectEnabled(id, false);
3636 }
3637 return mEffects.unregisterEffect(id);
3638}
3639
3640status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3641{
3642 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3643 if (effect == nullptr) {
3644 return INVALID_OPERATION;
3645 }
3646
3647 status_t status = mEffects.setEffectEnabled(id, enabled);
3648 if (status == NO_ERROR) {
3649 mInputs.trackEffectEnabled(effect, enabled);
3650 }
3651 return status;
3652}
3653
Eric Laurent6c796322019-04-09 14:13:17 -07003654
3655status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3656{
3657 mEffects.moveEffects(ids, io);
3658 return NO_ERROR;
3659}
3660
Eric Laurentc75307b2015-03-17 15:29:32 -07003661bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3662{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003663 auto vs = toVolumeSource(stream, false);
3664 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003665}
3666
3667bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3668{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003669 auto vs = toVolumeSource(stream, false);
3670 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003671}
3672
Eric Laurente0720872014-03-11 09:30:41 -07003673bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003674{
3675 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003676 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003677 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003678 return true;
3679 }
3680 }
3681 return false;
3682}
3683
Eric Laurent275e8e92014-11-30 15:14:47 -08003684// Register a list of custom mixes with their attributes and format.
3685// When a mix is registered, corresponding input and output profiles are
3686// added to the remote submix hw module. The profile contains only the
3687// parameters (sampling rate, format...) specified by the mix.
3688// The corresponding input remote submix device is also connected.
3689//
3690// When a remote submix device is connected, the address is checked to select the
3691// appropriate profile and the corresponding input or output stream is opened.
3692//
3693// When capture starts, getInputForAttr() will:
3694// - 1 look for a mix matching the address passed in attribtutes tags if any
3695// - 2 if none found, getDeviceForInputSource() will:
3696// - 2.1 look for a mix matching the attributes source
3697// - 2.2 if none found, default to device selection by policy rules
3698// At this time, the corresponding output remote submix device is also connected
3699// and active playback use cases can be transferred to this mix if needed when reconnecting
3700// after AudioTracks are invalidated
3701//
3702// When playback starts, getOutputForAttr() will:
3703// - 1 look for a mix matching the address passed in attribtutes tags if any
3704// - 2 if none found, look for a mix matching the attributes usage
3705// - 3 if none found, default to device and output selection by policy rules.
3706
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003707status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003708{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003709 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3710 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003711 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003712 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003713 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003714 // examine each mix's route type
3715 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003716 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003717 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3718 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3719 ALOGE("Unsupported Policy Mix %zu of %zu: "
3720 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3721 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003722 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003723 break;
3724 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003725 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3726 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003727 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003728 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3729 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003730 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003731 rSubmixModule = mHwModules.getModuleFromName(
3732 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3733 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003734 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003735 i);
3736 res = INVALID_OPERATION;
3737 break;
3738 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003739 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003740
Eric Laurent97ac8712018-07-27 18:59:02 -07003741 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003742 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003743 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003744 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003745 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3746 } else {
3747 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3748 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003749 }
François Gaffie036e1e92015-03-19 10:16:24 +01003750
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003751 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003752 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003753 res = INVALID_OPERATION;
3754 break;
3755 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003756 audio_config_t outputConfig = mix.mFormat;
3757 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003758 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3759 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003760 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3761 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003762 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003763 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3764 audio_is_linear_pcm(outputConfig.format)
3765 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003766 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003767 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3768 audio_is_linear_pcm(inputConfig.format)
3769 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003770
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003771 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003772 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003773 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003774 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003775 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003776 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003777 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003778 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3779 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003780 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003781 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003782 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003783
3784 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3785 mix.mDeviceType, mix.mDeviceAddress,
3786 String8(), AUDIO_FORMAT_DEFAULT);
3787 if (device == nullptr) {
3788 res = INVALID_OPERATION;
3789 break;
3790 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003791
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003792 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003793 // First try to find an already opened output supporting the device
3794 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003795 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003796
Eric Laurentc529cf62020-04-17 18:19:10 -07003797 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003798 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003799 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003800 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003801 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003802 } else {
3803 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003804 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003805 }
3806 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003807 // If no output found, try to find a direct output profile supporting the device
3808 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3809 sp<HwModule> module = mHwModules[i];
3810 for (size_t j = 0;
3811 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3812 j++) {
3813 sp<IOProfile> profile = module->getOutputProfiles()[j];
3814 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3815 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3816 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003817 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003818 res = INVALID_OPERATION;
3819 } else {
3820 foundOutput = true;
3821 }
3822 }
3823 }
3824 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003825 if (res != NO_ERROR) {
3826 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003827 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003828 res = INVALID_OPERATION;
3829 break;
3830 } else if (!foundOutput) {
3831 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003832 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003833 res = INVALID_OPERATION;
3834 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003835 } else {
3836 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003837 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003838 }
Eric Laurentc722f302014-12-10 11:21:49 -08003839 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003840 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003841 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003842 if (audio_flags::audio_mix_ownership()) {
3843 // Only unregister mixes that were actually registered to not accidentally unregister
3844 // mixes that already existed previously.
3845 unregisterPolicyMixes(registeredMixes);
3846 registeredMixes.clear();
3847 } else {
3848 unregisterPolicyMixes(mixes);
3849 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003850 } else if (checkOutputs) {
3851 checkForDeviceAndOutputChanges();
3852 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003853 }
3854 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003855}
3856
3857status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3858{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003859 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Marvin Raminabd9b892023-11-17 16:36:27 +01003860 status_t endResult = NO_ERROR;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003861 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003862 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003863 sp<HwModule> rSubmixModule;
3864 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003865 for (const auto& mix : mixes) {
3866 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003867
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003868 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003869 rSubmixModule = mHwModules.getModuleFromName(
3870 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3871 if (rSubmixModule == 0) {
3872 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003873 endResult = INVALID_OPERATION;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003874 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003875 }
3876 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003877
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003878 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003879
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003880 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003881 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003882 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003883 continue;
3884 }
3885
Kevin Rocard04ed0462019-05-02 17:53:24 -07003886 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003887 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003888 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3889 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003890 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003891 AUDIO_FORMAT_DEFAULT);
3892 if (res != OK) {
3893 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003894 "with type %d, address %s", device, address.c_str());
Marvin Raminabd9b892023-11-17 16:36:27 +01003895 endResult = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07003896 }
3897 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003898 }
jiabin5740f082019-08-19 15:08:30 -07003899 rSubmixModule->removeOutputProfile(address.c_str());
3900 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003901
Kevin Rocard153f92d2018-12-18 18:33:28 -08003902 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003903 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003904 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003905 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003906 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003907 } else {
3908 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003909 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003910 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003911 }
Marvin Raminabd9b892023-11-17 16:36:27 +01003912 if (audio_flags::audio_mix_ownership()) {
3913 res = endResult;
3914 if (res == NO_ERROR && checkOutputs) {
3915 checkForDeviceAndOutputChanges();
3916 updateCallAndOutputRouting();
3917 }
3918 } else {
3919 if (res == NO_ERROR && checkOutputs) {
3920 checkForDeviceAndOutputChanges();
3921 updateCallAndOutputRouting();
3922 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003923 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003924 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003925}
3926
Marvin Raminbdefaf02023-11-01 09:10:32 +01003927status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
3928 if (!audio_flags::audio_mix_test_api()) {
3929 return INVALID_OPERATION;
3930 }
3931
3932 _aidl_return.clear();
3933 _aidl_return.reserve(mPolicyMixes.size());
3934 for (const auto &policyMix: mPolicyMixes) {
3935 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
3936 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
3937 policyMix->mCbFlags);
3938 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01003939 _aidl_return.back().mToken = policyMix->mToken;
Marvin Raminbdefaf02023-11-01 09:10:32 +01003940 }
3941
3942 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return->size());
3943 return OK;
3944}
3945
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003946status_t AudioPolicyManager::updatePolicyMix(
3947 const AudioMix& mix,
3948 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3949 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3950 if (res == NO_ERROR) {
3951 checkForDeviceAndOutputChanges();
3952 updateCallAndOutputRouting();
3953 }
3954 return res;
3955}
3956
Mikhail Naganov100f0122018-11-29 11:22:16 -08003957void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3958{
3959 size_t i = 0;
3960 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3961 for (const auto& fmt : mManualSurroundFormats) {
3962 if (i++ != 0) dst->append(", ");
3963 std::string sfmt;
3964 FormatConverter::toString(fmt, sfmt);
3965 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3966 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3967 }
3968}
3969
Eric Laurentc529cf62020-04-17 18:19:10 -07003970// Returns true if all devices types match the predicate and are supported by one HW module
3971bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003972 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003973 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003974 const char *context,
3975 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003976 for (size_t i = 0; i < devices.size(); i++) {
3977 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003978 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003979 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003980 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003981 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003982 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003983 return false;
3984 }
3985 }
3986 return true;
3987}
3988
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003989void AudioPolicyManager::changeOutputDevicesMuteState(
3990 const AudioDeviceTypeAddrVector& devices) {
3991 ALOGVV("%s() num devices %zu", __func__, devices.size());
3992
3993 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3994 getSoftwareOutputsForDevices(devices);
3995
3996 for (size_t i = 0; i < outputs.size(); i++) {
3997 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3998 DeviceVector prevDevices = outputDesc->devices();
3999 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4000 }
4001}
4002
4003std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4004 const AudioDeviceTypeAddrVector& devices) const
4005{
4006 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4007 DeviceVector deviceDescriptors;
4008 for (size_t j = 0; j < devices.size(); j++) {
4009 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4010 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4011 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4012 ALOGE("%s: device type %#x address %s not supported or not an output device",
4013 __func__, devices[j].mType, devices[j].getAddress());
4014 continue;
4015 }
4016 deviceDescriptors.add(desc);
4017 }
4018 for (size_t i = 0; i < mOutputs.size(); i++) {
4019 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4020 continue;
4021 }
4022 outputs.push_back(mOutputs.valueAt(i));
4023 }
4024 return outputs;
4025}
4026
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004027status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004028 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004029 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004030 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4031 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004032 }
4033 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004034 if (res != NO_ERROR) {
4035 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4036 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004037 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004038
4039 checkForDeviceAndOutputChanges();
4040 updateCallAndOutputRouting();
4041
4042 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004043}
4044
4045status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4046 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004047 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4048 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004049 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004050 __FUNCTION__, uid);
4051 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004052 }
4053
Eric Laurentc529cf62020-04-17 18:19:10 -07004054 checkForDeviceAndOutputChanges();
4055 updateCallAndOutputRouting();
4056
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004057 return res;
4058}
4059
Eric Laurent2517af32020-11-25 15:31:27 +01004060
jiabin0a488932020-08-07 17:32:40 -07004061status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4062 device_role_t role,
4063 const AudioDeviceTypeAddrVector &devices) {
4064 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4065 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004066
Eric Laurentc529cf62020-04-17 18:19:10 -07004067 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004068 return BAD_VALUE;
4069 }
jiabin0a488932020-08-07 17:32:40 -07004070 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004071 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004072 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4073 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004074 return status;
4075 }
4076
4077 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004078
4079 bool forceVolumeReeval = false;
4080 // FIXME: workaround for truncated touch sounds
4081 // to be removed when the problem is handled by system UI
4082 uint32_t delayMs = 0;
4083 if (strategy == mCommunnicationStrategy) {
4084 forceVolumeReeval = true;
4085 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4086 updateInputRouting();
4087 }
4088 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004089
4090 return NO_ERROR;
4091}
4092
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004093void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4094 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004095{
4096 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004097 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004098 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004099 // Only apply special touch sound delay once
4100 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004101 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004102 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004103 for (size_t i = 0; i < mOutputs.size(); i++) {
4104 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4105 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004106 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4107 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004108 // As done in setDeviceConnectionState, we could also fix default device issue by
4109 // preventing the force re-routing in case of default dev that distinguishes on address.
4110 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004111 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004112 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4113 // If the device is using preferred mixer attributes, the output need to reopen
4114 // with default configuration when the new selected devices are different from
4115 // current routing devices.
4116 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4117 continue;
4118 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304119
4120 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4121 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004122 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004123 // Only apply special touch sound delay once
4124 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004125 }
4126 if (forceVolumeReeval && !newDevices.isEmpty()) {
4127 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4128 }
4129 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004130 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004131 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004132}
4133
Eric Laurent2517af32020-11-25 15:31:27 +01004134void AudioPolicyManager::updateInputRouting() {
4135 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304136 // Skip for hotword recording as the input device switch
4137 // is handled within sound trigger HAL
4138 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4139 continue;
4140 }
Eric Laurent2517af32020-11-25 15:31:27 +01004141 auto newDevice = getNewInputDevice(activeDesc);
4142 // Force new input selection if the new device can not be reached via current input
4143 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4144 setInputDevice(activeDesc->mIoHandle, newDevice);
4145 } else {
4146 closeInput(activeDesc->mIoHandle);
4147 }
4148 }
4149}
4150
Paul Wang5d7cdb52022-11-22 09:45:06 +00004151status_t
4152AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4153 device_role_t role,
4154 const AudioDeviceTypeAddrVector &devices) {
4155 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4156 dumpAudioDeviceTypeAddrVector(devices).c_str());
4157
Eric Laurent78fedbf2023-03-09 14:40:44 +01004158 if (!areAllDevicesSupported(
4159 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004160 return BAD_VALUE;
4161 }
4162 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4163 if (status != NO_ERROR) {
4164 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4165 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4166 return status;
4167 }
4168
4169 checkForDeviceAndOutputChanges();
4170
4171 bool forceVolumeReeval = false;
4172 // TODO(b/263479999): workaround for truncated touch sounds
4173 // to be removed when the problem is handled by system UI
4174 uint32_t delayMs = 0;
4175 if (strategy == mCommunnicationStrategy) {
4176 forceVolumeReeval = true;
4177 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4178 updateInputRouting();
4179 }
4180 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4181
4182 return NO_ERROR;
4183}
4184
4185status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4186 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004187{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004188 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004189
Paul Wang5d7cdb52022-11-22 09:45:06 +00004190 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004191 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004192 ALOGW_IF(status != NAME_NOT_FOUND,
4193 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004194 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004195 return status;
4196 }
4197
4198 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004199
4200 bool forceVolumeReeval = false;
4201 // FIXME: workaround for truncated touch sounds
4202 // to be removed when the problem is handled by system UI
4203 uint32_t delayMs = 0;
4204 if (strategy == mCommunnicationStrategy) {
4205 forceVolumeReeval = true;
4206 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4207 updateInputRouting();
4208 }
4209 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004210
4211 return NO_ERROR;
4212}
4213
jiabin0a488932020-08-07 17:32:40 -07004214status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4215 device_role_t role,
4216 AudioDeviceTypeAddrVector &devices) {
4217 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004218}
4219
Jiabin Huang3b98d322020-09-03 17:54:16 +00004220status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4221 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4222 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4223 dumpAudioDeviceTypeAddrVector(devices).c_str());
4224
Mikhail Naganov55773032020-10-01 15:08:13 -07004225 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004226 return BAD_VALUE;
4227 }
4228 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4229 ALOGW_IF(status != NO_ERROR,
4230 "Engine could not set preferred devices %s for audio source %d role %d",
4231 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4232
4233 return status;
4234}
4235
4236status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4237 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4238 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4239 dumpAudioDeviceTypeAddrVector(devices).c_str());
4240
Mikhail Naganov55773032020-10-01 15:08:13 -07004241 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004242 return BAD_VALUE;
4243 }
4244 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4245 ALOGW_IF(status != NO_ERROR,
4246 "Engine could not add preferred devices %s for audio source %d role %d",
4247 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4248
Eric Laurent2517af32020-11-25 15:31:27 +01004249 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004250 return status;
4251}
4252
4253status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4254 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4255{
4256 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4257 dumpAudioDeviceTypeAddrVector(devices).c_str());
4258
Eric Laurent78fedbf2023-03-09 14:40:44 +01004259 if (!areAllDevicesSupported(
4260 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004261 return BAD_VALUE;
4262 }
4263
4264 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4265 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004266 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004267 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004268 if (status == NO_ERROR) {
4269 updateInputRouting();
4270 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004271 return status;
4272}
4273
4274status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4275 device_role_t role) {
4276 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4277
4278 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004279 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004280 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004281 if (status == NO_ERROR) {
4282 updateInputRouting();
4283 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004284 return status;
4285}
4286
4287status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4288 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4289 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4290}
4291
Oscar Azucena90e77632019-11-27 17:12:28 -08004292status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004293 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004294 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004295 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4296 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004297 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004298 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4299 if (status != NO_ERROR) {
4300 ALOGE("%s() could not set device affinity for userId %d",
4301 __FUNCTION__, userId);
4302 return status;
4303 }
4304
4305 // reevaluate outputs for all devices
4306 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004307 changeOutputDevicesMuteState(devices);
4308 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4309 true /* skipDelays */);
4310 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004311
4312 return NO_ERROR;
4313}
4314
4315status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004316 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004317 AudioDeviceTypeAddrVector devices;
4318 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004319 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4320 if (status != NO_ERROR) {
4321 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4322 __FUNCTION__, userId);
4323 return status;
4324 }
4325
4326 // reevaluate outputs for all devices
4327 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004328 changeOutputDevicesMuteState(devices);
4329 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4330 true /* skipDelays */);
4331 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004332
4333 return NO_ERROR;
4334}
4335
Andy Hungc29d82b2018-10-05 12:23:17 -07004336void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004337{
Andy Hungc29d82b2018-10-05 12:23:17 -07004338 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004339 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004340 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004341 std::string stateLiteral;
4342 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004343 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004344 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4345 "communications", "media", "record", "dock", "system",
4346 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4347 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4348 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004349 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4350 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4351 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4352 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4353 dst->append(" (MANUAL: ");
4354 dumpManualSurroundFormats(dst);
4355 dst->append(")");
4356 }
4357 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004358 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004359 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4360 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004361 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004362 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004363
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004364 dst->append("\n");
4365 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4366 dst->append("\n");
4367 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004368 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004369 mOutputs.dump(dst);
4370 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004371 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004372 mAudioPatches.dump(dst);
4373 mPolicyMixes.dump(dst);
4374 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004375
Kevin Rocardb99cc752019-03-21 20:52:24 -07004376 dst->appendFormat(" AllowedCapturePolicies:\n");
4377 for (auto& policy : mAllowedCapturePolicies) {
4378 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4379 }
4380
jiabina84c3d32022-12-02 18:59:55 +00004381 dst->appendFormat(" Preferred mixer audio configuration:\n");
4382 for (const auto it : mPreferredMixerAttrInfos) {
4383 dst->appendFormat(" - device port id: %d\n", it.first);
4384 for (const auto preferredMixerInfoIt : it.second) {
4385 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4386 preferredMixerInfoIt.second->dump(dst);
4387 }
4388 }
4389
François Gaffiec005e562018-11-06 15:04:49 +01004390 dst->appendFormat("\nPolicy Engine dump:\n");
4391 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004392}
4393
4394status_t AudioPolicyManager::dump(int fd)
4395{
4396 String8 result;
4397 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004398 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004399 return NO_ERROR;
4400}
4401
Kevin Rocardb99cc752019-03-21 20:52:24 -07004402status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4403{
4404 mAllowedCapturePolicies[uid] = capturePolicy;
4405 return NO_ERROR;
4406}
4407
Eric Laurente552edb2014-03-10 17:42:56 -07004408// This function checks for the parameters which can be offloaded.
4409// This can be enhanced depending on the capability of the DSP and policy
4410// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004411audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004412{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004413 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004414 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004415 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004416 offloadInfo.format,
4417 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4418 offloadInfo.has_video);
4419
jiabin2b9d5a12021-12-10 01:06:29 +00004420 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004421 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004422 }
4423
4424 // See if there is a profile to support this.
4425 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004426 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004427 offloadInfo.sample_rate,
4428 offloadInfo.format,
4429 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004430 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4431 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004432 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4433 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4434 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004435 if (profile == nullptr) {
4436 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4437 }
4438 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4439 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4440 }
4441 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004442}
4443
Michael Chana94fbb22018-04-24 14:31:19 +10004444bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4445 const audio_attributes_t& attributes) {
4446 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004447 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004448 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4449 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004450 config.sample_rate,
4451 config.format,
4452 config.channel_mask,
4453 output_flags,
4454 true /* directOnly */);
4455 ALOGV("%s() profile %sfound with name: %s, "
4456 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4457 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004458 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004459 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004460
4461 // also try the MSD module if compatible profile not found
4462 if (profile == nullptr) {
4463 profile = getMsdProfileForOutput(outputDevices,
4464 config.sample_rate,
4465 config.format,
4466 config.channel_mask,
4467 output_flags,
4468 true /* directOnly */);
4469 ALOGV("%s() MSD profile %sfound with name: %s, "
4470 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4471 __FUNCTION__, profile != 0 ? "" : "NOT ",
4472 (profile != 0 ? profile->getTagName().c_str() : "null"),
4473 config.sample_rate, config.format, config.channel_mask, output_flags);
4474 }
4475 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004476}
4477
jiabin2b9d5a12021-12-10 01:06:29 +00004478bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4479 bool durationIgnored) {
4480 if (mMasterMono) {
4481 return false; // no offloading if mono is set.
4482 }
4483
4484 // Check if offload has been disabled
4485 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4486 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4487 return false;
4488 }
4489
4490 // Check if stream type is music, then only allow offload as of now.
4491 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4492 {
4493 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4494 return false;
4495 }
4496
4497 //TODO: enable audio offloading with video when ready
4498 const bool allowOffloadWithVideo =
4499 property_get_bool("audio.offload.video", false /* default_value */);
4500 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4501 ALOGV("%s: has_video == true, returning false", __func__);
4502 return false;
4503 }
4504
4505 //If duration is less than minimum value defined in property, return false
4506 const int min_duration_secs = property_get_int32(
4507 "audio.offload.min.duration.secs", -1 /* default_value */);
4508 if (!durationIgnored) {
4509 if (min_duration_secs >= 0) {
4510 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4511 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4512 __func__, min_duration_secs);
4513 return false;
4514 }
4515 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4516 ALOGV("%s: Offload denied by duration < default min(=%u)",
4517 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4518 return false;
4519 }
4520 }
4521
4522 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4523 // creating an offloaded track and tearing it down immediately after start when audioflinger
4524 // detects there is an active non offloadable effect.
4525 // FIXME: We should check the audio session here but we do not have it in this context.
4526 // This may prevent offloading in rare situations where effects are left active by apps
4527 // in the background.
4528 if (mEffects.isNonOffloadableEffectEnabled()) {
4529 return false;
4530 }
4531
4532 return true;
4533}
4534
4535audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4536 const audio_config_t *config) {
4537 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4538 offloadInfo.format = config->format;
4539 offloadInfo.sample_rate = config->sample_rate;
4540 offloadInfo.channel_mask = config->channel_mask;
4541 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4542 offloadInfo.has_video = false;
4543 offloadInfo.is_streaming = false;
4544 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4545
4546 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4547 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4548 audio_flags_to_audio_output_flags(attr->flags, &flags);
4549 // only retain flags that will drive compressed offload or passthrough
4550 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4551 if (offloadPossible) {
4552 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4553 }
4554 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4555
Dorin Drimusfae3c642022-03-17 18:36:30 +01004556 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004557 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004558 DeviceVector outputDevices = engineOutputDevices;
4559 // the MSD module checks for different conditions and output devices
4560 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4561 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4562 continue;
4563 }
4564 outputDevices = getMsdAudioOutDevices();
4565 }
jiabin2b9d5a12021-12-10 01:06:29 +00004566 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004567 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004568 config->sample_rate, nullptr /*updatedSamplingRate*/,
4569 config->format, nullptr /*updatedFormat*/,
4570 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004571 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004572 continue;
4573 }
4574 // reject profiles not corresponding to a device currently available
4575 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4576 continue;
4577 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004578 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4579 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004580 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004581 != AUDIO_DIRECT_NOT_SUPPORTED) {
4582 // Already reports offload gapless supported. No need to report offload support.
4583 continue;
4584 }
4585 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4586 != AUDIO_OUTPUT_FLAG_NONE) {
4587 // If offload gapless is reported, no need to report offload support.
4588 directMode = (audio_direct_mode_t) ((directMode &
4589 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4590 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4591 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004592 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004593 }
4594 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004595 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004596 }
4597 }
4598 }
4599 return directMode;
4600}
4601
Dorin Drimusf2196d82022-01-03 12:11:18 +01004602status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4603 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004604 if (mEffects.isNonOffloadableEffectEnabled()) {
4605 return OK;
4606 }
jiabinf1c73972022-04-14 16:28:52 -07004607 DeviceVector devices;
4608 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004609 if (status != OK) {
4610 return status;
4611 }
4612 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4613 if (devices.empty()) {
4614 return OK; // no output devices for the attributes
4615 }
jiabinf1c73972022-04-14 16:28:52 -07004616 return getProfilesForDevices(devices, audioProfilesVector,
4617 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004618}
4619
jiabina84c3d32022-12-02 18:59:55 +00004620status_t AudioPolicyManager::getSupportedMixerAttributes(
4621 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4622 ALOGV("%s, portId=%d", __func__, portId);
4623 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4624 if (deviceDescriptor == nullptr) {
4625 ALOGE("%s the requested device is currently unavailable", __func__);
4626 return BAD_VALUE;
4627 }
jiabin96daffc2023-05-11 17:51:55 +00004628 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4629 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4630 deviceDescriptor->type());
4631 return BAD_VALUE;
4632 }
jiabina84c3d32022-12-02 18:59:55 +00004633 for (const auto& hwModule : mHwModules) {
4634 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4635 if (curProfile->supportsDevice(deviceDescriptor)) {
4636 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4637 }
4638 }
4639 }
4640 return NO_ERROR;
4641}
4642
4643status_t AudioPolicyManager::setPreferredMixerAttributes(
4644 const audio_attributes_t *attr,
4645 audio_port_handle_t portId,
4646 uid_t uid,
4647 const audio_mixer_attributes_t *mixerAttributes) {
4648 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4649 "mixerBehavior=%d}, uid=%d, portId=%u",
4650 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4651 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4652 mixerAttributes->mixer_behavior, uid, portId);
4653 if (attr->usage != AUDIO_USAGE_MEDIA) {
4654 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4655 return BAD_VALUE;
4656 }
4657 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4658 if (deviceDescriptor == nullptr) {
4659 ALOGE("%s the requested device is currently unavailable", __func__);
4660 return BAD_VALUE;
4661 }
4662 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4663 ALOGE("%s(%d), type=%d, is not a usb output device",
4664 __func__, portId, deviceDescriptor->type());
4665 return BAD_VALUE;
4666 }
4667
4668 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4669 audio_flags_to_audio_output_flags(attr->flags, &flags);
4670 flags = (audio_output_flags_t) (flags |
4671 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4672 sp<IOProfile> profile = nullptr;
4673 DeviceVector devices(deviceDescriptor);
4674 for (const auto& hwModule : mHwModules) {
4675 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4676 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004677 && curProfile->getCompatibilityScore(
4678 devices,
4679 mixerAttributes->config.sample_rate,
4680 nullptr /*updatedSamplingRate*/,
4681 mixerAttributes->config.format,
4682 nullptr /*updatedFormat*/,
4683 mixerAttributes->config.channel_mask,
4684 nullptr /*updatedChannelMask*/,
4685 flags,
4686 false /*exactMatchRequiredForInputFlags*/)
4687 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004688 profile = curProfile;
4689 break;
4690 }
4691 }
4692 }
4693 if (profile == nullptr) {
4694 ALOGE("%s, there is no compatible profile found", __func__);
4695 return BAD_VALUE;
4696 }
4697
4698 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4699 sp<PreferredMixerAttributesInfo>::make(
4700 uid, portId, profile, flags, *mixerAttributes);
4701 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4702 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4703
4704 // If 1) there is any client from the preferred mixer configuration owner that is currently
4705 // active and matches the strategy and 2) current output is on the preferred device and the
4706 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4707 // configuration.
4708 std::vector<audio_io_handle_t> outputsToReopen;
4709 for (size_t i = 0; i < mOutputs.size(); i++) {
4710 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004711 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4712 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4713 output->mUsePreferredMixerAttributes = true;
4714 } else {
4715 for (const auto &client: output->getActiveClients()) {
4716 if (client->uid() == uid && client->strategy() == strategy) {
4717 client->setIsInvalid();
4718 outputsToReopen.push_back(output->mIoHandle);
4719 }
jiabina84c3d32022-12-02 18:59:55 +00004720 }
4721 }
4722 }
4723 }
4724 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4725 config.sample_rate = mixerAttributes->config.sample_rate;
4726 config.channel_mask = mixerAttributes->config.channel_mask;
4727 config.format = mixerAttributes->config.format;
4728 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004729 sp<SwAudioOutputDescriptor> desc =
4730 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4731 if (desc == nullptr) {
4732 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4733 continue;
4734 }
4735 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004736 }
4737
4738 return NO_ERROR;
4739}
4740
4741sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004742 audio_port_handle_t devicePortId,
4743 product_strategy_t strategy,
4744 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004745 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4746 if (it == mPreferredMixerAttrInfos.end()) {
4747 return nullptr;
4748 }
jiabind9a58d32023-06-01 17:57:30 +00004749 if (activeBitPerfectPreferred) {
4750 for (auto [strategy, info] : it->second) {
4751 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4752 && info->getActiveClientCount() != 0) {
4753 return info;
4754 }
4755 }
jiabina84c3d32022-12-02 18:59:55 +00004756 }
jiabind9a58d32023-06-01 17:57:30 +00004757 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4758 return strategyMatchedMixerAttrInfoIt == it->second.end()
4759 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004760}
4761
4762status_t AudioPolicyManager::getPreferredMixerAttributes(
4763 const audio_attributes_t *attr,
4764 audio_port_handle_t portId,
4765 audio_mixer_attributes_t* mixerAttributes) {
4766 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4767 portId, mEngine->getProductStrategyForAttributes(*attr));
4768 if (info == nullptr) {
4769 return NAME_NOT_FOUND;
4770 }
4771 *mixerAttributes = info->getMixerAttributes();
4772 return NO_ERROR;
4773}
4774
4775status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4776 audio_port_handle_t portId,
4777 uid_t uid) {
4778 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4779 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4780 if (preferredMixerAttrInfo == nullptr) {
4781 return NAME_NOT_FOUND;
4782 }
4783 if (preferredMixerAttrInfo->getUid() != uid) {
4784 ALOGE("%s, requested uid=%d, owned uid=%d",
4785 __func__, uid, preferredMixerAttrInfo->getUid());
4786 return PERMISSION_DENIED;
4787 }
4788 mPreferredMixerAttrInfos[portId].erase(strategy);
4789 if (mPreferredMixerAttrInfos[portId].empty()) {
4790 mPreferredMixerAttrInfos.erase(portId);
4791 }
4792
4793 // Reconfig existing output
4794 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4795 for (size_t i = 0; i < mOutputs.size(); i++) {
4796 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4797 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4798 }
4799 }
4800 for (const auto output : potentialOutputsToReopen) {
4801 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4802 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4803 preferredMixerAttrInfo->getFlags())) {
4804 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4805 }
4806 }
4807 return NO_ERROR;
4808}
4809
Eric Laurent6a94d692014-05-20 11:18:06 -07004810status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4811 audio_port_type_t type,
4812 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004813 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 unsigned int *generation)
4815{
jiabin19cdba52020-11-24 11:28:58 -08004816 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4817 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004818 return BAD_VALUE;
4819 }
4820 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004821 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004822 *num_ports = 0;
4823 }
4824
4825 size_t portsWritten = 0;
4826 size_t portsMax = *num_ports;
4827 *num_ports = 0;
4828 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004829 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4830 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004831 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004832 for (const auto& dev : mAvailableOutputDevices) {
4833 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004834 continue;
4835 }
4836 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004837 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004838 }
4839 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004840 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004841 }
4842 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004843 for (const auto& dev : mAvailableInputDevices) {
4844 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004845 continue;
4846 }
4847 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004848 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004849 }
4850 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004851 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004852 }
4853 }
4854 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4855 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4856 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4857 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4858 }
4859 *num_ports += mInputs.size();
4860 }
4861 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004862 size_t numOutputs = 0;
4863 for (size_t i = 0; i < mOutputs.size(); i++) {
4864 if (!mOutputs[i]->isDuplicated()) {
4865 numOutputs++;
4866 if (portsWritten < portsMax) {
4867 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4868 }
4869 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004870 }
Eric Laurent84c70242014-06-23 08:46:27 -07004871 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 }
4873 }
jiabina84c3d32022-12-02 18:59:55 +00004874
Eric Laurent6a94d692014-05-20 11:18:06 -07004875 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004876 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004877 return NO_ERROR;
4878}
4879
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004880status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4881 std::vector<media::AudioPortFw>* _aidl_return) {
4882 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4883 audio_port_v7 port;
4884 dev->toAudioPort(&port);
4885 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4886 _aidl_return->push_back(std::move(aidlPort));
4887 return OK;
4888 };
4889
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004890 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004891 for (const auto& dev : module->getDeclaredDevices()) {
4892 if (role == media::AudioPortRole::NONE ||
4893 ((role == media::AudioPortRole::SOURCE)
4894 == audio_is_input_device(dev->type()))) {
4895 RETURN_STATUS_IF_ERROR(pushPort(dev));
4896 }
4897 }
4898 }
4899 return OK;
4900}
4901
jiabin19cdba52020-11-24 11:28:58 -08004902status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004903{
Eric Laurent99fcae42018-05-17 16:59:18 -07004904 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4905 return BAD_VALUE;
4906 }
4907 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4908 if (dev != 0) {
4909 dev->toAudioPort(port);
4910 return NO_ERROR;
4911 }
4912 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4913 if (dev != 0) {
4914 dev->toAudioPort(port);
4915 return NO_ERROR;
4916 }
4917 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4918 if (out != 0) {
4919 out->toAudioPort(port);
4920 return NO_ERROR;
4921 }
4922 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4923 if (in != 0) {
4924 in->toAudioPort(port);
4925 return NO_ERROR;
4926 }
4927 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004928}
4929
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004930status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4931 audio_patch_handle_t *handle,
4932 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004933{
François Gaffieafd4cea2019-11-18 15:50:22 +01004934 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004935 if (handle == NULL || patch == NULL) {
4936 return BAD_VALUE;
4937 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004938 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004939 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004940 return BAD_VALUE;
4941 }
4942 // only one source per audio patch supported for now
4943 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004944 return INVALID_OPERATION;
4945 }
Eric Laurent874c42872014-08-08 15:13:39 -07004946 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004947 return INVALID_OPERATION;
4948 }
Eric Laurent874c42872014-08-08 15:13:39 -07004949 for (size_t i = 0; i < patch->num_sinks; i++) {
4950 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4951 return INVALID_OPERATION;
4952 }
4953 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004954
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004955 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4956 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4957 if (srcDevice == nullptr || sinkDevice == nullptr) {
4958 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4959 return BAD_VALUE;
4960 }
4961 ALOGV("%s between source %s and sink %s", __func__,
4962 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4963 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4964 // Default attributes, default volume priority, not to infer with non raw audio patches.
4965 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4966 const struct audio_port_config *source = &patch->sources[0];
4967 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004968 new SourceClientDescriptor(
4969 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4970 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4971 true);
4972 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004973
4974 status_t status =
4975 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4976
4977 if (status != NO_ERROR) {
4978 return INVALID_OPERATION;
4979 }
4980 mAudioSources.add(portId, sourceDesc);
4981 return NO_ERROR;
4982}
4983
4984status_t AudioPolicyManager::connectAudioSourceToSink(
4985 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4986 const struct audio_patch *patch,
4987 audio_patch_handle_t &handle,
4988 uid_t uid, uint32_t delayMs)
4989{
4990 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4991 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4992 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4993 return INVALID_OPERATION;
4994 }
4995 sourceDesc->connect(handle, sinkDevice);
4996 if (isMsdPatch(handle)) {
4997 return NO_ERROR;
4998 }
4999 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5000 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5001 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5002 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5003 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5004 goto FailurePatchAdded;
5005 }
5006 status = swOutput->start();
5007 if (status != NO_ERROR) {
5008 goto FailureSourceAdded;
5009 }
5010 swOutput->addClient(sourceDesc);
5011 status = startSource(swOutput, sourceDesc, &delayMs);
5012 if (status != NO_ERROR) {
5013 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5014 goto FailureSourceActive;
5015 }
5016 if (delayMs != 0) {
5017 usleep(delayMs * 1000);
5018 }
5019 return NO_ERROR;
5020
5021FailureSourceActive:
5022 swOutput->stop();
5023 releaseOutput(sourceDesc->portId());
5024FailureSourceAdded:
5025 sourceDesc->setSwOutput(nullptr);
5026FailurePatchAdded:
5027 releaseAudioPatchInternal(handle);
5028 return INVALID_OPERATION;
5029}
5030
5031status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5032 audio_patch_handle_t *handle,
5033 uid_t uid, uint32_t delayMs,
5034 const sp<SourceClientDescriptor>& sourceDesc)
5035{
5036 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005037 sp<AudioPatch> patchDesc;
5038 ssize_t index = mAudioPatches.indexOfKey(*handle);
5039
François Gaffieafd4cea2019-11-18 15:50:22 +01005040 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5041 patch->sources[0].role,
5042 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005043#if LOG_NDEBUG == 0
5044 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005045 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5046 patch->sinks[i].role,
5047 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005048 }
5049#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005050
5051 if (index >= 0) {
5052 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005053 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5054 __func__, mUidCached, patchDesc->getUid(), uid);
5055 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005056 return INVALID_OPERATION;
5057 }
5058 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005059 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005060 }
5061
5062 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005063 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005064 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005065 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005066 return BAD_VALUE;
5067 }
Eric Laurent84c70242014-06-23 08:46:27 -07005068 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5069 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005070 if (patchDesc != 0) {
5071 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005072 ALOGV("%s source id differs for patch current id %d new id %d",
5073 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005074 return BAD_VALUE;
5075 }
5076 }
Eric Laurent874c42872014-08-08 15:13:39 -07005077 DeviceVector devices;
5078 for (size_t i = 0; i < patch->num_sinks; i++) {
5079 // Only support mix to devices connection
5080 // TODO add support for mix to mix connection
5081 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005082 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005083 return INVALID_OPERATION;
5084 }
5085 sp<DeviceDescriptor> devDesc =
5086 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5087 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005088 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005089 return BAD_VALUE;
5090 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005091
jiabin66acc432024-02-06 00:57:36 +00005092 if (outputDesc->mProfile->getCompatibilityScore(
5093 DeviceVector(devDesc),
5094 patch->sources[0].sample_rate,
5095 nullptr, // updatedSamplingRate
5096 patch->sources[0].format,
5097 nullptr, // updatedFormat
5098 patch->sources[0].channel_mask,
5099 nullptr, // updatedChannelMask
5100 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005101 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005102 return INVALID_OPERATION;
5103 }
5104 devices.add(devDesc);
5105 }
5106 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005107 return INVALID_OPERATION;
5108 }
Eric Laurent874c42872014-08-08 15:13:39 -07005109
Eric Laurent6a94d692014-05-20 11:18:06 -07005110 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005111 ALOGV("%s setting device %s on output %d",
5112 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305113 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005114 index = mAudioPatches.indexOfKey(*handle);
5115 if (index >= 0) {
5116 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005117 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005118 }
5119 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005120 patchDesc->setUid(uid);
5121 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005122 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005123 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005124 return INVALID_OPERATION;
5125 }
5126 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5127 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5128 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005129 // only one sink supported when connecting an input device to a mix
5130 if (patch->num_sinks > 1) {
5131 return INVALID_OPERATION;
5132 }
François Gaffie53615e22015-03-19 09:24:12 +01005133 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005134 if (inputDesc == NULL) {
5135 return BAD_VALUE;
5136 }
5137 if (patchDesc != 0) {
5138 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5139 return BAD_VALUE;
5140 }
5141 }
François Gaffie11d30102018-11-02 16:09:09 +01005142 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005143 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005144 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005145 return BAD_VALUE;
5146 }
5147
jiabin66acc432024-02-06 00:57:36 +00005148 if (inputDesc->mProfile->getCompatibilityScore(
5149 DeviceVector(device),
5150 patch->sinks[0].sample_rate,
5151 nullptr, /*updatedSampleRate*/
5152 patch->sinks[0].format,
5153 nullptr, /*updatedFormat*/
5154 patch->sinks[0].channel_mask,
5155 nullptr, /*updatedChannelMask*/
5156 // FIXME for the parameter type,
5157 // and the NONE
5158 (audio_output_flags_t)
5159 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005160 return INVALID_OPERATION;
5161 }
5162 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005163 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005164 device->toString().c_str(), inputDesc->mIoHandle);
5165 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005166 index = mAudioPatches.indexOfKey(*handle);
5167 if (index >= 0) {
5168 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005169 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005170 }
5171 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005172 patchDesc->setUid(uid);
5173 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005174 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005175 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005176 return INVALID_OPERATION;
5177 }
5178 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5179 // device to device connection
5180 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005181 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005182 return BAD_VALUE;
5183 }
5184 }
François Gaffie11d30102018-11-02 16:09:09 +01005185 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005186 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005187 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005188 return BAD_VALUE;
5189 }
Eric Laurent874c42872014-08-08 15:13:39 -07005190
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 //update source and sink with our own data as the data passed in the patch may
5192 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005193 PatchBuilder patchBuilder;
5194 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005195
5196 // if first sink is to MSD, establish single MSD patch
5197 if (getMsdAudioOutDevices().contains(
5198 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5199 ALOGV("%s patching to MSD", __FUNCTION__);
5200 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5201 goto installPatch;
5202 }
5203
François Gaffieafd4cea2019-11-18 15:50:22 +01005204 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5205 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005206
Eric Laurent874c42872014-08-08 15:13:39 -07005207 for (size_t i = 0; i < patch->num_sinks; i++) {
5208 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005209 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005210 return INVALID_OPERATION;
5211 }
François Gaffie11d30102018-11-02 16:09:09 +01005212 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005213 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005214 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005215 return BAD_VALUE;
5216 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005217 audio_port_config sinkPortConfig = {};
5218 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5219 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005220
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005221 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5222 // volume management purpose (tracking activity)
5223 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5224 // in config XML to reach the sink so that is can be declared as available.
5225 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005226 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005227 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005228 // take care of dynamic routing for SwOutput selection,
5229 audio_attributes_t attributes = sourceDesc->attributes();
5230 audio_stream_type_t stream = sourceDesc->stream();
5231 audio_attributes_t resultAttr;
5232 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5233 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005234 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5235 config.channel_mask =
5236 (audio_channel_mask_get_representation(sourceMask)
5237 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5238 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005239 config.format = sourceDesc->config().format;
5240 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5241 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5242 bool isRequestedDeviceForExclusiveUse = false;
5243 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005244 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005245 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005246 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5247 &stream, sourceDesc->uid(), &config, &flags,
5248 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005249 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005250 if (output == AUDIO_IO_HANDLE_NONE) {
5251 ALOGV("%s no output for device %s",
5252 __FUNCTION__, sinkDevice->toString().c_str());
5253 return INVALID_OPERATION;
5254 }
5255 outputDesc = mOutputs.valueFor(output);
5256 if (outputDesc->isDuplicated()) {
5257 ALOGE("%s output is duplicated", __func__);
5258 return INVALID_OPERATION;
5259 }
François Gaffie7e39df22022-04-26 12:48:49 +02005260 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5261 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005262 } else {
5263 // Same for "raw patches" aka created from createAudioPatch API
5264 SortedVector<audio_io_handle_t> outputs =
5265 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5266 // if the sink device is reachable via an opened output stream, request to
5267 // go via this output stream by adding a second source to the patch
5268 // description
5269 output = selectOutput(outputs);
5270 if (output == AUDIO_IO_HANDLE_NONE) {
5271 ALOGE("%s no output available for internal patch sink", __func__);
5272 return INVALID_OPERATION;
5273 }
5274 outputDesc = mOutputs.valueFor(output);
5275 if (outputDesc->isDuplicated()) {
5276 ALOGV("%s output for device %s is duplicated",
5277 __func__, sinkDevice->toString().c_str());
5278 return INVALID_OPERATION;
5279 }
François Gaffie7e39df22022-04-26 12:48:49 +02005280 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005281 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005282 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005283 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005284 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005285 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005286 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5287 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005288 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5289 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005290 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005291 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005292 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005293 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005294 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005295 return INVALID_OPERATION;
5296 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005297 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005298 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005299 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005300 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005301 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005302 srcMixPortConfig.ext.mix.usecase.stream =
5303 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005304 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5305 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005306 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005307 }
Eric Laurent83b88082014-06-20 18:31:16 -07005308 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 }
5310 // TODO: check from routing capabilities in config file and other conflicting patches
5311
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005312installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005313 status_t status = installPatch(
5314 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005315 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005316 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005317 return INVALID_OPERATION;
5318 }
5319 } else {
5320 return BAD_VALUE;
5321 }
5322 } else {
5323 return BAD_VALUE;
5324 }
5325 return NO_ERROR;
5326}
5327
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005328status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005329{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005330 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005331 ssize_t index = mAudioPatches.indexOfKey(handle);
5332
5333 if (index < 0) {
5334 return BAD_VALUE;
5335 }
5336 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005337 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5338 __func__, mUidCached, patchDesc->getUid(), uid);
5339 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005340 return INVALID_OPERATION;
5341 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005342 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5343 for (size_t i = 0; i < mAudioSources.size(); i++) {
5344 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5345 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5346 portId = sourceDesc->portId();
5347 break;
5348 }
5349 }
5350 return portId != AUDIO_PORT_HANDLE_NONE ?
5351 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005352}
Eric Laurent6a94d692014-05-20 11:18:06 -07005353
François Gaffieafd4cea2019-11-18 15:50:22 +01005354status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005355 uint32_t delayMs,
5356 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005357{
5358 ALOGV("%s patch %d", __func__, handle);
5359 if (mAudioPatches.indexOfKey(handle) < 0) {
5360 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5361 return BAD_VALUE;
5362 }
5363 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005364 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005365 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005367 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005368 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005369 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005370 return BAD_VALUE;
5371 }
5372
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305373 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005374 getNewOutputDevices(outputDesc, true /*fromCache*/),
5375 true,
5376 0,
5377 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005378 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5379 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005380 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005381 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005382 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005383 return BAD_VALUE;
5384 }
5385 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005386 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005387 true,
5388 NULL);
5389 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005390 status_t status =
5391 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5392 ALOGV("%s patch panel returned %d patchHandle %d",
5393 __func__, status, patchDesc->getAfHandle());
5394 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005395 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005396 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005397 // SW or HW Bridge
5398 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5399 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005400 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005401 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5402 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5403 outputDesc = sourceDesc->swOutput().promote();
5404 }
5405 if (outputDesc == nullptr) {
5406 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5407 // releaseOutput has already called closeOutput in case of direct output
5408 return NO_ERROR;
5409 }
François Gaffie7e39df22022-04-26 12:48:49 +02005410 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005411 // While using a HwBridge, force reconsidering device only if not reusing an existing
5412 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005413 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005414 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5415 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5416 // Reconsider device only for cases:
5417 // 1 / Active Output
5418 // 2 / Inactive Output previously hosting HwBridge
5419 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5420 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5421 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305422 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005423 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5424 outputDesc->devices(),
5425 force,
5426 0,
5427 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005428 } else {
5429 return BAD_VALUE;
5430 }
5431 } else {
5432 return BAD_VALUE;
5433 }
5434 return NO_ERROR;
5435}
5436
5437status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5438 struct audio_patch *patches,
5439 unsigned int *generation)
5440{
François Gaffie53615e22015-03-19 09:24:12 +01005441 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005442 return BAD_VALUE;
5443 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005444 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005445 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005446}
5447
Eric Laurente1715a42014-05-20 11:30:42 -07005448status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005449{
Eric Laurente1715a42014-05-20 11:30:42 -07005450 ALOGV("setAudioPortConfig()");
5451
5452 if (config == NULL) {
5453 return BAD_VALUE;
5454 }
5455 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5456 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005457 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5458 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005459 }
5460
Eric Laurenta121f902014-06-03 13:32:54 -07005461 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005462 if (config->type == AUDIO_PORT_TYPE_MIX) {
5463 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005464 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005465 if (outputDesc == NULL) {
5466 return BAD_VALUE;
5467 }
Eric Laurent84c70242014-06-23 08:46:27 -07005468 ALOG_ASSERT(!outputDesc->isDuplicated(),
5469 "setAudioPortConfig() called on duplicated output %d",
5470 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005471 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005472 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005473 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005474 if (inputDesc == NULL) {
5475 return BAD_VALUE;
5476 }
Eric Laurenta121f902014-06-03 13:32:54 -07005477 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005478 } else {
5479 return BAD_VALUE;
5480 }
5481 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5482 sp<DeviceDescriptor> deviceDesc;
5483 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5484 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5485 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5486 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5487 } else {
5488 return BAD_VALUE;
5489 }
5490 if (deviceDesc == NULL) {
5491 return BAD_VALUE;
5492 }
Eric Laurenta121f902014-06-03 13:32:54 -07005493 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005494 } else {
5495 return BAD_VALUE;
5496 }
5497
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005498 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005499 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5500 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005501 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005502 audioPortConfig->toAudioPortConfig(&newConfig, config);
5503 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005504 }
Eric Laurenta121f902014-06-03 13:32:54 -07005505 if (status != NO_ERROR) {
5506 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005507 }
Eric Laurente1715a42014-05-20 11:30:42 -07005508
5509 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005510}
5511
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005512void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5513{
Eric Laurentd60560a2015-04-10 11:31:20 -07005514 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005515 clearAudioPatches(uid);
5516 clearSessionRoutes(uid);
5517}
5518
Eric Laurent6a94d692014-05-20 11:18:06 -07005519void AudioPolicyManager::clearAudioPatches(uid_t uid)
5520{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005521 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005522 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005523 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005524 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005525 }
5526 }
5527}
5528
François Gaffiec005e562018-11-06 15:04:49 +01005529void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005530{
François Gaffiec005e562018-11-06 15:04:49 +01005531 // Take the first attributes following the product strategy as it is used to retrieve the routed
5532 // device. All attributes wihin a strategy follows the same "routing strategy"
5533 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5534 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005535 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005536 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005537 for (size_t j = 0; j < mOutputs.size(); j++) {
5538 if (mOutputs.keyAt(j) == ouptutToSkip) {
5539 continue;
5540 }
5541 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005542 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005543 continue;
5544 }
5545 // If the default device for this strategy is on another output mix,
5546 // invalidate all tracks in this strategy to force re connection.
5547 // Otherwise select new device on the output mix.
5548 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005549 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005550 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005551 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5552 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5553 // If the device is using preferred mixer attributes, the output need to reopen
5554 // with default configuration when the new selected devices are different from
5555 // current routing devices.
5556 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5557 continue;
5558 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305559 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005560 }
5561 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005562 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005563}
5564
5565void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5566{
5567 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005568 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005569 for (size_t i = 0; i < mOutputs.size(); i++) {
5570 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005571 for (const auto& client : outputDesc->getClientIterable()) {
5572 if (client->hasPreferredDevice() && client->uid() == uid) {
5573 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005574 auto clientStrategy = client->strategy();
5575 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5576 end(affectedStrategies)) {
5577 continue;
5578 }
5579 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005580 }
5581 }
5582 }
5583 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005584 for (const auto& strategy : affectedStrategies) {
5585 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005586 }
5587
5588 // remove input routes associated with this uid
5589 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005590 for (size_t i = 0; i < mInputs.size(); i++) {
5591 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005592 for (const auto& client : inputDesc->getClientIterable()) {
5593 if (client->hasPreferredDevice() && client->uid() == uid) {
5594 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5595 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005596 }
5597 }
5598 }
5599 // reroute inputs if necessary
5600 SortedVector<audio_io_handle_t> inputsToClose;
5601 for (size_t i = 0; i < mInputs.size(); i++) {
5602 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005603 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005604 inputsToClose.add(inputDesc->mIoHandle);
5605 }
5606 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005607 for (const auto& input : inputsToClose) {
5608 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005609 }
5610}
5611
Eric Laurentd60560a2015-04-10 11:31:20 -07005612void AudioPolicyManager::clearAudioSources(uid_t uid)
5613{
5614 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005615 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5616 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005617 stopAudioSource(mAudioSources.keyAt(i));
5618 }
5619 }
5620}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005621
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005622status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5623 audio_io_handle_t *ioHandle,
5624 audio_devices_t *device)
5625{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005626 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5627 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005628 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005629 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5630 if (deviceDesc == nullptr) {
5631 return INVALID_OPERATION;
5632 }
5633 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005634
François Gaffiedf372692015-03-19 10:43:27 +01005635 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005636}
5637
Eric Laurentd60560a2015-04-10 11:31:20 -07005638status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005639 const audio_attributes_t *attributes,
5640 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005641 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005642{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005643 ALOGV("%s", __FUNCTION__);
5644 *portId = AUDIO_PORT_HANDLE_NONE;
5645
5646 if (source == NULL || attributes == NULL || portId == NULL) {
5647 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5648 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005649 return BAD_VALUE;
5650 }
5651
Eric Laurentd60560a2015-04-10 11:31:20 -07005652 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5653 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005654 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5655 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005656 return INVALID_OPERATION;
5657 }
5658
François Gaffie11d30102018-11-02 16:09:09 +01005659 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005660 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005661 String8(source->ext.device.address),
5662 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005663 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005664 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005665 return BAD_VALUE;
5666 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005667
jiabin4ef93452019-09-10 14:29:54 -07005668 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005669
François Gaffieaaac0fd2018-11-22 17:56:39 +01005670 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005671 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005672 mEngine->getStreamTypeForAttributes(*attributes),
5673 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005674 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005675
5676 status_t status = connectAudioSource(sourceDesc);
5677 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005678 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005679 }
5680 return status;
5681}
5682
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005683status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005684{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005685 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005686
5687 // make sure we only have one patch per source.
5688 disconnectAudioSource(sourceDesc);
5689
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005690 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005691 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5692 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5693 sourceDesc->srcDevice()->type(),
5694 String8(sourceDesc->srcDevice()->address().c_str()),
5695 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005696 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005697 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005698 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005699 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005700 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5701 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5702 return INVALID_OPERATION;
5703 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005704 PatchBuilder patchBuilder;
5705 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5706 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005707
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005708 return connectAudioSourceToSink(
5709 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005710}
5711
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005712status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005713{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005714 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5715 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005716 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005717 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005718 return BAD_VALUE;
5719 }
5720 status_t status = disconnectAudioSource(sourceDesc);
5721
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005722 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005723 return status;
5724}
5725
Andy Hung2ddee192015-12-18 17:34:44 -08005726status_t AudioPolicyManager::setMasterMono(bool mono)
5727{
5728 if (mMasterMono == mono) {
5729 return NO_ERROR;
5730 }
5731 mMasterMono = mono;
5732 // if enabling mono we close all offloaded devices, which will invalidate the
5733 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5734 // for recreating the new AudioTrack as non-offloaded PCM.
5735 //
5736 // If disabling mono, we leave all tracks as is: we don't know which clients
5737 // and tracks are able to be recreated as offloaded. The next "song" should
5738 // play back offloaded.
5739 if (mMasterMono) {
5740 Vector<audio_io_handle_t> offloaded;
5741 for (size_t i = 0; i < mOutputs.size(); ++i) {
5742 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5743 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5744 offloaded.push(desc->mIoHandle);
5745 }
5746 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005747 for (const auto& handle : offloaded) {
5748 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005749 }
5750 }
5751 // update master mono for all remaining outputs
5752 for (size_t i = 0; i < mOutputs.size(); ++i) {
5753 updateMono(mOutputs.keyAt(i));
5754 }
5755 return NO_ERROR;
5756}
5757
5758status_t AudioPolicyManager::getMasterMono(bool *mono)
5759{
5760 *mono = mMasterMono;
5761 return NO_ERROR;
5762}
5763
Eric Laurentac9cef52017-06-09 15:46:26 -07005764float AudioPolicyManager::getStreamVolumeDB(
5765 audio_stream_type_t stream, int index, audio_devices_t device)
5766{
jiabin9a3361e2019-10-01 09:38:30 -07005767 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005768}
5769
jiabin81772902018-04-02 17:52:27 -07005770status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5771 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005772 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005773{
Kriti Dang6537def2021-03-02 13:46:59 +01005774 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5775 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005776 return BAD_VALUE;
5777 }
Kriti Dang6537def2021-03-02 13:46:59 +01005778 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5779 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005780
5781 size_t formatsWritten = 0;
5782 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005783
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005784 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005785 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5786 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005787 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005788 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005789 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005790 bool formatEnabled = true;
5791 switch (forceUse) {
5792 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005793 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005794 break;
5795 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5796 formatEnabled = false;
5797 break;
5798 default: // AUTO or ALWAYS => true
5799 break;
jiabin81772902018-04-02 17:52:27 -07005800 }
5801 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5802 }
jiabin81772902018-04-02 17:52:27 -07005803 }
5804 return NO_ERROR;
5805}
5806
Kriti Dang6537def2021-03-02 13:46:59 +01005807status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5808 audio_format_t *surroundFormats) {
5809 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5810 return BAD_VALUE;
5811 }
5812 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5813 __func__, *numSurroundFormats, surroundFormats);
5814
5815 size_t formatsWritten = 0;
5816 size_t formatsMax = *numSurroundFormats;
5817 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5818
5819 // Return formats from all device profiles that have already been resolved by
5820 // checkOutputsForDevice().
5821 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5822 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5823 audio_devices_t deviceType = device->type();
5824 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5825 // returns formats reported by HDMI devices.
5826 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5827 continue;
5828 }
5829 // Formats reported by sink devices
5830 std::unordered_set<audio_format_t> formatset;
5831 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5832 formatset.insert(it->second.begin(), it->second.end());
5833 }
5834
5835 // Formats hard-coded in the in policy configuration file (if any).
5836 FormatVector encodedFormats = device->encodedFormats();
5837 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5838 // Filter the formats which are supported by the vendor hardware.
5839 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005840 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005841 formats.insert(*it);
5842 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005843 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005844 if (pair.second.count(*it) != 0) {
5845 formats.insert(pair.first);
5846 break;
5847 }
5848 }
5849 }
5850 }
5851 }
5852 *numSurroundFormats = formats.size();
5853 for (const auto& format: formats) {
5854 if (formatsWritten < formatsMax) {
5855 surroundFormats[formatsWritten++] = format;
5856 }
5857 }
5858 return NO_ERROR;
5859}
5860
jiabin81772902018-04-02 17:52:27 -07005861status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5862{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005863 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005864 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5865 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005866 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005867 return BAD_VALUE;
5868 }
5869
Mikhail Naganov100f0122018-11-29 11:22:16 -08005870 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5871 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005872 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005873 return INVALID_OPERATION;
5874 }
5875
Mikhail Naganov100f0122018-11-29 11:22:16 -08005876 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005877 return NO_ERROR;
5878 }
5879
Mikhail Naganov100f0122018-11-29 11:22:16 -08005880 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005881 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005882 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005883 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005884 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005885 }
5886 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005887 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005888 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005889 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005890 }
5891 }
5892
5893 sp<SwAudioOutputDescriptor> outputDesc;
5894 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005895 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5896 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005897 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5898 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005899 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005900 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005901 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5902 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5903 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005904 name.c_str(),
5905 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005906 if (status != NO_ERROR) {
5907 continue;
5908 }
5909 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5910 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5911 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005912 name.c_str(),
5913 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005914 profileUpdated |= (status == NO_ERROR);
5915 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005916 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005917 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005918 AUDIO_DEVICE_IN_HDMI);
5919 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5920 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005921 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005922 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005923 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5924 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5925 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005926 name.c_str(),
5927 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005928 if (status != NO_ERROR) {
5929 continue;
5930 }
5931 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5932 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5933 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005934 name.c_str(),
5935 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005936 profileUpdated |= (status == NO_ERROR);
5937 }
5938
jiabin81772902018-04-02 17:52:27 -07005939 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005940 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005941 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005942 }
5943
5944 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5945}
5946
Eric Laurent5ada82e2019-08-29 17:53:54 -07005947void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005948{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005949 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005950 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005951 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005952 }
5953}
5954
jiabin6012f912018-11-02 17:06:30 -07005955bool AudioPolicyManager::isHapticPlaybackSupported()
5956{
5957 for (const auto& hwModule : mHwModules) {
5958 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5959 for (const auto &outProfile : outputProfiles) {
5960 struct audio_port audioPort;
5961 outProfile->toAudioPort(&audioPort);
5962 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5963 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5964 return true;
5965 }
5966 }
5967 }
5968 }
5969 return false;
5970}
5971
Carter Hsu325a8eb2022-01-19 19:56:51 +08005972bool AudioPolicyManager::isUltrasoundSupported()
5973{
5974 bool hasUltrasoundOutput = false;
5975 bool hasUltrasoundInput = false;
5976 for (const auto& hwModule : mHwModules) {
5977 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5978 if (!hasUltrasoundOutput) {
5979 for (const auto &outProfile : outputProfiles) {
5980 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5981 hasUltrasoundOutput = true;
5982 break;
5983 }
5984 }
5985 }
5986
5987 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5988 if (!hasUltrasoundInput) {
5989 for (const auto &inputProfile : inputProfiles) {
5990 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5991 hasUltrasoundInput = true;
5992 break;
5993 }
5994 }
5995 }
5996
5997 if (hasUltrasoundOutput && hasUltrasoundInput)
5998 return true;
5999 }
6000 return false;
6001}
6002
Atneya Nair698f5ef2022-12-15 16:15:09 -08006003bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6004{
6005 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6006 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6007 for (const auto& hwModule : mHwModules) {
6008 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6009 for (const auto &inputProfile : inputProfiles) {
6010 if ((inputProfile->getFlags() & mask) == mask) {
6011 return true;
6012 }
6013 }
6014 }
6015 return false;
6016}
6017
Eric Laurent8340e672019-11-06 11:01:08 -08006018bool AudioPolicyManager::isCallScreenModeSupported()
6019{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006020 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006021}
6022
6023
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006024status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006025{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006026 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006027 if (!sourceDesc->isConnected()) {
6028 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6029 return NO_ERROR;
6030 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006031 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6032 if (swOutput != 0) {
6033 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006034 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006035 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006036 }
jiabinbce0c1d2020-10-05 11:20:18 -07006037 if (releaseOutput(sourceDesc->portId())) {
6038 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6039 // no need to release audio patch here but just return NO_ERROR.
6040 return NO_ERROR;
6041 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006042 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006043 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006044 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006045 // close Hwoutput and remove from mHwOutputs
6046 } else {
6047 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6048 }
6049 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006050 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006051 sourceDesc->disconnect();
6052 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006053}
6054
François Gaffiec005e562018-11-06 15:04:49 +01006055sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6056 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006057{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006058 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006059 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006060 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006061 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006062 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6063 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006064 source = sourceDesc;
6065 break;
6066 }
6067 }
6068 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006069}
6070
Eric Laurentb4f42a92022-01-17 17:37:31 +01006071bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006072 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006073 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006074{
6075 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6076 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006077 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006078 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006079 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6080 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6081 return false;
6082 }
6083 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6084 return false;
6085 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006086 }
6087
Eric Laurentd332bc82023-08-04 11:45:23 +02006088 // The caller can have the audio config criteria ignored by either passing a null ptr or
6089 // the AUDIO_CONFIG_INITIALIZER value.
6090 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006091 // some positional channel masks and PCM format and for stereo if low latency performance
6092 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006093
6094 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006095 static const bool stereo_spatialization_enabled =
6096 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006097 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006098 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006099 ? audio_channel_mask_contains_stereo(config->channel_mask)
6100 : audio_is_channel_mask_spatialized(config->channel_mask);
6101 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006102 return false;
6103 }
6104 if (!audio_is_linear_pcm(config->format)) {
6105 return false;
6106 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006107 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6108 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6109 return false;
6110 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006111 }
6112
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006113 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006114 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006115 if (profile == nullptr) {
6116 return false;
6117 }
6118
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006119 return true;
6120}
6121
Shunkai Yao4c3af932024-04-26 04:12:21 +00006122// The Spatializer output is compatible with Haptic use cases if:
6123// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6124// with client if client haptic channel bits were set, or
6125// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6126// including the haptic bits or creating the HapticGenerator effect for same session.
6127bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6128 const audio_config_t* config, audio_session_t sessionId) const {
6129 const auto clientHapticChannel =
6130 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6131 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6132 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6133
6134 if (threadOutputHapticChannel) {
6135 // check format and sampleRate match if client haptic channel mask exist
6136 if (clientHapticChannel) {
6137 return mSpatializerOutput->getFormat() == config->format &&
6138 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6139 }
6140 return true;
6141 } else {
6142 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6143 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6144 // HapticGenerator effect for this session) are not supported.
6145 return clientHapticChannel == 0 &&
6146 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6147 }
6148}
6149
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006150void AudioPolicyManager::checkVirtualizerClientRoutes() {
6151 std::set<audio_stream_type_t> streamsToInvalidate;
6152 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006153 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6154 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006155 audio_attributes_t attr = client->attributes();
6156 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6157 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6158 audio_config_base_t clientConfig = client->config();
6159 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006160 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006161 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006162 streamsToInvalidate.insert(client->stream());
6163 }
6164 }
6165 }
6166
jiabinc44b3462022-12-08 12:52:31 -08006167 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006168}
6169
Eric Laurente191d1b2022-04-15 11:59:25 +02006170
6171bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6172 const sp<SwAudioOutputDescriptor>& outputDesc) {
6173 if (outputDesc->isDuplicated()) {
6174 return false;
6175 }
6176 DeviceVector devices = outputDesc->supportedDevices();
6177 for (size_t i = 0; i < mOutputs.size(); i++) {
6178 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6179 if (desc == outputDesc || desc->isDuplicated()) {
6180 continue;
6181 }
6182 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6183 if (!sharedDevices.isEmpty()
6184 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6185 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6186 return false;
6187 }
6188 }
6189 return true;
6190}
6191
6192
Eric Laurentfa0f6742021-08-17 18:39:44 +02006193status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006194 const audio_attributes_t *attr,
6195 audio_io_handle_t *output) {
6196 *output = AUDIO_IO_HANDLE_NONE;
6197
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006198 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6199 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6200 audio_config_t *configPtr = nullptr;
6201 audio_config_t config;
6202 if (mixerConfig != nullptr) {
6203 config = audio_config_initializer(mixerConfig);
6204 configPtr = &config;
6205 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006206 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006207 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006208 return BAD_VALUE;
6209 }
6210
6211 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006212 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006213 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006214 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006215 return BAD_VALUE;
6216 }
6217
Eric Laurente191d1b2022-04-15 11:59:25 +02006218 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006219 for (size_t i = 0; i < mOutputs.size(); i++) {
6220 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006221 if (!desc->isDuplicated()
6222 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6223 spatializerOutputs.push_back(desc);
6224 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006225 }
6226 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006227 mSpatializerOutput.clear();
6228 bool outputsChanged = false;
6229 for (const auto& desc : spatializerOutputs) {
6230 if (desc->mProfile == profile
6231 && (configPtr == nullptr
6232 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6233 mSpatializerOutput = desc;
6234 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6235 } else {
6236 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6237 " and devices %s", __func__, desc->mIoHandle,
6238 configPtr != nullptr ? configPtr->channel_mask : 0,
6239 devices.toString().c_str());
6240 closeOutput(desc->mIoHandle);
6241 outputsChanged = true;
6242 }
Eric Laurent39095982021-08-24 18:29:27 +02006243 }
6244
Eric Laurente191d1b2022-04-15 11:59:25 +02006245 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006246 sp<SwAudioOutputDescriptor> desc =
6247 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006248 if (desc != nullptr) {
6249 mSpatializerOutput = desc;
6250 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006251 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006252 }
6253
6254 checkVirtualizerClientRoutes();
6255
Eric Laurente191d1b2022-04-15 11:59:25 +02006256 if (outputsChanged) {
6257 mPreviousOutputs = mOutputs;
6258 mpClientInterface->onAudioPortListUpdate();
6259 }
6260
6261 if (mSpatializerOutput == nullptr) {
6262 ALOGV("%s could not open spatializer output with requested config", __func__);
6263 return BAD_VALUE;
6264 }
Eric Laurent39095982021-08-24 18:29:27 +02006265 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006266 ALOGV("%s returning new spatializer output %d", __func__, *output);
6267 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006268}
6269
Eric Laurentfa0f6742021-08-17 18:39:44 +02006270status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6271 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006272 return INVALID_OPERATION;
6273 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006274 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006275 return BAD_VALUE;
6276 }
Eric Laurent39095982021-08-24 18:29:27 +02006277
Eric Laurente191d1b2022-04-15 11:59:25 +02006278 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6279 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6280 closeOutput(mSpatializerOutput->mIoHandle);
6281 //from now on mSpatializerOutput is null
6282 checkVirtualizerClientRoutes();
6283 }
Eric Laurent39095982021-08-24 18:29:27 +02006284
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006285 return NO_ERROR;
6286}
6287
Eric Laurente552edb2014-03-10 17:42:56 -07006288// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006289// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006290// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006291uint32_t AudioPolicyManager::nextAudioPortGeneration()
6292{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006293 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006294}
6295
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006296AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006297 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006298 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006299 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006300 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006301 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006302 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006303 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006304 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006305 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006306 mAudioPortGeneration(1),
6307 mBeaconMuteRefCount(0),
6308 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006309 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006310 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006311 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006312 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006313{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006314}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006315
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006316status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006317 if (mEngine == nullptr) {
6318 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006319 }
6320 mEngine->setObserver(this);
6321 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006322 if (status != NO_ERROR) {
6323 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6324 return status;
6325 }
François Gaffie2110e042015-03-24 08:41:51 +01006326
jiabin29230182023-04-04 21:02:36 +00006327 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6328 // at the end of this function.
6329 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006330 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6331 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6332
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006333 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006334 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006335 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006336
Eric Laurent3a4311c2014-03-17 12:00:47 -07006337 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006338 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6339 defaultOutputDevice == nullptr ||
6340 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6341 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6342 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006343 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006344 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006345 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006346
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006347 // Silence ALOGV statements
6348 property_set("log.tag." LOG_TAG, "D");
6349
Eric Laurente552edb2014-03-10 17:42:56 -07006350 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006351 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006352}
6353
Eric Laurente0720872014-03-11 09:30:41 -07006354AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006355{
Eric Laurente552edb2014-03-10 17:42:56 -07006356 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006357 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006358 }
6359 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006360 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006361 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006362 mAvailableOutputDevices.clear();
6363 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006364 mOutputs.clear();
6365 mInputs.clear();
6366 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006367 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006368 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006369}
6370
Eric Laurente0720872014-03-11 09:30:41 -07006371status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006372{
Eric Laurent87ffa392015-05-22 10:32:38 -07006373 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006374}
6375
Eric Laurente552edb2014-03-10 17:42:56 -07006376// ---
6377
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006378void AudioPolicyManager::onNewAudioModulesAvailable()
6379{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006380 DeviceVector newDevices;
6381 onNewAudioModulesAvailableInt(&newDevices);
6382 if (!newDevices.empty()) {
6383 nextAudioPortGeneration();
6384 mpClientInterface->onAudioPortListUpdate();
6385 }
6386}
6387
6388void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6389{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006390 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006391 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6392 continue;
6393 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006394 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006395 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6396 handle != AUDIO_MODULE_HANDLE_NONE) {
6397 hwModule->setHandle(handle);
6398 } else {
6399 ALOGW("could not load HW module %s", hwModule->getName());
6400 continue;
6401 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006402 }
6403 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006404 // open all output streams needed to access attached devices.
6405 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006406 // This also validates mAvailableOutputDevices list
6407 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6408 if (!outProfile->canOpenNewIo()) {
6409 ALOGE("Invalid Output profile max open count %u for profile %s",
6410 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6411 continue;
6412 }
6413 if (!outProfile->hasSupportedDevices()) {
6414 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6415 continue;
6416 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006417 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6418 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006419 mTtsOutputAvailable = true;
6420 }
6421
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006422 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006423 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006424 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006425 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6426 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006427 } else {
6428 // choose first device present in profile's SupportedDevices also part of
6429 // mAvailableOutputDevices.
6430 if (availProfileDevices.isEmpty()) {
6431 continue;
6432 }
6433 supportedDevice = availProfileDevices.itemAt(0);
6434 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006435 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006436 continue;
6437 }
6438 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6439 mpClientInterface);
6440 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006441 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6442 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006443 AUDIO_STREAM_DEFAULT,
6444 AUDIO_OUTPUT_FLAG_NONE, &output);
6445 if (status != NO_ERROR) {
6446 ALOGW("Cannot open output stream for devices %s on hw module %s",
6447 supportedDevice->toString().c_str(), hwModule->getName());
6448 continue;
6449 }
6450 for (const auto &device : availProfileDevices) {
6451 // give a valid ID to an attached device once confirmed it is reachable
6452 if (!device->isAttached()) {
6453 device->attach(hwModule);
6454 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006455 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006456 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006457 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6458 }
6459 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006460 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006461 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6462 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006463 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006464 }
Eric Laurent39095982021-08-24 18:29:27 +02006465 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006466 outputDesc->close();
6467 } else {
6468 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306469 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006470 DeviceVector(supportedDevice),
6471 true,
6472 0,
6473 NULL);
6474 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006475 }
6476 // open input streams needed to access attached devices to validate
6477 // mAvailableInputDevices list
6478 for (const auto& inProfile : hwModule->getInputProfiles()) {
6479 if (!inProfile->canOpenNewIo()) {
6480 ALOGE("Invalid Input profile max open count %u for profile %s",
6481 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6482 continue;
6483 }
6484 if (!inProfile->hasSupportedDevices()) {
6485 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6486 continue;
6487 }
6488 // chose first device present in profile's SupportedDevices also part of
6489 // available input devices
6490 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006491 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006492 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006493 ALOGV("%s: Input device list is empty! for profile %s",
6494 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006495 continue;
6496 }
6497 sp<AudioInputDescriptor> inputDesc =
6498 new AudioInputDescriptor(inProfile, mpClientInterface);
6499
6500 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6501 status_t status = inputDesc->open(nullptr,
6502 availProfileDevices.itemAt(0),
6503 AUDIO_SOURCE_MIC,
6504 AUDIO_INPUT_FLAG_NONE,
6505 &input);
6506 if (status != NO_ERROR) {
6507 ALOGW("Cannot open input stream for device %s on hw module %s",
6508 availProfileDevices.toString().c_str(),
6509 hwModule->getName());
6510 continue;
6511 }
6512 for (const auto &device : availProfileDevices) {
6513 // give a valid ID to an attached device once confirmed it is reachable
6514 if (!device->isAttached()) {
6515 device->attach(hwModule);
6516 device->importAudioPortAndPickAudioProfile(inProfile, true);
6517 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006518 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006519 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6520 }
6521 }
6522 inputDesc->close();
6523 }
6524 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006525
6526 // Check if spatializer outputs can be closed until used.
6527 // mOutputs vector never contains duplicated outputs at this point.
6528 std::vector<audio_io_handle_t> outputsClosed;
6529 for (size_t i = 0; i < mOutputs.size(); i++) {
6530 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6531 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6532 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6533 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006534 nextAudioPortGeneration();
6535 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6536 if (index >= 0) {
6537 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6538 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6539 patchDesc->getAfHandle(), 0);
6540 mAudioPatches.removeItemsAt(index);
6541 mpClientInterface->onAudioPatchListUpdate();
6542 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006543 desc->close();
6544 }
6545 }
6546 for (auto output : outputsClosed) {
6547 removeOutput(output);
6548 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006549}
6550
Eric Laurent98e38192018-02-15 18:31:53 -08006551void AudioPolicyManager::addOutput(audio_io_handle_t output,
6552 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006553{
Eric Laurent1c333e22014-05-20 10:48:17 -07006554 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006555 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006556 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006557 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006558 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006559}
6560
François Gaffie53615e22015-03-19 09:24:12 +01006561void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6562{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006563 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6564 ALOGV("%s: removing primary output", __func__);
6565 mPrimaryOutput = nullptr;
6566 }
François Gaffie53615e22015-03-19 09:24:12 +01006567 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006568 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006569}
6570
Eric Laurent98e38192018-02-15 18:31:53 -08006571void AudioPolicyManager::addInput(audio_io_handle_t input,
6572 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006573{
Eric Laurent1c333e22014-05-20 10:48:17 -07006574 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006575 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006576}
Eric Laurente552edb2014-03-10 17:42:56 -07006577
François Gaffie11d30102018-11-02 16:09:09 +01006578status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006579 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006580 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006581{
François Gaffie11d30102018-11-02 16:09:09 +01006582 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006583 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006584 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006585
François Gaffie11d30102018-11-02 16:09:09 +01006586 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006587 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006588 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006589 }
Eric Laurente552edb2014-03-10 17:42:56 -07006590
Eric Laurent3b73df72014-03-11 09:06:29 -07006591 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006592 // first call getAudioPort to get the supported attributes from the HAL
6593 struct audio_port_v7 port = {};
6594 device->toAudioPort(&port);
6595 status_t status = mpClientInterface->getAudioPort(&port);
6596 if (status == NO_ERROR) {
6597 device->importAudioPort(port);
6598 }
6599
6600 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006601 for (size_t i = 0; i < mOutputs.size(); i++) {
6602 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006603 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006604 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006605 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6606 mOutputs.keyAt(i), device->toString().c_str());
6607 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006608 }
6609 }
6610 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006611 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006612 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006613 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6614 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006615 if (profile->supportsDevice(device)) {
6616 profiles.add(profile);
6617 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6618 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006619 }
6620 }
6621 }
6622
Eric Laurent7b279bb2015-12-14 10:18:23 -08006623 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006624
Eric Laurente552edb2014-03-10 17:42:56 -07006625 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006626 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006627 return BAD_VALUE;
6628 }
6629
6630 // open outputs for matching profiles if needed. Direct outputs are also opened to
6631 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6632 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006633 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006634
6635 // nothing to do if one output is already opened for this profile
6636 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006637 for (j = 0; j < outputs.size(); j++) {
6638 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006639 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006640 // matching profile: save the sample rates, format and channel masks supported
6641 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006642 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006643 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006644 }
Eric Laurente552edb2014-03-10 17:42:56 -07006645 break;
6646 }
6647 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006648 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006649 continue;
6650 }
6651
Eric Laurent3974e3b2017-12-07 17:58:43 -08006652 if (!profile->canOpenNewIo()) {
6653 ALOGW("Max Output number %u already opened for this profile %s",
6654 profile->maxOpenCount, profile->getTagName().c_str());
6655 continue;
6656 }
6657
Eric Laurent83efe1c2017-07-09 16:51:08 -07006658 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006659 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006660 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6661 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006662 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006663 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006664 profiles.removeAt(profile_index);
6665 profile_index--;
6666 } else {
6667 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006668 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006669 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006670 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6671 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006672 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006673 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006674
François Gaffie11d30102018-11-02 16:09:09 +01006675 if (device_distinguishes_on_address(deviceType)) {
6676 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6677 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306678 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6679 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006680 }
Eric Laurente552edb2014-03-10 17:42:56 -07006681 ALOGV("checkOutputsForDevice(): adding output %d", output);
6682 }
6683 }
6684
6685 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006686 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006687 return BAD_VALUE;
6688 }
Eric Laurentd4692962014-05-05 18:13:44 -07006689 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006690 // check if one opened output is not needed any more after disconnecting one device
6691 for (size_t i = 0; i < mOutputs.size(); i++) {
6692 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006693 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006694 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006695 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006696 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006697 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006698 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006699 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6700 mOutputs.keyAt(i));
6701 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006702 }
Eric Laurente552edb2014-03-10 17:42:56 -07006703 }
6704 }
Eric Laurentd4692962014-05-05 18:13:44 -07006705 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006706 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006707 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6708 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006709 if (!profile->supportsDevice(device)) {
6710 continue;
6711 }
6712 ALOGV("checkOutputsForDevice(): "
6713 "clearing direct output profile %zu on module %s",
6714 j, hwModule->getName());
6715 profile->clearAudioProfiles();
6716 if (!profile->hasDynamicAudioProfile()) {
6717 continue;
6718 }
6719 // When a device is disconnected, if there is an IOProfile that contains dynamic
6720 // profiles and supports the disconnected device, call getAudioPort to repopulate
6721 // the capabilities of the devices that is supported by the IOProfile.
6722 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6723 if (supportedDevice == device ||
6724 !mAvailableOutputDevices.contains(supportedDevice)) {
6725 continue;
6726 }
6727 struct audio_port_v7 port;
6728 supportedDevice->toAudioPort(&port);
6729 status_t status = mpClientInterface->getAudioPort(&port);
6730 if (status == NO_ERROR) {
6731 supportedDevice->importAudioPort(port);
6732 }
Eric Laurente552edb2014-03-10 17:42:56 -07006733 }
6734 }
6735 }
6736 }
6737 return NO_ERROR;
6738}
6739
François Gaffie11d30102018-11-02 16:09:09 +01006740status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006741 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006742{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006743 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006744
François Gaffie11d30102018-11-02 16:09:09 +01006745 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006746 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006747 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006748 }
6749
Eric Laurentd4692962014-05-05 18:13:44 -07006750 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006751 // first call getAudioPort to get the supported attributes from the HAL
6752 struct audio_port_v7 port = {};
6753 device->toAudioPort(&port);
6754 status_t status = mpClientInterface->getAudioPort(&port);
6755 if (status == NO_ERROR) {
6756 device->importAudioPort(port);
6757 }
6758
Eric Laurent0dd51852019-04-19 18:18:58 -07006759 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006760 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006761 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006762 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006763 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006764 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006765 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006766
François Gaffie11d30102018-11-02 16:09:09 +01006767 if (profile->supportsDevice(device)) {
6768 profiles.add(profile);
6769 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6770 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006771 }
6772 }
6773 }
6774
Eric Laurent0dd51852019-04-19 18:18:58 -07006775 if (profiles.isEmpty()) {
6776 ALOGW("%s: No input profile available for device %s",
6777 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006778 return BAD_VALUE;
6779 }
6780
6781 // open inputs for matching profiles if needed. Direct inputs are also opened to
6782 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6783 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6784
Eric Laurent1c333e22014-05-20 10:48:17 -07006785 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006786
Eric Laurentd4692962014-05-05 18:13:44 -07006787 // nothing to do if one input is already opened for this profile
6788 size_t input_index;
6789 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6790 desc = mInputs.valueAt(input_index);
6791 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006792 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006793 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006794 }
Eric Laurentd4692962014-05-05 18:13:44 -07006795 break;
6796 }
6797 }
6798 if (input_index != mInputs.size()) {
6799 continue;
6800 }
6801
Eric Laurent3974e3b2017-12-07 17:58:43 -08006802 if (!profile->canOpenNewIo()) {
6803 ALOGW("Max Input number %u already opened for this profile %s",
6804 profile->maxOpenCount, profile->getTagName().c_str());
6805 continue;
6806 }
6807
Eric Laurentfe231122017-11-17 17:48:06 -08006808 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006809 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006810 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006811
Eric Laurentcf2c0212014-07-25 16:20:43 -07006812 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006813 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006814 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006815 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006816 mpClientInterface->setParameters(input, String8(param));
6817 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006818 }
jiabin12537fc2023-10-12 17:56:08 +00006819 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006820 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006821 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006822 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006823 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006824 }
6825
Eric Laurent0dd51852019-04-19 18:18:58 -07006826 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006827 addInput(input, desc);
6828 }
6829 } // endif input != 0
6830
Eric Laurentcf2c0212014-07-25 16:20:43 -07006831 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006832 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006833 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006834 profiles.removeAt(profile_index);
6835 profile_index--;
6836 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006837 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006838 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006839 }
Eric Laurentd4692962014-05-05 18:13:44 -07006840 ALOGV("checkInputsForDevice(): adding input %d", input);
6841 }
6842 } // end scan profiles
6843
6844 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006845 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006846 return BAD_VALUE;
6847 }
6848 } else {
6849 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006850 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006851 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006852 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006853 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006854 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006855 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006856 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006857 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6858 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006859 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006860 }
6861 }
6862 }
6863 } // end disconnect
6864
6865 return NO_ERROR;
6866}
6867
6868
Eric Laurente0720872014-03-11 09:30:41 -07006869void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006870{
6871 ALOGV("closeOutput(%d)", output);
6872
François Gaffie1c878552018-11-22 16:53:21 +01006873 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6874 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006875 ALOGW("closeOutput() unknown output %d", output);
6876 return;
6877 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006878 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006879 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006880
Eric Laurente552edb2014-03-10 17:42:56 -07006881 // look for duplicated outputs connected to the output being removed.
6882 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006883 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6884 if (dupOutput->isDuplicated() &&
6885 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6886 sp<SwAudioOutputDescriptor> remainingOutput =
6887 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006888 // As all active tracks on duplicated output will be deleted,
6889 // and as they were also referenced on the other output, the reference
6890 // count for their stream type must be adjusted accordingly on
6891 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006892 const bool wasActive = remainingOutput->isActive();
6893 // Note: no-op on the closing output where all clients has already been set inactive
6894 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006895 // stop() will be a no op if the output is still active but is needed in case all
6896 // active streams refcounts where cleared above
6897 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006898 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006899 }
Eric Laurente552edb2014-03-10 17:42:56 -07006900 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6901 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6902
6903 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006904 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006905 }
6906 }
6907
Eric Laurent05b90f82014-08-27 15:32:29 -07006908 nextAudioPortGeneration();
6909
François Gaffie1c878552018-11-22 16:53:21 +01006910 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006911 if (index >= 0) {
6912 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006913 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6914 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006915 mAudioPatches.removeItemsAt(index);
6916 mpClientInterface->onAudioPatchListUpdate();
6917 }
6918
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006919 if (closingOutputWasActive) {
6920 closingOutput->stop();
6921 }
François Gaffie1c878552018-11-22 16:53:21 +01006922 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006923 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6924 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6925 for (const auto device : closingOutput->devices()) {
6926 device->setPreferredConfig(nullptr);
6927 }
6928 }
Eric Laurente552edb2014-03-10 17:42:56 -07006929
François Gaffie53615e22015-03-19 09:24:12 +01006930 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006931 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006932 if (closingOutput == mSpatializerOutput) {
6933 mSpatializerOutput.clear();
6934 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006935
6936 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6937 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006938 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006939 bool directOutputOpen = false;
6940 for (size_t i = 0; i < mOutputs.size(); i++) {
6941 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6942 directOutputOpen = true;
6943 break;
6944 }
6945 }
6946 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006947 ALOGV("no direct outputs open, reset MSD patches");
6948 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6949 // how output devices for patching are resolved. Avoid by caching and reusing the
6950 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6951 // devices to patch to. This may be complicated by the fact that devices may become
6952 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006953 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006954 }
6955 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006956}
6957
6958void AudioPolicyManager::closeInput(audio_io_handle_t input)
6959{
6960 ALOGV("closeInput(%d)", input);
6961
6962 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6963 if (inputDesc == NULL) {
6964 ALOGW("closeInput() unknown input %d", input);
6965 return;
6966 }
6967
Eric Laurent6a94d692014-05-20 11:18:06 -07006968 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006969
François Gaffie11d30102018-11-02 16:09:09 +01006970 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006971 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006972 if (index >= 0) {
6973 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006974 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6975 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006976 mAudioPatches.removeItemsAt(index);
6977 mpClientInterface->onAudioPatchListUpdate();
6978 }
6979
François Gaffie6ebbce02023-07-19 13:27:53 +02006980 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006981 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006982 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006983
François Gaffie11d30102018-11-02 16:09:09 +01006984 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6985 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006986 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006987 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006988 }
Eric Laurente552edb2014-03-10 17:42:56 -07006989}
6990
François Gaffie11d30102018-11-02 16:09:09 +01006991SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6992 const DeviceVector &devices,
6993 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006994{
6995 SortedVector<audio_io_handle_t> outputs;
6996
François Gaffie11d30102018-11-02 16:09:09 +01006997 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006998 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006999 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007000 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007001 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007002 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007003 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007004 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007005 outputs.add(openOutputs.keyAt(i));
7006 }
7007 }
7008 return outputs;
7009}
7010
Mikhail Naganov37977152018-07-11 15:54:44 -07007011void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7012{
7013 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7014 // output is suspended before any tracks are moved to it
7015 checkA2dpSuspend();
7016 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007017 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007018 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007019 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007020 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007021 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7022 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7023 // configuration changes will ultimately be rerouted correctly. We can still avoid
7024 // unnecessary rerouting by caching and reusing the arguments to
7025 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7026 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007027 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007028 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007029 // an event that changed routing likely occurred, inform upper layers
7030 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007031}
7032
François Gaffiec005e562018-11-06 15:04:49 +01007033bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7034 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007035{
François Gaffiec005e562018-11-06 15:04:49 +01007036 return mEngine->getProductStrategyForAttributes(lAttr) ==
7037 mEngine->getProductStrategyForAttributes(rAttr);
7038}
7039
Francois Gaffieff1eb522020-05-06 18:37:04 +02007040void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7041{
7042 for (size_t i = 0; i < mAudioSources.size(); i++) {
7043 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7044 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007045 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007046 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007047 connectAudioSource(sourceDesc);
7048 }
7049 }
7050}
7051
7052void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7053{
7054 for (size_t i = 0; i < mAudioSources.size(); i++) {
7055 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7056 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7057 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7058 disconnectAudioSource(sourceDesc);
7059 }
7060 }
7061}
7062
François Gaffiec005e562018-11-06 15:04:49 +01007063void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7064{
7065 auto psId = mEngine->getProductStrategyForAttributes(attr);
7066
7067 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7068 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007069
François Gaffie11d30102018-11-02 16:09:09 +01007070 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7071 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007072
Eric Laurentc209fe42020-06-05 18:11:23 -07007073 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007074 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007075 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007076 // take into account dynamic audio policies related changes: if a client is now associated
7077 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007078 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007079 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7080 if (desc->isDuplicated()) {
7081 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007082 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007083 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7084 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7085 continue;
7086 }
7087 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007088 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007089 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7090 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7091 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007092 if (status != OK) {
7093 continue;
7094 }
yucliuf4de36d2020-09-14 14:57:56 -07007095 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007096 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007097 maxLatency = desc->latency();
7098 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007099 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007100 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007101 }
7102 }
7103
Eric Laurent56ed8842022-11-15 16:04:41 +01007104 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007105 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7106 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007107 for (audio_io_handle_t srcOut : srcOutputs) {
7108 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007109 if (desc == nullptr) continue;
7110
7111 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007112 maxLatency = desc->latency();
7113 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007114
Eric Laurent56ed8842022-11-15 16:04:41 +01007115 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007116 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007117 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007118 // a client on a non direct outputs has necessarily a linear PCM format
7119 // so we can call selectOutput() safely
7120 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7121 client->flags(),
7122 client->config().format,
7123 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007124 client->config().sample_rate,
7125 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007126 if (newOutput != srcOut) {
7127 invalidate = true;
7128 break;
7129 }
7130 } else {
7131 sp<IOProfile> profile = getProfileForOutput(newDevices,
7132 client->config().sample_rate,
7133 client->config().format,
7134 client->config().channel_mask,
7135 client->flags(),
7136 true /* directOnly */);
7137 if (profile != desc->mProfile) {
7138 invalidate = true;
7139 break;
7140 }
7141 }
7142 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007143 // mute strategy while moving tracks from one output to another
7144 if (invalidate) {
7145 invalidatedOutputs.push_back(desc);
7146 if (desc->isStrategyActive(psId)) {
7147 setStrategyMute(psId, true, desc);
7148 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7149 newDevices.types());
7150 }
Eric Laurente552edb2014-03-10 17:42:56 -07007151 }
François Gaffiec005e562018-11-06 15:04:49 +01007152 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007153 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007154 connectAudioSource(source);
7155 }
Eric Laurente552edb2014-03-10 17:42:56 -07007156 }
7157
Eric Laurent56ed8842022-11-15 16:04:41 +01007158 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7159 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7160 std::to_string(srcOutputs[0]).c_str(),
7161 std::to_string(dstOutputs[0]).c_str());
7162
François Gaffiec005e562018-11-06 15:04:49 +01007163 // Move effects associated to this stream from previous output to new output
7164 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007165 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007166 }
François Gaffiec005e562018-11-06 15:04:49 +01007167 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007168 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007169 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007170 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007171 desc->setTracksInvalidatedStatusByStrategy(psId);
7172 }
Eric Laurente552edb2014-03-10 17:42:56 -07007173 }
7174 }
7175}
7176
Eric Laurente0720872014-03-11 09:30:41 -07007177void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007178{
François Gaffiec005e562018-11-06 15:04:49 +01007179 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7180 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7181 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007182 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007183 }
Eric Laurente552edb2014-03-10 17:42:56 -07007184}
7185
Kevin Rocard153f92d2018-12-18 18:33:28 -08007186void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007187 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007188 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007189 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007190 for (size_t i = 0; i < mOutputs.size(); i++) {
7191 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7192 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007193 sp<AudioPolicyMix> primaryMix;
7194 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007195 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007196 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7197 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7198 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007199 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7200 for (auto &secondaryMix : secondaryMixes) {
7201 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7202 if (outputDesc != nullptr &&
7203 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7204 secondaryDescs.push_back(outputDesc);
7205 }
7206 }
7207
jiabinc44b3462022-12-08 12:52:31 -08007208 if (status != OK &&
7209 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7210 // When it failed to query secondary output, only invalidate the client that is not
7211 // MMAP. The reason is that MMAP stream will not support secondary output.
7212 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007213 } else if (!std::equal(
7214 client->getSecondaryOutputs().begin(),
7215 client->getSecondaryOutputs().end(),
7216 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007217 if (!audio_is_linear_pcm(client->config().format)) {
7218 // If the format is not PCM, the tracks should be invalidated to get correct
7219 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007220 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007221 } else {
7222 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7223 std::vector<audio_io_handle_t> secondaryOutputIds;
7224 for (const auto &secondaryDesc: secondaryDescs) {
7225 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7226 weakSecondaryDescs.push_back(secondaryDesc);
7227 }
7228 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7229 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007230 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007231 }
7232 }
7233 }
jiabin10a03f12021-05-07 23:46:28 +00007234 if (!trackSecondaryOutputs.empty()) {
7235 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7236 }
jiabinc44b3462022-12-08 12:52:31 -08007237 if (!clientsToInvalidate.empty()) {
7238 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7239 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007240 }
7241}
7242
Eric Laurent2517af32020-11-25 15:31:27 +01007243bool AudioPolicyManager::isScoRequestedForComm() const {
7244 AudioDeviceTypeAddrVector devices;
7245 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7246 for (const auto &device : devices) {
7247 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7248 return true;
7249 }
7250 }
7251 return false;
7252}
7253
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007254bool AudioPolicyManager::isHearingAidUsedForComm() const {
7255 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7256 true /*fromCache*/);
7257 for (const auto &device : devices) {
7258 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7259 return true;
7260 }
7261 }
7262 return false;
7263}
7264
7265
Eric Laurente0720872014-03-11 09:30:41 -07007266void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007267{
François Gaffie53615e22015-03-19 09:24:12 +01007268 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007269 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007270 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007271 return;
7272 }
7273
Eric Laurent3a4311c2014-03-17 12:00:47 -07007274 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007275 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7276 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007277 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007278
7279 // if suspended, restore A2DP output if:
7280 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007281 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007282 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007283 //
Eric Laurentf732e072016-08-03 19:30:28 -07007284 // if not suspended, suspend A2DP output if:
7285 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007286 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007287 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007288 //
7289 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007290 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007291 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007292 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007293 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007294
7295 mpClientInterface->restoreOutput(a2dpOutput);
7296 mA2dpSuspended = false;
7297 }
7298 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007299 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007300 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007301 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007302 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007303
7304 mpClientInterface->suspendOutput(a2dpOutput);
7305 mA2dpSuspended = true;
7306 }
7307 }
7308}
7309
François Gaffie11d30102018-11-02 16:09:09 +01007310DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7311 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007312{
François Gaffiedb1755b2023-09-01 11:50:35 +02007313 if (outputDesc == nullptr) {
7314 return DeviceVector{};
7315 }
François Gaffie11d30102018-11-02 16:09:09 +01007316
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007317 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007318 if (index >= 0) {
7319 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007320 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007321 ALOGV("%s device %s forced by patch %d", __func__,
7322 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7323 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007324 }
7325 }
7326
Dean Wheatley514b4312020-06-17 21:45:00 +10007327 // Do not retrieve engine device for outputs through MSD
7328 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7329 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7330 return outputDesc->devices();
7331 }
7332
Eric Laurent97ac8712018-07-27 18:59:02 -07007333 // Honor explicit routing requests only if no client using default routing is active on this
7334 // input: a specific app can not force routing for other apps by setting a preferred device.
7335 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007336 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007337 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007338 if (device != nullptr) {
7339 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007340 }
7341
François Gaffiea807ef92018-11-05 10:44:33 +01007342 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7343 // of setForceUse / Default Bus device here
7344 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7345 if (device != nullptr) {
7346 return DeviceVector(device);
7347 }
7348
François Gaffiedb1755b2023-09-01 11:50:35 +02007349 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007350 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7351 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7352 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307353 auto hasStreamActive = [&](auto stream) {
7354 return hasStream(streams, stream) && isStreamActive(stream, 0);
7355 };
Eric Laurent484e9272018-06-07 17:29:23 -07007356
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307357 auto doGetOutputDevicesForVoice = [&]() {
7358 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007359 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307360 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007361 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7362 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307363 };
7364
7365 // With low-latency playing on speaker, music on WFD, when the first low-latency
7366 // output is stopped, getNewOutputDevices checks for a product strategy
7367 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007368 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307369 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7370 // stream is associated to the output descriptor.
7371 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7372 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7373 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7374 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007375 // Retrieval of devices for voice DL is done on primary output profile, cannot
7376 // check the route (would force modifying configuration file for this profile)
7377 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7378 break;
7379 }
Eric Laurente552edb2014-03-10 17:42:56 -07007380 }
François Gaffiec005e562018-11-06 15:04:49 +01007381 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007382 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007383}
7384
François Gaffie11d30102018-11-02 16:09:09 +01007385sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7386 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007387{
François Gaffie11d30102018-11-02 16:09:09 +01007388 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007389
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007390 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007391 if (index >= 0) {
7392 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007393 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007394 ALOGV("getNewInputDevice() device %s forced by patch %d",
7395 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7396 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007397 }
7398 }
7399
Eric Laurent97ac8712018-07-27 18:59:02 -07007400 // Honor explicit routing requests only if no client using default routing is active on this
7401 // input: a specific app can not force routing for other apps by setting a preferred device.
7402 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007403 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7404 if (device != nullptr) {
7405 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007406 }
7407
Eric Laurentdc95a252018-04-12 12:46:56 -07007408 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007409 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007410 audio_attributes_t attributes;
7411 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007412 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007413 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7414 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007415 attributes = topClient->attributes();
7416 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007417 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007418 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007419 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7420 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007421 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007422 }
7423
Francois Gaffie716e1432019-01-14 16:58:59 +01007424 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7425 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007426 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007427 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007428 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007429 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007430
Eric Laurente552edb2014-03-10 17:42:56 -07007431 return device;
7432}
7433
Eric Laurent794fde22016-03-11 09:50:45 -08007434bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7435 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007436 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007437}
7438
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007439status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007440 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007441 if (devices == nullptr) {
7442 return BAD_VALUE;
7443 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007444
Andy Hung6d23c0f2022-02-16 09:37:15 -08007445 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007446 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7447 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007448 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007449 for (const auto& device : curDevices) {
7450 devices->push_back(device->getDeviceTypeAddr());
7451 }
7452 return NO_ERROR;
7453}
7454
Eric Laurente0720872014-03-11 09:30:41 -07007455void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007456 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007457 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007458 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007459 updateDevicesAndOutputs();
7460 break;
7461 default:
7462 break;
7463 }
7464}
7465
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007466uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007467
7468 // skip beacon mute management if a dedicated TTS output is available
7469 if (mTtsOutputAvailable) {
7470 return 0;
7471 }
7472
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007473 switch(event) {
7474 case STARTING_OUTPUT:
7475 mBeaconMuteRefCount++;
7476 break;
7477 case STOPPING_OUTPUT:
7478 if (mBeaconMuteRefCount > 0) {
7479 mBeaconMuteRefCount--;
7480 }
7481 break;
7482 case STARTING_BEACON:
7483 mBeaconPlayingRefCount++;
7484 break;
7485 case STOPPING_BEACON:
7486 if (mBeaconPlayingRefCount > 0) {
7487 mBeaconPlayingRefCount--;
7488 }
7489 break;
7490 }
7491
7492 if (mBeaconMuteRefCount > 0) {
7493 // any playback causes beacon to be muted
7494 return setBeaconMute(true);
7495 } else {
7496 // no other playback: unmute when beacon starts playing, mute when it stops
7497 return setBeaconMute(mBeaconPlayingRefCount == 0);
7498 }
7499}
7500
7501uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7502 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7503 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7504 // keep track of muted state to avoid repeating mute/unmute operations
7505 if (mBeaconMuted != mute) {
7506 // mute/unmute AUDIO_STREAM_TTS on all outputs
7507 ALOGV("\t muting %d", mute);
7508 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007509 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7510 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7511 ALOGV("\t no tts volume source available");
7512 return 0;
7513 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007514 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007515 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007516 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007517 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007518 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007519 maxLatency = latency;
7520 }
7521 }
7522 mBeaconMuted = mute;
7523 return maxLatency;
7524 }
7525 return 0;
7526}
7527
Eric Laurente0720872014-03-11 09:30:41 -07007528void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007529{
François Gaffiec005e562018-11-06 15:04:49 +01007530 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007531 mPreviousOutputs = mOutputs;
7532}
7533
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007534uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007535 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007536 uint32_t delayMs)
7537{
7538 // mute/unmute strategies using an incompatible device combination
7539 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7540 // if unmuting, unmute only after the specified delay
7541 if (outputDesc->isDuplicated()) {
7542 return 0;
7543 }
7544
7545 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007546 DeviceVector devices = outputDesc->devices();
7547 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007548
François Gaffiec005e562018-11-06 15:04:49 +01007549 auto productStrategies = mEngine->getOrderedProductStrategies();
7550 for (const auto &productStrategy : productStrategies) {
7551 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7552 DeviceVector curDevices =
7553 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7554 curDevices = curDevices.filter(outputDesc->supportedDevices());
7555 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007556 bool doMute = false;
7557
François Gaffiec005e562018-11-06 15:04:49 +01007558 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007559 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007560 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7561 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007562 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007563 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007564 }
Eric Laurent99401132014-05-07 19:48:15 -07007565 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007566 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007567 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007568 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007569 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007570 continue;
7571 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307572 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007573 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7574 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7575 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007576 if (mute) {
7577 // FIXME: should not need to double latency if volume could be applied
7578 // immediately by the audioflinger mixer. We must account for the delay
7579 // between now and the next time the audioflinger thread for this output
7580 // will process a buffer (which corresponds to one buffer size,
7581 // usually 1/2 or 1/4 of the latency).
7582 if (muteWaitMs < desc->latency() * 2) {
7583 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007584 }
7585 }
7586 }
7587 }
7588 }
7589 }
7590
Eric Laurent99401132014-05-07 19:48:15 -07007591 // temporary mute output if device selection changes to avoid volume bursts due to
7592 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007593 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007594 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007595
Eric Laurentdc462862016-07-19 12:29:53 -07007596 if (muteWaitMs < tempMuteWaitMs) {
7597 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007598 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007599
7600 // If recommended duration is defined, replace temporary mute duration to avoid
7601 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7602 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7603 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7604 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7605 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7606
François Gaffieaaac0fd2018-11-22 17:56:39 +01007607 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7608 // make sure that we do not start the temporary mute period too early in case of
7609 // delayed device change
7610 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7611 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007612 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007613 }
7614 }
7615
Eric Laurente552edb2014-03-10 17:42:56 -07007616 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7617 if (muteWaitMs > delayMs) {
7618 muteWaitMs -= delayMs;
7619 usleep(muteWaitMs * 1000);
7620 return muteWaitMs;
7621 }
7622 return 0;
7623}
7624
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307625uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7626 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007627 const DeviceVector &devices,
7628 bool force,
7629 int delayMs,
7630 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007631 bool requiresMuteCheck, bool requiresVolumeCheck,
7632 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007633{
jiabin3ff8d7d2022-12-13 06:27:44 +00007634 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307635 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7636 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7637 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007638 uint32_t muteWaitMs;
7639
7640 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307641 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007642 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307643 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007644 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007645 return muteWaitMs;
7646 }
Eric Laurente552edb2014-03-10 17:42:56 -07007647
7648 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007649 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007650 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007651 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007652
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307653 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7654 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007655
7656 if (!filteredDevices.isEmpty()) {
7657 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007658 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007659
7660 // if the outputs are not materially active, there is no need to mute.
7661 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007662 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007663 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307664 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7665 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007666 muteWaitMs = 0;
7667 }
Eric Laurente552edb2014-03-10 17:42:56 -07007668
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007669 bool outputRouted = outputDesc->isRouted();
7670
Eric Laurent79ea9582020-06-11 18:49:24 -07007671 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7672 // output profile or if new device is not supported AND previous device(s) is(are) still
7673 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007674 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307675 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7676 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007677 // restore previous device after evaluating strategy mute state
7678 outputDesc->setDevices(prevDevices);
7679 return muteWaitMs;
7680 }
7681
Eric Laurente552edb2014-03-10 17:42:56 -07007682 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007683 // the requested device is AUDIO_DEVICE_NONE
7684 // OR the requested device is the same as current device
7685 // AND force is not specified
7686 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007687 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007688 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307689 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7690 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7691 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007692 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307693 ALOGV("%s %s setting same device on routed output, force apply volumes",
7694 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007695 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7696 }
Eric Laurente552edb2014-03-10 17:42:56 -07007697 return muteWaitMs;
7698 }
7699
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307700 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7701 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007702
Eric Laurente552edb2014-03-10 17:42:56 -07007703 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007704 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007705 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007706 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007707 PatchBuilder patchBuilder;
7708 patchBuilder.addSource(outputDesc);
7709 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7710 for (const auto &filteredDevice : filteredDevices) {
7711 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007712 }
7713
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007714 // Add half reported latency to delayMs when muteWaitMs is null in order
7715 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007716 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7717 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7718 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007719 }
Eric Laurente552edb2014-03-10 17:42:56 -07007720
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007721 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7722 if (!skipMuteDelay) {
7723 // update stream volumes according to new device
7724 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7725 }
Eric Laurente552edb2014-03-10 17:42:56 -07007726
7727 return muteWaitMs;
7728}
7729
Eric Laurentc75307b2015-03-17 15:29:32 -07007730status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007731 int delayMs,
7732 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007733{
Eric Laurent6a94d692014-05-20 11:18:06 -07007734 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007735 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7736 return INVALID_OPERATION;
7737 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007738 if (patchHandle) {
7739 index = mAudioPatches.indexOfKey(*patchHandle);
7740 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007741 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007742 }
7743 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007744 return INVALID_OPERATION;
7745 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007746 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007747 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007748 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007749 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007750 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007751 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007752 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007753 return status;
7754}
7755
7756status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007757 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007758 bool force,
7759 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007760{
7761 status_t status = NO_ERROR;
7762
Eric Laurent1f2f2232014-06-02 12:01:23 -07007763 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007764 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7765 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007766
François Gaffie11d30102018-11-02 16:09:09 +01007767 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007768 PatchBuilder patchBuilder;
7769 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007770 // AUDIO_SOURCE_HOTWORD is for internal use only:
7771 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007772 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7773 auto result = usecase;
7774 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7775 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7776 }
7777 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007778 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007779 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007780 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007781 }
7782 }
7783 return status;
7784}
7785
Eric Laurent6a94d692014-05-20 11:18:06 -07007786status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7787 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007788{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007789 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007790 ssize_t index;
7791 if (patchHandle) {
7792 index = mAudioPatches.indexOfKey(*patchHandle);
7793 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007794 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007795 }
7796 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007797 return INVALID_OPERATION;
7798 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007799 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007800 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007801 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007802 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007803 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007804 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007805 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007806 return status;
7807}
7808
François Gaffie11d30102018-11-02 16:09:09 +01007809sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007810 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007811 audio_format_t& format,
7812 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007813 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007814{
7815 // Choose an input profile based on the requested capture parameters: select the first available
7816 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007817 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007818
Atneya Nair0f0a8032022-12-12 16:20:12 -08007819 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7820 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7821 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7822
7823 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007824
jiabin2fd710d2022-05-02 23:20:22 +00007825 for (;;) {
7826 sp<IOProfile> firstInexact = nullptr;
7827 uint32_t updatedSamplingRate = 0;
7828 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7829 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7830 for (const auto& hwModule : mHwModules) {
7831 for (const auto& profile : hwModule->getInputProfiles()) {
7832 // profile->log();
7833 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007834 if (profile->getCompatibilityScore(
7835 DeviceVector(device),
7836 samplingRate,
7837 &updatedSamplingRate,
7838 format,
7839 &updatedFormat,
7840 channelMask,
7841 &updatedChannelMask,
7842 // FIXME ugly cast
7843 (audio_output_flags_t) flags,
7844 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7845 samplingRate = updatedSamplingRate;
7846 format = updatedFormat;
7847 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007848 return profile;
7849 }
jiabin66acc432024-02-06 00:57:36 +00007850 if (firstInexact == nullptr
7851 && profile->getCompatibilityScore(
7852 DeviceVector(device),
7853 samplingRate,
7854 &updatedSamplingRate,
7855 format,
7856 &updatedFormat,
7857 channelMask,
7858 &updatedChannelMask,
7859 // FIXME ugly cast
7860 (audio_output_flags_t) flags,
7861 false /*exactMatchRequiredForInputFlags*/)
7862 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007863 firstInexact = profile;
7864 }
7865 }
7866 }
7867
7868 if (firstInexact != nullptr) {
7869 samplingRate = updatedSamplingRate;
7870 format = updatedFormat;
7871 channelMask = updatedChannelMask;
7872 return firstInexact;
7873 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7874 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7875 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7876 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7877 flags = AUDIO_INPUT_FLAG_NONE;
7878 } else { // fail
7879 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7880 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7881 samplingRate, format, channelMask, oriFlags);
7882 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007883 }
7884 }
jiabin2fd710d2022-05-02 23:20:22 +00007885
7886 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007887}
7888
François Gaffieaaac0fd2018-11-22 17:56:39 +01007889float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7890 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007891 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007892 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007893{
jiabin9a3361e2019-10-01 09:38:30 -07007894 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007895
7896 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7897 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7898 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7899 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007900 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7901 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7902 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7903 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7904 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007905 // Verify that the current volume source is not the ringer volume to prevent recursively
7906 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7907 // to the same volume group.
7908 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007909 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7910 mOutputs.isActive(ringVolumeSrc, 0)) {
7911 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007912 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007913 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007914 }
7915
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007916 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007917 if ((volumeSource != callVolumeSrc && (isInCall() ||
7918 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007919 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007920 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7921 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007922 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7923 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7924 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007925 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007926 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007927 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007928 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007929 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007930 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007931 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7932 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7933 // programmatically muted.
7934 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7935 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7936 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007937 bool exemptFromCapping =
7938 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7939 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007940 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7941 volumeSource, volumeDb);
7942 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007943 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7944 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7945 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007946 }
7947 }
Eric Laurente552edb2014-03-10 17:42:56 -07007948 // if a headset is connected, apply the following rules to ring tones and notifications
7949 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007950 // - always attenuate notifications volume by 6dB
7951 // - attenuate ring tones volume by 6dB unless music is not playing and
7952 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007953 // - if music is playing, always limit the volume to current music volume,
7954 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007955 if (!Intersection(deviceTypes,
7956 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7957 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007958 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7959 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007960 ((volumeSource == alarmVolumeSrc ||
7961 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007962 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7963 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7964 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007965 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7966 curves.canBeMuted()) {
7967
Eric Laurente552edb2014-03-10 17:42:56 -07007968 // when the phone is ringing we must consider that music could have been paused just before
7969 // by the music application and behave as if music was active if the last music track was
7970 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007971 // Verify that the current volume source is not the music volume to prevent recursively
7972 // calling to compute volume. This could happen in cases where music and
7973 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7974 if (volumeSource != musicVolumeSrc &&
7975 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7976 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007977 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007978 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007979 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7980 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007981 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007982 float musicVolDb = computeVolume(musicCurves,
7983 musicVolumeSrc,
7984 musicCurves.getVolumeIndex(musicDevice),
7985 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007986 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7987 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7988 if (volumeDb > minVolDb) {
7989 volumeDb = minVolDb;
7990 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007991 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007992 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7993 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7994 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007995 // on A2DP, also ensure notification volume is not too low compared to media when
7996 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007997 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007998 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007999 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8000 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008001 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8002 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008003 }
8004 }
jiabin9a3361e2019-10-01 09:38:30 -07008005 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008006 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008007 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008008 }
8009 }
8010
François Gaffie43c73442018-11-08 08:21:55 +01008011 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008012}
8013
Eric Laurent3839bc02018-07-10 18:33:34 -07008014int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008015 VolumeSource fromVolumeSource,
8016 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008017{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008018 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008019 return srcIndex;
8020 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008021 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8022 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008023 float minSrc = (float)srcCurves.getVolumeIndexMin();
8024 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8025 float minDst = (float)dstCurves.getVolumeIndexMin();
8026 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008027
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008028 // preserve mute request or correct range
8029 if (srcIndex < minSrc) {
8030 if (srcIndex == 0) {
8031 return 0;
8032 }
8033 srcIndex = minSrc;
8034 } else if (srcIndex > maxSrc) {
8035 srcIndex = maxSrc;
8036 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008037 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8038}
8039
François Gaffieaaac0fd2018-11-22 17:56:39 +01008040status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8041 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008042 int index,
8043 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008044 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008045 int delayMs,
8046 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008047{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008048 // do not change actual attributes volume if the attributes is muted
8049 if (outputDesc->isMuted(volumeSource)) {
8050 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8051 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008052 return NO_ERROR;
8053 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008054
Eric Laurentae6e88c2024-01-10 14:42:57 +01008055 bool isVoiceVolSrc;
8056 bool isBtScoVolSrc;
8057 if (!isVolumeConsistentForCalls(
8058 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008059 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008060 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008061 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008062 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008063
jiabin9a3361e2019-10-01 09:38:30 -07008064 if (deviceTypes.empty()) {
8065 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008066 index = curves.getVolumeIndex(deviceTypes);
8067 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
8068 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008069 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008070
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008071 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8072 ALOGE("invalid volume index range");
8073 return BAD_VALUE;
8074 }
8075
jiabin9a3361e2019-10-01 09:38:30 -07008076 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8077 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07008078 // Force VoIP volume to max for bluetooth SCO device except if muted
8079 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07008080 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008081 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008082 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008083 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008084 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8085 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008086
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008087 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008088 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008089 }
Eric Laurente552edb2014-03-10 17:42:56 -07008090 return NO_ERROR;
8091}
8092
Eric Laurentae6e88c2024-01-10 14:42:57 +01008093void AudioPolicyManager::setVoiceVolume(
8094 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
8095 float voiceVolume;
8096 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
8097 // by the headset
8098 if (isVoiceVolSrc) {
8099 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8100 } else {
8101 voiceVolume = index == 0 ? 0.0 : 1.0;
8102 }
8103 if (voiceVolume != mLastVoiceVolume) {
8104 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8105 mLastVoiceVolume = voiceVolume;
8106 }
8107}
8108
8109bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8110 const DeviceTypeSet& deviceTypes,
8111 bool& isVoiceVolSrc,
8112 bool& isBtScoVolSrc,
8113 const char* caller) {
8114 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8115 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8116 const bool isScoRequested = isScoRequestedForComm();
8117 const bool isHAUsed = isHearingAidUsedForComm();
8118
8119 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8120 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8121
8122 if ((callVolSrc != btScoVolSrc) &&
8123 ((isVoiceVolSrc && isScoRequested) ||
8124 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8125 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8126 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8127 volumeSource, isScoRequested ? " " : " not ");
8128 return false;
8129 }
8130 return true;
8131}
8132
Eric Laurentc75307b2015-03-17 15:29:32 -07008133void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008134 const DeviceTypeSet& deviceTypes,
8135 int delayMs,
8136 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008137{
jiabincd510522020-01-22 09:40:55 -08008138 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008139 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8140 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8141 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008142 curves.getVolumeIndex(deviceTypes),
8143 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008144 }
8145}
8146
François Gaffiec005e562018-11-06 15:04:49 +01008147void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8148 bool on,
8149 const sp<AudioOutputDescriptor>& outputDesc,
8150 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008151 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008152{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008153 std::vector<VolumeSource> sourcesToMute;
8154 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8155 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8156 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008157 VolumeSource source = toVolumeSource(attributes, false);
8158 if ((source != VOLUME_SOURCE_NONE) &&
8159 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8160 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008161 sourcesToMute.push_back(source);
8162 }
Eric Laurente552edb2014-03-10 17:42:56 -07008163 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008164 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008165 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008166 }
8167
Eric Laurente552edb2014-03-10 17:42:56 -07008168}
8169
François Gaffieaaac0fd2018-11-22 17:56:39 +01008170void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8171 bool on,
8172 const sp<AudioOutputDescriptor>& outputDesc,
8173 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008174 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008175{
jiabin9a3361e2019-10-01 09:38:30 -07008176 if (deviceTypes.empty()) {
8177 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008178 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008179 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008180 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008181 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008182 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008183 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008184 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8185 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008186 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008187 }
8188 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008189 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8190 // ignored
8191 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008192 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008193 if (!outputDesc->isMuted(volumeSource)) {
8194 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008195 return;
8196 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008197 if (outputDesc->decMuteCount(volumeSource) == 0) {
8198 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008199 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008200 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008201 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008202 delayMs);
8203 }
8204 }
8205}
8206
François Gaffie53615e22015-03-19 09:24:12 +01008207bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8208{
François Gaffiec005e562018-11-06 15:04:49 +01008209 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008210 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8211 return true;
8212 }
8213
8214 // has known usage?
8215 switch (paa->usage) {
8216 case AUDIO_USAGE_UNKNOWN:
8217 case AUDIO_USAGE_MEDIA:
8218 case AUDIO_USAGE_VOICE_COMMUNICATION:
8219 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8220 case AUDIO_USAGE_ALARM:
8221 case AUDIO_USAGE_NOTIFICATION:
8222 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8223 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8224 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8225 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8226 case AUDIO_USAGE_NOTIFICATION_EVENT:
8227 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8228 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8229 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8230 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008231 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008232 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008233 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008234 case AUDIO_USAGE_EMERGENCY:
8235 case AUDIO_USAGE_SAFETY:
8236 case AUDIO_USAGE_VEHICLE_STATUS:
8237 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008238 break;
8239 default:
8240 return false;
8241 }
8242 return true;
8243}
8244
François Gaffie2110e042015-03-24 08:41:51 +01008245audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8246{
8247 return mEngine->getForceUse(usage);
8248}
8249
Eric Laurent96d1dda2022-03-14 17:14:19 +01008250bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008251 return isStateInCall(mEngine->getPhoneState());
8252}
8253
Eric Laurent96d1dda2022-03-14 17:14:19 +01008254bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008255 return is_state_in_call(state);
8256}
8257
Eric Laurentf9cccec2022-11-16 19:12:00 +01008258bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008259 audio_mode_t mode = mEngine->getPhoneState();
8260 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008261 || (mode == AUDIO_MODE_CALL_SCREEN)
8262 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008263}
8264
Eric Laurentf9cccec2022-11-16 19:12:00 +01008265bool AudioPolicyManager::isInCallOrScreening() const {
8266 audio_mode_t mode = mEngine->getPhoneState();
8267 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8268}
8269
Eric Laurentd60560a2015-04-10 11:31:20 -07008270void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8271{
8272 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008273 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008274 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008275 sourceDesc->sinkDevice()->equals(deviceDesc))
8276 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008277 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008278 }
8279 }
8280
8281 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8282 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8283 bool release = false;
8284 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8285 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8286 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8287 source->ext.device.type == deviceDesc->type()) {
8288 release = true;
8289 }
8290 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008291 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008292 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8293 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8294 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008295 sink->ext.device.type == deviceDesc->type() &&
8296 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8297 || strncmp(sink->ext.device.address, address,
8298 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008299 release = true;
8300 }
8301 }
8302 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008303 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8304 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008305 }
8306 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008307
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008308 mInputs.clearSessionRoutesForDevice(deviceDesc);
8309
Francois Gaffie716e1432019-01-14 16:58:59 +01008310 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008311}
8312
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008313void AudioPolicyManager::modifySurroundFormats(
8314 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008315 std::unordered_set<audio_format_t> enforcedSurround(
8316 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008317 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008318 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008319 allSurround.insert(pair.first);
8320 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8321 }
Phil Burk09bc4612016-02-24 15:58:15 -08008322
8323 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8324 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008325 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008326 // This is the resulting set of formats depending on the surround mode:
8327 // 'all surround' = allSurround
8328 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8329 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8330 // 'manual surround' = mManualSurroundFormats
8331 // AUTO: formats v 'enforced surround'
8332 // ALWAYS: formats v 'all surround' v 'enforced surround'
8333 // NEVER: formats ^ 'non-surround'
8334 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008335
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008336 std::unordered_set<audio_format_t> formatSet;
8337 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8338 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008339 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008340 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008341 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008342 formatSet.insert(*formatIter);
8343 }
8344 }
8345 } else {
8346 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8347 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008348 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008349
jiabin81772902018-04-02 17:52:27 -07008350 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008351 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008352 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8353 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8354 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008355 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008356 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8357 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8358 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008359 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008360 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008361 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008362 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008363 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008364 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008365}
8366
jiabin06e4bab2019-07-29 10:13:34 -07008367void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8368 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008369 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8370 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8371
8372 // If NEVER, then remove support for channelMasks > stereo.
8373 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008374 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8375 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008376 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008377 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008378 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008379 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008380 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008381 }
8382 }
jiabin81772902018-04-02 17:52:27 -07008383 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8384 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8385 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008386 bool supports5dot1 = false;
8387 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008388 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008389 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8390 supports5dot1 = true;
8391 break;
8392 }
8393 }
8394 // If not then add 5.1 support.
8395 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008396 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008397 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008398 }
Phil Burk09bc4612016-02-24 15:58:15 -08008399 }
8400}
8401
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008402void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008403 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008404 const sp<IOProfile>& profile) {
8405 if (!profile->hasDynamicAudioProfile()) {
8406 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008407 }
François Gaffie112b0af2015-11-19 16:13:25 +01008408
jiabin12537fc2023-10-12 17:56:08 +00008409 audio_port_v7 devicePort;
8410 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008411
jiabin12537fc2023-10-12 17:56:08 +00008412 audio_port_v7 mixPort;
8413 profile->toAudioPort(&mixPort);
8414 mixPort.ext.mix.handle = ioHandle;
8415
8416 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8417 if (status != NO_ERROR) {
8418 ALOGE("%s failed to query the attributes of the mix port", __func__);
8419 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008420 }
jiabin12537fc2023-10-12 17:56:08 +00008421
8422 std::set<audio_format_t> supportedFormats;
8423 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8424 supportedFormats.insert(mixPort.audio_profiles[i].format);
8425 }
8426 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8427 mReportedFormatsMap[devDesc] = formats;
8428
8429 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8430 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8431 modifySurroundFormats(devDesc, &formats);
8432 size_t modifiedNumProfiles = 0;
8433 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8434 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8435 formats.end()) {
8436 // Skip the format that is not present after modifying surround formats.
8437 continue;
8438 }
8439 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8440 sizeof(struct audio_profile));
8441 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8442 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8443 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8444 modifySurroundChannelMasks(&channels);
8445 std::copy(channels.begin(), channels.end(),
8446 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8447 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8448 }
8449 mixPort.num_audio_profiles = modifiedNumProfiles;
8450 }
8451 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008452}
Eric Laurentd60560a2015-04-10 11:31:20 -07008453
Mikhail Naganovdc769682018-05-04 15:34:08 -07008454status_t AudioPolicyManager::installPatch(const char *caller,
8455 audio_patch_handle_t *patchHandle,
8456 AudioIODescriptorInterface *ioDescriptor,
8457 const struct audio_patch *patch,
8458 int delayMs)
8459{
8460 ssize_t index = mAudioPatches.indexOfKey(
8461 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8462 *patchHandle : ioDescriptor->getPatchHandle());
8463 sp<AudioPatch> patchDesc;
8464 status_t status = installPatch(
8465 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8466 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008467 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008468 }
8469 return status;
8470}
8471
8472status_t AudioPolicyManager::installPatch(const char *caller,
8473 ssize_t index,
8474 audio_patch_handle_t *patchHandle,
8475 const struct audio_patch *patch,
8476 int delayMs,
8477 uid_t uid,
8478 sp<AudioPatch> *patchDescPtr)
8479{
8480 sp<AudioPatch> patchDesc;
8481 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8482 if (index >= 0) {
8483 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008484 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008485 }
8486
8487 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8488 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8489 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8490 if (status == NO_ERROR) {
8491 if (index < 0) {
8492 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008493 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008494 } else {
8495 patchDesc->mPatch = *patch;
8496 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008497 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008498 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008499 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008500 }
8501 nextAudioPortGeneration();
8502 mpClientInterface->onAudioPatchListUpdate();
8503 }
8504 if (patchDescPtr) *patchDescPtr = patchDesc;
8505 return status;
8506}
8507
jiabinbce0c1d2020-10-05 11:20:18 -07008508bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8509{
8510 const TrackClientVector activeClients = output->getActiveClients();
8511 if (activeClients.empty()) {
8512 return true;
8513 }
8514 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8515 if (index < 0) {
8516 ALOGE("%s, no audio patch found while there are active clients on output %d",
8517 __func__, output->getId());
8518 return false;
8519 }
8520 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8521 DeviceVector routedDevices;
8522 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8523 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8524 patchDesc->mPatch.sinks[i].id);
8525 if (device == nullptr) {
8526 ALOGE("%s, no audio device found with id(%d)",
8527 __func__, patchDesc->mPatch.sinks[i].id);
8528 return false;
8529 }
8530 routedDevices.add(device);
8531 }
8532 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008533 if (client->isInvalid()) {
8534 // No need to take care about invalidated clients.
8535 continue;
8536 }
jiabinbce0c1d2020-10-05 11:20:18 -07008537 sp<DeviceDescriptor> preferredDevice =
8538 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8539 if (mEngine->getOutputDevicesForAttributes(
8540 client->attributes(), preferredDevice, false) == routedDevices) {
8541 return false;
8542 }
8543 }
8544 return true;
8545}
8546
8547sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008548 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008549 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8550 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008551{
8552 for (const auto& device : devices) {
8553 // TODO: This should be checking if the profile supports the device combo.
8554 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008555 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8556 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008557 return nullptr;
8558 }
8559 }
8560 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8561 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008562 status_t status = desc->open(halConfig, mixerConfig, devices,
8563 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008564 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008565 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008566 return nullptr;
8567 }
jiabin14b50cc2023-12-13 19:01:52 +00008568 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8569 auto portConfig = desc->getConfig();
8570 for (const auto& device : devices) {
8571 device->setPreferredConfig(&portConfig);
8572 }
8573 }
jiabinbce0c1d2020-10-05 11:20:18 -07008574
8575 // Here is where the out_set_parameters() for card & device gets called
8576 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8577 const audio_devices_t deviceType = device->type();
8578 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008579 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008580 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8581 mpClientInterface->setParameters(output, String8(param));
8582 free(param);
8583 }
jiabin12537fc2023-10-12 17:56:08 +00008584 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008585 if (!profile->hasValidAudioProfile()) {
8586 ALOGW("%s() missing param", __func__);
8587 desc->close();
8588 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008589 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8590 // Reopen the output with the best audio profile picked by APM when the profile supports
8591 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008592 desc->close();
8593 output = AUDIO_IO_HANDLE_NONE;
8594 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8595 profile->pickAudioProfile(
8596 config.sample_rate, config.channel_mask, config.format);
8597 config.offload_info.sample_rate = config.sample_rate;
8598 config.offload_info.channel_mask = config.channel_mask;
8599 config.offload_info.format = config.format;
8600
jiabina84c3d32022-12-02 18:59:55 +00008601 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008602 if (status != NO_ERROR) {
8603 return nullptr;
8604 }
8605 }
8606
8607 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008608
baek.kim -61c20122022-07-27 10:05:32 +00008609 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8610 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8611
jiabinbce0c1d2020-10-05 11:20:18 -07008612 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8613 sp<AudioPolicyMix> policyMix;
8614 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8615 policyMix->setOutput(desc);
8616 desc->mPolicyMix = policyMix;
8617 } else {
8618 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008619 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008620 }
8621
baek.kim -61c20122022-07-27 10:05:32 +00008622 } else if (hasPrimaryOutput() && speaker != nullptr
8623 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008624 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8625 // no duplicated output for:
8626 // - direct outputs
8627 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008628 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008629 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8630
8631 //TODO: configure audio effect output stage here
8632
8633 // open a duplicating output thread for the new output and the primary output
8634 sp<SwAudioOutputDescriptor> dupOutputDesc =
8635 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8636 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8637 if (status == NO_ERROR) {
8638 // add duplicated output descriptor
8639 addOutput(duplicatedOutput, dupOutputDesc);
8640 } else {
8641 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8642 mPrimaryOutput->mIoHandle, output);
8643 desc->close();
8644 removeOutput(output);
8645 nextAudioPortGeneration();
8646 return nullptr;
8647 }
8648 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008649 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8650 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8651 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008652 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008653 }
jiabinbce0c1d2020-10-05 11:20:18 -07008654 return desc;
8655}
8656
jiabinf1c73972022-04-14 16:28:52 -07008657status_t AudioPolicyManager::getDevicesForAttributes(
8658 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8659 // Devices are determined in the following precedence:
8660 //
8661 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8662 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8663 //
8664 // If no such dynamic policy then
8665 // 2) Devices containing an active client using setPreferredDevice
8666 // with same strategy as the attributes.
8667 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8668 //
8669 // If no corresponding active client with setPreferredDevice then
8670 // 3) Devices associated with the strategy determined by the attributes
8671 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8672 //
8673 // See related getOutputForAttrInt().
8674
8675 // check dynamic policies but only for primary descriptors (secondary not used for audible
8676 // audio routing, only used for duplication for playback capture)
8677 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008678 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008679 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008680 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8681 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8682 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008683 if (status != OK) {
8684 return status;
8685 }
8686
8687 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8688 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8689 // as they are unaffected by device/stream volume
8690 // (per SwAudioOutputDescriptor::isFixedVolume()).
8691 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8692 ) {
8693 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8694 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8695 devices.add(deviceDesc);
8696 } else {
8697 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8698 // which selects setPreferredDevice if active. This means forVolume call
8699 // will take an active setPreferredDevice, if such exists.
8700
8701 devices = mEngine->getOutputDevicesForAttributes(
8702 attr, nullptr /* preferredDevice */, false /* fromCache */);
8703 }
8704
8705 if (forVolume) {
8706 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8707 // for single volume control in AudioService (such relationship should exist if
8708 // SPEAKER_SAFE is present).
8709 //
8710 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8711 DeviceVector speakerSafeDevices =
8712 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8713 if (!speakerSafeDevices.isEmpty()) {
8714 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8715 devices.remove(speakerSafeDevices);
8716 }
8717 }
8718
8719 return NO_ERROR;
8720}
8721
8722status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8723 AudioProfileVector& audioProfiles,
8724 uint32_t flags,
8725 bool isInput) {
8726 for (const auto& hwModule : mHwModules) {
8727 // the MSD module checks for different conditions
8728 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8729 continue;
8730 }
8731 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8732 : hwModule->getOutputProfiles();
8733 for (const auto& profile : ioProfiles) {
8734 if (!profile->areAllDevicesSupported(devices) ||
8735 !profile->isCompatibleProfileForFlags(
8736 flags, false /*exactMatchRequiredForInputFlags*/)) {
8737 continue;
8738 }
8739 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8740 }
8741 }
8742
8743 if (!isInput) {
8744 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8745 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8746 if (msdModule != nullptr) {
8747 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8748 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8749 for (const auto &profile: msdModule->getOutputProfiles()) {
8750 if (!profile->asAudioPort()->isDirectOutput()) {
8751 continue;
8752 }
8753 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8754 }
8755 } else {
8756 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8757 }
8758 }
8759 }
8760
8761 return NO_ERROR;
8762}
8763
jiabin3ff8d7d2022-12-13 06:27:44 +00008764sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8765 const audio_config_t *config,
8766 audio_output_flags_t flags,
8767 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008768 closeOutput(outputDesc->mIoHandle);
8769 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8770 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8771 if (preferredOutput == nullptr) {
8772 ALOGE("%s failed to reopen output device=%d, caller=%s",
8773 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008774 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008775 return preferredOutput;
8776}
8777
8778void AudioPolicyManager::reopenOutputsWithDevices(
8779 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8780 for (const auto& [output, devices] : outputsToReopen) {
8781 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8782 closeOutput(output);
8783 openOutputWithProfileAndDevice(desc->mProfile, devices);
8784 }
jiabina84c3d32022-12-02 18:59:55 +00008785}
8786
jiabinc44b3462022-12-08 12:52:31 -08008787PortHandleVector AudioPolicyManager::getClientsForStream(
8788 audio_stream_type_t streamType) const {
8789 PortHandleVector clients;
8790 for (size_t i = 0; i < mOutputs.size(); ++i) {
8791 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8792 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8793 }
8794 return clients;
8795}
8796
8797void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8798 PortHandleVector clients;
8799 for (auto stream : streams) {
8800 PortHandleVector clientsForStream = getClientsForStream(stream);
8801 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8802 }
8803 mpClientInterface->invalidateTracks(clients);
8804}
8805
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008806} // namespace android