blob: 14eb48a5c085fd97dc859c0949de5cc1f41115d2 [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) {
jiabinc0048632023-04-27 22:04:31 +0000132 ALOGE("Error %d while setting connected state for device %s", state,
Mikhail Naganov516d3982022-02-01 23:53:59 +0000133 device->getDeviceTypeAddr().toString(false).c_str());
134 }
François Gaffie44481e72016-04-20 07:49:57 +0200135}
136
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100137status_t AudioPolicyManager::setDeviceConnectionStateInt(
138 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
139 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100140 if (port.ext.getTag() != AudioPortExt::device) {
141 return BAD_VALUE;
142 }
143 audio_devices_t device_type;
144 std::string device_address;
145 if (status_t status = aidl2legacy_AudioDevice_audio_device(
146 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
147 status != OK) {
148 return status;
149 };
150 const char* device_name = port.name.c_str();
151 // connect/disconnect only 1 device at a time
152 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
153 return BAD_VALUE;
154
155 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
156 device_type, device_address.c_str(), device_name, encodedFormat,
157 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000158 if (device == nullptr) {
159 return INVALID_OPERATION;
160 }
161 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
162 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
163 }
164 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100165}
166
François Gaffie11d30102018-11-02 16:09:09 +0100167status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800168 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100169 const char* device_address,
170 const char* device_name,
171 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800172 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100173 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
174 status == OK) {
175 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
176 } else {
177 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
178 return status;
179 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700180}
Paul McLeane743a472015-01-28 11:07:31 -0800181
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700182status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
183 audio_policy_dev_state_t state)
184{
Eric Laurente552edb2014-03-10 17:42:56 -0700185 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700186 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700187 SortedVector <audio_io_handle_t> outputs;
188
François Gaffie11d30102018-11-02 16:09:09 +0100189 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // save a copy of the opened output descriptors before any output is opened or closed
192 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
193 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100194
195 bool wasLeUnicastActive = isLeUnicastActive();
196
Eric Laurente552edb2014-03-10 17:42:56 -0700197 switch (state)
198 {
199 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800200 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700201 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100202 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700203 return INVALID_OPERATION;
204 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800205 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700206 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700207
Eric Laurente552edb2014-03-10 17:42:56 -0700208 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200209 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700210 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700211 }
212
François Gaffie44481e72016-04-20 07:49:57 +0200213 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
214 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000215 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200216
François Gaffie11d30102018-11-02 16:09:09 +0100217 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
218 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200219
Francois Gaffie716e1432019-01-14 16:58:59 +0100220 mHwModules.cleanUpForDevice(device);
221
jiabinc0048632023-04-27 22:04:31 +0000222 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700223 return INVALID_OPERATION;
224 }
François Gaffie2110e042015-03-24 08:41:51 +0100225
jiabin1c4794b2020-05-05 10:08:05 -0700226 // Populate encapsulation information when a output device is connected.
227 device->setEncapsulationInfoFromHal(mpClientInterface);
228
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700229 // outputs should never be empty here
230 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
231 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100232 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800233
Eric Laurent3ae5f312015-02-03 17:12:08 -0800234 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700235 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700236 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700237 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100238 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700239 return INVALID_OPERATION;
240 }
241
François Gaffie11d30102018-11-02 16:09:09 +0100242 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700243
jiabinc0048632023-04-27 22:04:31 +0000244 // Notify the HAL to prepare to disconnect device
245 broadcastDeviceConnectionState(
246 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700247
Eric Laurente552edb2014-03-10 17:42:56 -0700248 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100249 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700250
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100251 mOutputs.clearSessionRoutesForDevice(device);
252
François Gaffie11d30102018-11-02 16:09:09 +0100253 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100254
jiabinc0048632023-04-27 22:04:31 +0000255 // Send Disconnect to HALs
256 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
257
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800258 // Reset active device codec
259 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
260
Kriti Dangef6be8f2020-11-05 11:58:19 +0100261 // remove device from mReportedFormatsMap cache
262 mReportedFormatsMap.erase(device);
263
jiabina84c3d32022-12-02 18:59:55 +0000264 // remove preferred mixer configurations
265 mPreferredMixerAttrInfos.erase(device->getId());
266
Eric Laurente552edb2014-03-10 17:42:56 -0700267 } break;
268
269 default:
François Gaffie11d30102018-11-02 16:09:09 +0100270 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700271 return BAD_VALUE;
272 }
273
Eric Laurent736a1022019-03-27 18:28:46 -0700274 // Propagate device availability to Engine
275 setEngineDeviceConnectionState(device, state);
276
Eric Laurentae970022019-01-29 14:25:04 -0800277 // No need to evaluate playback routing when connecting a remote submix
278 // output device used by a dynamic policy of type recorder as no
279 // playback use case is affected.
280 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700281 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800282 for (audio_io_handle_t output : outputs) {
283 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800284 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
285 if (policyMix != nullptr
286 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000287 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800288 doCheckForDeviceAndOutputChanges = false;
289 break;
290 }
291 }
292 }
293
294 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700295 // outputs must be closed after checkOutputForAllStrategies() is executed
296 if (!outputs.isEmpty()) {
297 for (audio_io_handle_t output : outputs) {
298 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100299 // close unused outputs after device disconnection or direct outputs that have
300 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200301 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200302 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
303 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200304 (desc->mDirectOpenCount == 0))
305 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
306 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200307 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700308 closeOutput(output);
309 }
Eric Laurente552edb2014-03-10 17:42:56 -0700310 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700311 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
312 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700313 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700314 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800315 };
316
317 if (doCheckForDeviceAndOutputChanges) {
318 checkForDeviceAndOutputChanges(checkCloseOutputs);
319 } else {
320 checkCloseOutputs();
321 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100322 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100323 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700324 const DeviceVector activeMediaDevices =
325 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000326 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700327 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700328 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530329 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
330 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100331 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700332 // do not force device change on duplicated output because if device is 0, it will
333 // also force a device 0 for the two outputs it is duplicated to which may override
334 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100335 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100336 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700337 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700338 // always force when disconnecting (a non-duplicated device)
339 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000340 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
341 // If the device is using preferred mixer attributes, the output need to reopen
342 // with default configuration when the new selected devices are different from
343 // current routing devices
344 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
345 continue;
346 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530347 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700348 }
jiabinbce0c1d2020-10-05 11:20:18 -0700349 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000350 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700351 desc->supportsDevicesForPlayback(activeMediaDevices)) {
352 // Reopen the output to query the dynamic profiles when there is not active
353 // clients or all active clients will be rerouted. Otherwise, set the flag
354 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
355 // can be reopened to query dynamic profiles when all clients are inactive.
356 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000357 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700358 } else {
359 desc->mPendingReopenToQueryProfiles = true;
360 }
361 }
362 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
363 // Clear the flag that previously set for re-querying profiles.
364 desc->mPendingReopenToQueryProfiles = false;
365 }
366 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000367 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700368
Eric Laurentd60560a2015-04-10 11:31:20 -0700369 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100370 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700371 }
372
Eric Laurent96d1dda2022-03-14 17:14:19 +0100373 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
374
Eric Laurent72aa32f2014-05-30 18:51:48 -0700375 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700376 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700377 } // end if is output device
378
Eric Laurente552edb2014-03-10 17:42:56 -0700379 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700380 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100381 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700382 switch (state)
383 {
384 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700385 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700386 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100387 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700388 return INVALID_OPERATION;
389 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700390
391 if (mAvailableInputDevices.add(device) < 0) {
392 return NO_MEMORY;
393 }
394
François Gaffie44481e72016-04-20 07:49:57 +0200395 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
396 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000397 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200398
Eric Laurent0dd51852019-04-19 18:18:58 -0700399 if (checkInputsForDevice(device, state) != NO_ERROR) {
400 mAvailableInputDevices.remove(device);
401
jiabinc0048632023-04-27 22:04:31 +0000402 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100403
404 mHwModules.cleanUpForDevice(device);
405
Eric Laurentd4692962014-05-05 18:13:44 -0700406 return INVALID_OPERATION;
407 }
408
Eric Laurentd4692962014-05-05 18:13:44 -0700409 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700410
411 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700412 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700413 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100414 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700415 return INVALID_OPERATION;
416 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700417
François Gaffie11d30102018-11-02 16:09:09 +0100418 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700419
jiabinc0048632023-04-27 22:04:31 +0000420 // Notify the HAL to prepare to disconnect device
421 broadcastDeviceConnectionState(
422 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700423
François Gaffie11d30102018-11-02 16:09:09 +0100424 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700425
426 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100427
jiabinc0048632023-04-27 22:04:31 +0000428 // Set Disconnect to HALs
429 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
430
Kriti Dangef6be8f2020-11-05 11:58:19 +0100431 // remove device from mReportedFormatsMap cache
432 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700433 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700434
435 default:
François Gaffie11d30102018-11-02 16:09:09 +0100436 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700437 return BAD_VALUE;
438 }
439
Eric Laurent736a1022019-03-27 18:28:46 -0700440 // Propagate device availability to Engine
441 setEngineDeviceConnectionState(device, state);
442
Eric Laurent0dd51852019-04-19 18:18:58 -0700443 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700444 // As the input device list can impact the output device selection, update
445 // getDeviceForStrategy() cache
446 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700447
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100448 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200449 // Reconnect Audio Source
450 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
451 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
452 checkAudioSourceForAttributes(attributes);
453 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700454 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100455 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700456 }
457
Eric Laurentb52c1522014-05-20 11:27:36 -0700458 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700459 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700460 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700461
François Gaffie11d30102018-11-02 16:09:09 +0100462 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700463 return BAD_VALUE;
464}
465
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100466status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
467 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800468 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700469 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
470 devDescr->setName(device_name);
471 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100472}
473
Eric Laurent736a1022019-03-27 18:28:46 -0700474void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
475 audio_policy_dev_state_t state) {
476
477 // the Engine does not have to know about remote submix devices used by dynamic audio policies
478 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
479 return;
480 }
481 mEngine->setDeviceConnectionState(device, state);
482}
483
484
Eric Laurente0720872014-03-11 09:30:41 -0700485audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100486 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700487{
Eric Laurent634b7142016-04-20 13:48:02 -0700488 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800489 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
490 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700491 (strlen(device_address) != 0)/*matchAddress*/);
492
493 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100494 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700495 device, device_address);
496 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
497 }
François Gaffie53615e22015-03-19 09:24:12 +0100498
Eric Laurent3a4311c2014-03-17 12:00:47 -0700499 DeviceVector *deviceVector;
500
Eric Laurente552edb2014-03-10 17:42:56 -0700501 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700502 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700503 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700504 deviceVector = &mAvailableInputDevices;
505 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100506 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700507 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700508 }
Eric Laurent634b7142016-04-20 13:48:02 -0700509
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 return (deviceVector->getDevice(
511 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700512 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800513}
514
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800515status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
516 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 const char *device_name,
518 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800520 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
521 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800522
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800523 // connect/disconnect only 1 device at a time
524 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
525
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800526 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700527 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800528 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800529 // Nothing to do: device is not connected
530 return NO_ERROR;
531 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800532 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800533
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700534 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800535 // configure codecs.
536 // Handle two specific cases by sending a set parameter to
537 // configure A2DP codecs. No need to toggle device state.
538 // Case 1: A2DP active device switches from primary to primary
539 // module
540 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100541 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700542 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800543 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
544 if (availablePrimaryOutputDevices().contains(devDesc) &&
545 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100546 bool isA2dp = audio_is_a2dp_out_device(device);
547 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
548 : String8(AudioParameter::keyReconfigLeSupported);
549 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800550 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100551 int isReconfigSupported;
552 repliedParameters.getInt(supportKey, isReconfigSupported);
553 if (isReconfigSupported) {
554 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
555 : String8(AudioParameter::keyReconfigLe);
556 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800557 param.add(key, String8("true"));
558 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
559 devDesc->setEncodedFormat(encodedFormat);
560 return NO_ERROR;
561 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700562 }
563 }
cnx421bd2dcc42020-07-11 14:58:44 +0800564 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
565 for (size_t i = 0; i < mOutputs.size(); i++) {
566 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
567 // mute media strategies and delay device switch by the largest
568 // This avoid sending the music tail into the earpiece or headset.
569 setStrategyMute(musicStrategy, true, desc);
570 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
571 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
572 nullptr, true /*fromCache*/).types());
573 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800574 // Toggle the device state: UNAVAILABLE -> AVAILABLE
575 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100576 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800577 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800578 device_address, device_name,
579 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800580 if (status != NO_ERROR) {
581 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
582 status);
583 return status;
584 }
585
586 status = setDeviceConnectionState(device,
587 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800588 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800589 if (status != NO_ERROR) {
590 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
591 status);
592 return status;
593 }
594
595 return NO_ERROR;
596}
597
Pattydd807582021-11-04 21:01:03 +0800598status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
599 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800600{
Pattydd807582021-11-04 21:01:03 +0800601 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800602 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800603 std::unordered_set<audio_format_t> formatSet;
604 sp<HwModule> primaryModule =
605 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700606 if (primaryModule == nullptr) {
607 ALOGE("%s() unable to get primary module", __func__);
608 return NO_INIT;
609 }
Pattydd807582021-11-04 21:01:03 +0800610
611 DeviceTypeSet audioDeviceSet;
612
613 switch(device) {
614 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
615 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
616 break;
617 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800618 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
619 break;
620 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
621 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800622 break;
623 default:
624 ALOGE("%s() device type 0x%08x not supported", __func__, device);
625 return BAD_VALUE;
626 }
627
jiabin9a3361e2019-10-01 09:38:30 -0700628 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800629 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800630 for (const auto& device : declaredDevices) {
631 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800632 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800633 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800634 return status;
635}
636
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100637DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
638{
639 DeviceVector rxSinkdevices{};
640 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
641 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
642 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
643 auto rxSinkDevice = rxSinkdevices.itemAt(0);
644 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
645 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
646 // retrieve Rx Source device descriptor
647 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
648 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
649
650 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
651 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
652 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
653 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
654 return DeviceVector(rxSinkDevice);
655 }
656 }
657 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
658 // the device returned is not necessarily reachable via this output
659 // (filter later by setOutputDevices())
660 return getNewOutputDevices(mPrimaryOutput, fromCache);
661}
662
663status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
664{
François Gaffiedb1755b2023-09-01 11:50:35 +0200665 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100666 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
667 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
668 }
669 return INVALID_OPERATION;
670}
671
672status_t AudioPolicyManager::updateCallRoutingInternal(
673 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674{
675 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100676 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700677 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200678 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700679 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100680 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700681 }
François Gaffie11d30102018-11-02 16:09:09 +0100682
Francois Gaffie716e1432019-01-14 16:58:59 +0100683 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100684 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200685
686 disconnectTelephonyAudioSource(mCallRxSourceClient);
687 disconnectTelephonyAudioSource(mCallTxSourceClient);
688
689 if (rxDevices.isEmpty()) {
690 ALOGW("%s() no selected output device", __func__);
691 return INVALID_OPERATION;
692 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000693 if (txSourceDevice == nullptr) {
694 ALOGE("%s() selected input device not available", __func__);
695 return INVALID_OPERATION;
696 }
François Gaffiec005e562018-11-06 15:04:49 +0100697
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100698 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100699 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700700
François Gaffie9eb18552018-11-05 10:33:26 +0100701 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700702 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100703 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700704 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100705 // retrieve Rx Source and Tx Sink device descriptors
706 sp<DeviceDescriptor> rxSourceDevice =
707 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
708 String8(),
709 AUDIO_FORMAT_DEFAULT);
710 sp<DeviceDescriptor> txSinkDevice =
711 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
712 String8(),
713 AUDIO_FORMAT_DEFAULT);
714
715 // RX and TX Telephony device are declared by Primary Audio HAL
716 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
717 (telephonyRxModule->getHalVersionMajor() >= 3)) {
718 if (rxSourceDevice == 0 || txSinkDevice == 0) {
719 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100720 ALOGE("%s() no telephony Tx and/or RX device", __func__);
721 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100722 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100723 // createAudioPatchInternal now supports both HW / SW bridging
724 createRxPatch = true;
725 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100726 } else {
727 // If the RX device is on the primary HW module, then use legacy routing method for
728 // voice calls via setOutputDevice() on primary output.
729 // Otherwise, create two audio patches for TX and RX path.
730 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
731 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700732 // If the TX device is also on the primary HW module, setOutputDevice() will take care
733 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100734 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
735 (txSinkDevice != 0);
736 }
737 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
738 // Otherwise, create two audio patches for TX and RX path.
739 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200740 if (!hasPrimaryOutput()) {
741 ALOGW("%s() no primary output available", __func__);
742 return INVALID_OPERATION;
743 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530744 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700745 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200746 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800747 // If the TX device is on the primary HW module but RX device is
748 // on other HW module, SinkMetaData of telephony input should handle it
749 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700750 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700751 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100752 // terminate active capture if on the same HW module as the call TX source device
753 // FIXME: would be better to refine to only inputs whose profile connects to the
754 // call TX device but this information is not in the audio patch and logic here must be
755 // symmetric to the one in startInput()
756 for (const auto& activeDesc : mInputs.getActiveInputs()) {
757 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
758 closeActiveClients(activeDesc);
759 }
760 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200761 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800762 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100763 if (waitMs != nullptr) {
764 *waitMs = muteWaitMs;
765 }
766 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800767}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700768
Mikhail Naganov100f0122018-11-29 11:22:16 -0800769bool AudioPolicyManager::isDeviceOfModule(
770 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
771 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
772 if (module != 0) {
773 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
774 .indexOf(devDesc) != NAME_NOT_FOUND
775 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
776 .indexOf(devDesc) != NAME_NOT_FOUND;
777 }
778 return false;
779}
780
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200781void AudioPolicyManager::connectTelephonyRxAudioSource()
782{
Francois Gaffie601801d2021-06-22 13:27:39 +0200783 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200784 const struct audio_port_config source = {
785 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
786 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
787 };
788 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100789
790 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
791 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
792 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
793 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200794 ALOGE_IF(mCallRxSourceClient == nullptr,
795 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200796}
797
Francois Gaffie601801d2021-06-22 13:27:39 +0200798void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200799{
Francois Gaffie601801d2021-06-22 13:27:39 +0200800 if (clientDesc == nullptr) {
801 return;
802 }
803 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
804 "%s error stopping audio source", __func__);
805 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200806}
807
808void AudioPolicyManager::connectTelephonyTxAudioSource(
809 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
810 uint32_t delayMs)
811{
Francois Gaffie601801d2021-06-22 13:27:39 +0200812 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200813 if (srcDevice == nullptr || sinkDevice == nullptr) {
814 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
815 return;
816 }
817 PatchBuilder patchBuilder;
818 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
819 ALOGV("%s between source %s and sink %s", __func__,
820 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200822 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
823
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200824 struct audio_port_config source = {};
825 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100826 mCallTxSourceClient = new SourceClientDescriptor(
827 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
828 mCommunnicationStrategy, toVolumeSource(aa), true);
829 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
830
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200831 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
832 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200833 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
834 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200835 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
836 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200837 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200838 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200839}
840
Eric Laurente0720872014-03-11 09:30:41 -0700841void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700842{
843 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100844 // store previous phone state for management of sonification strategy below
845 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100846 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100847
848 if (mEngine->setPhoneState(state) != NO_ERROR) {
849 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700850 return;
851 }
François Gaffie2110e042015-03-24 08:41:51 +0100852 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700853 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700854 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700855 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800856 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700857 }
858
François Gaffie2110e042015-03-24 08:41:51 +0100859 /**
860 * Switching to or from incall state or switching between telephony and VoIP lead to force
861 * routing command.
862 */
Eric Laurent74b71512019-11-06 17:21:57 -0800863 bool force = ((isStateInCall(oldState) != isStateInCall(state))
864 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700865
866 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700867 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700868
Eric Laurente552edb2014-03-10 17:42:56 -0700869 int delayMs = 0;
870 if (isStateInCall(state)) {
871 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100872 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
873 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700874 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700875 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700876 // mute media and sonification strategies and delay device switch by the largest
877 // latency of any output where either strategy is active.
878 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100879 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
880 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
881 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700882 (delayMs < (int)desc->latency()*2)) {
883 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700884 }
François Gaffiec005e562018-11-06 15:04:49 +0100885 setStrategyMute(musicStrategy, true, desc);
886 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
887 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
888 nullptr, true /*fromCache*/).types());
889 setStrategyMute(sonificationStrategy, true, desc);
890 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
891 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
892 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700893 }
894 }
895
François Gaffiedb1755b2023-09-01 11:50:35 +0200896 if (state == AUDIO_MODE_IN_CALL) {
897 (void)updateCallRouting(false /*fromCache*/, delayMs);
898 } else {
899 if (oldState == AUDIO_MODE_IN_CALL) {
900 disconnectTelephonyAudioSource(mCallRxSourceClient);
901 disconnectTelephonyAudioSource(mCallTxSourceClient);
902 }
903 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100904 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
905 // force routing command to audio hardware when ending call
906 // even if no device change is needed
907 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
908 rxDevices = mPrimaryOutput->devices();
909 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530910 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700911 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700912 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700913
jiabin3ff8d7d2022-12-13 06:27:44 +0000914 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700915 // reevaluate routing on all outputs in case tracks have been started during the call
916 for (size_t i = 0; i < mOutputs.size(); i++) {
917 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100918 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200919 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
920 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000921 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
922 // If the device is using preferred mixer attributes, the output need to reopen
923 // with default configuration when the new selected devices are different from
924 // current routing devices.
925 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
926 continue;
927 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530928 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200929 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700930 }
931 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000932 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700933
Eric Laurent96d1dda2022-03-14 17:14:19 +0100934 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
935
Eric Laurente552edb2014-03-10 17:42:56 -0700936 if (isStateInCall(state)) {
937 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700938 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800939 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700940 }
941
942 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100943 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
944 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700945}
946
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700947audio_mode_t AudioPolicyManager::getPhoneState() {
948 return mEngine->getPhoneState();
949}
950
Eric Laurente0720872014-03-11 09:30:41 -0700951void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100952 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700953{
François Gaffie2110e042015-03-24 08:41:51 +0100954 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700955 if (config == mEngine->getForceUse(usage)) {
956 return;
957 }
Eric Laurente552edb2014-03-10 17:42:56 -0700958
François Gaffie2110e042015-03-24 08:41:51 +0100959 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
960 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
961 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700962 }
François Gaffie2110e042015-03-24 08:41:51 +0100963 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
964 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
965 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700966
967 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700968 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800969
Eric Laurent22fcda22019-05-17 16:28:47 -0700970 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
971 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800972 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700973 }
974
Eric Laurentdc462862016-07-19 12:29:53 -0700975 //FIXME: workaround for truncated touch sounds
976 // to be removed when the problem is handled by system UI
977 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700978 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
979 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
980 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700981
982 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100983 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700984}
985
Eric Laurente0720872014-03-11 09:30:41 -0700986void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700987{
988 ALOGV("setSystemProperty() property %s, value %s", property, value);
989}
990
Dorin Drimusecc9f422022-03-09 17:57:40 +0100991// Find an MSD output profile compatible with the parameters passed.
992// When "directOnly" is set, restrict search to profiles for direct outputs.
993sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
994 const DeviceVector& devices,
995 uint32_t samplingRate,
996 audio_format_t format,
997 audio_channel_mask_t channelMask,
998 audio_output_flags_t flags,
999 bool directOnly)
1000{
1001 flags = getRelevantFlags(flags, directOnly);
1002
1003 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1004 if (msdModule != nullptr) {
1005 // for the msd module check if there are patches to the output devices
1006 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1007 HwModuleCollection modules;
1008 modules.add(msdModule);
1009 return searchCompatibleProfileHwModules(
1010 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1011 flags, directOnly);
1012 }
1013 }
1014 return nullptr;
1015}
1016
Michael Chana94fbb22018-04-24 14:31:19 +10001017// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1018// search to profiles for direct outputs.
1019sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001020 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001021 uint32_t samplingRate,
1022 audio_format_t format,
1023 audio_channel_mask_t channelMask,
1024 audio_output_flags_t flags,
1025 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001026{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001027 flags = getRelevantFlags(flags, directOnly);
1028
1029 return searchCompatibleProfileHwModules(
1030 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1031}
1032
1033audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1034 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001035 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 // only retain flags that will drive the direct output profile selection
1037 // if explicitly requested
1038 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001039 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001040 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1041 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001042 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001043 return flags;
1044}
Eric Laurent861a6282015-05-18 15:40:16 -07001045
Dorin Drimusecc9f422022-03-09 17:57:40 +01001046sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1047 const HwModuleCollection& hwModules,
1048 const DeviceVector& devices,
1049 uint32_t samplingRate,
1050 audio_format_t format,
1051 audio_channel_mask_t channelMask,
1052 audio_output_flags_t flags,
1053 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001054 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001055 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001056 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001057 if (!curProfile->isCompatibleProfile(devices,
1058 samplingRate, NULL /*updatedSamplingRate*/,
1059 format, NULL /*updatedFormat*/,
1060 channelMask, NULL /*updatedChannelMask*/,
1061 flags)) {
1062 continue;
1063 }
1064 // reject profiles not corresponding to a device currently available
1065 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1066 continue;
1067 }
1068 // reject profiles if connected device does not support codec
1069 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1070 continue;
1071 }
1072 if (!directOnly) {
1073 return curProfile;
1074 }
1075
1076 // when searching for direct outputs, if several profiles are compatible, give priority
1077 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001078 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001079 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001080 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001081 }
1082 profile = curProfile;
1083 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1084 break;
1085 }
Eric Laurente552edb2014-03-10 17:42:56 -07001086 }
1087 }
Eric Laurent861a6282015-05-18 15:40:16 -07001088 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001089}
1090
Eric Laurentfa0f6742021-08-17 18:39:44 +02001091sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001092 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001093{
1094 for (const auto& hwModule : mHwModules) {
1095 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001096 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001097 continue;
1098 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001099 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001100 // reject profiles not corresponding to a device currently available
1101 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1102 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1103 continue;
1104 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001105 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1106 != devices.size()) {
1107 continue;
1108 }
1109 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001110 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1111 return curProfile;
1112 }
1113 }
1114 return nullptr;
1115}
1116
Eric Laurentf4e63452017-11-06 19:31:46 +00001117audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001118{
François Gaffiec005e562018-11-06 15:04:49 +01001119 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001120
1121 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1122 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1123 // format, flags, etc. This may result in some discrepancy for functions that utilize
1124 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1125 // and AudioSystem::getOutputSamplingRate().
1126
François Gaffie11d30102018-11-02 16:09:09 +01001127 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001128 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1129 if (stream == AUDIO_STREAM_MUSIC &&
1130 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1131 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1132 }
1133 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001134
François Gaffie11d30102018-11-02 16:09:09 +01001135 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1136 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001137 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001138}
1139
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001140status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1141 const audio_attributes_t *srcAttr,
1142 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001143{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001144 if (srcAttr != NULL) {
1145 if (!isValidAttributes(srcAttr)) {
1146 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1147 __func__,
1148 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1149 srcAttr->tags);
1150 return BAD_VALUE;
1151 }
1152 *dstAttr = *srcAttr;
1153 } else {
1154 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1155 ALOGE("%s: invalid stream type", __func__);
1156 return BAD_VALUE;
1157 }
François Gaffiec005e562018-11-06 15:04:49 +01001158 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001159 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001160
1161 // Only honor audibility enforced when required. The client will be
1162 // forced to reconnect if the forced usage changes.
1163 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001164 dstAttr->flags = static_cast<audio_flags_mask_t>(
1165 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001166 }
1167
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001168 return NO_ERROR;
1169}
1170
Kevin Rocard153f92d2018-12-18 18:33:28 -08001171status_t AudioPolicyManager::getOutputForAttrInt(
1172 audio_attributes_t *resultAttr,
1173 audio_io_handle_t *output,
1174 audio_session_t session,
1175 const audio_attributes_t *attr,
1176 audio_stream_type_t *stream,
1177 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001178 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001179 audio_output_flags_t *flags,
1180 audio_port_handle_t *selectedDeviceId,
1181 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001182 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001183 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001184 bool *isSpatialized,
1185 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001186{
François Gaffiec005e562018-11-06 15:04:49 +01001187 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001188 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001189 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001190 const sp<DeviceDescriptor> requestedDevice =
1191 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1192
Eric Laurent8a1095a2019-11-08 14:44:16 -08001193 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001194 *isSpatialized = false;
1195
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001196 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1197 if (status != NO_ERROR) {
1198 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001199 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001200 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001201 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001202 }
François Gaffiec005e562018-11-06 15:04:49 +01001203 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001204
François Gaffiec005e562018-11-06 15:04:49 +01001205 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1206 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001207
Oscar Azucena873d10f2023-01-12 18:34:42 -08001208 bool usePrimaryOutputFromPolicyMixes = false;
1209
Kevin Rocard153f92d2018-12-18 18:33:28 -08001210 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1211 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1212 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001213 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001214 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1215 .channel_mask = config->channel_mask,
1216 .format = config->format,
1217 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001218 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001219 mAvailableOutputDevices, requestedDevice, primaryMix,
1220 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001221 if (status != OK) {
1222 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001223 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001224
Kevin Rocard153f92d2018-12-18 18:33:28 -08001225 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001226 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1227 && !audio_is_linear_pcm(config->format)) {
1228 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001229 return BAD_VALUE;
1230 }
1231 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001232 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001233 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1234 primaryMix->mDeviceAddress,
1235 AUDIO_FORMAT_DEFAULT);
1236 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001237 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001238 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1239 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001240 // if a direct output can be opened to deliver the track's multi-channel content to the
1241 // output rather than being downmixed by the primary output, then use this direct
1242 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1243 // mix.
1244 bool tryDirectForChannelMask = policyDesc != nullptr
1245 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1246 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001247 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001248 audio_io_handle_t newOutput;
1249 status = openDirectOutput(
1250 *stream, session, config,
1251 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001252 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001253 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001254 policyDesc = mOutputs.valueFor(newOutput);
1255 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001256 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001257 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001258 policyDesc = nullptr;
1259 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001260 }
1261 if (policyDesc != nullptr) {
1262 policyDesc->mPolicyMix = primaryMix;
1263 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001264 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1265 : AUDIO_PORT_HANDLE_NONE;
1266 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1267 // Remove direct flag as it is not on a direct output.
1268 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1269 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001270
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001271 ALOGV("getOutputForAttr() returns output %d", *output);
1272 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1273 *outputType = API_OUT_MIX_PLAYBACK;
1274 } else {
1275 *outputType = API_OUTPUT_LEGACY;
1276 }
1277 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001278 } else {
1279 if (policyMixDevice != nullptr) {
1280 ALOGE("%s, try to use primary mix but no output found", __func__);
1281 return INVALID_OPERATION;
1282 }
1283 // Fallback to default engine selection as the selected primary mix device is not
1284 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001285 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001286 }
François Gaffiec005e562018-11-06 15:04:49 +01001287 // Virtual sources must always be dynamicaly or explicitly routed
1288 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1289 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1290 return BAD_VALUE;
1291 }
1292 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1293 // in order to let the choice of the order to future vendor engine
1294 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001295
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001296 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001297 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001298 }
1299
Nadav Barb2f18162018-07-18 13:01:53 +03001300 // Set incall music only if device was explicitly set, and fallback to the device which is
1301 // chosen by the engine if not.
1302 // FIXME: provide a more generic approach which is not device specific and move this back
1303 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001304 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001305 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001306 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001307 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001308 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001309 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001310 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001311 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001312 }
1313 }
1314
François Gaffiec005e562018-11-06 15:04:49 +01001315 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1316 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1317 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001318
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001319 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001320 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001321 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001322 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001323 ALOGV("%s() Using MSD devices %s instead of devices %s",
1324 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001325 } else {
1326 *output = AUDIO_IO_HANDLE_NONE;
1327 }
1328 }
1329 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001330 sp<PreferredMixerAttributesInfo> info = nullptr;
1331 if (outputDevices.size() == 1) {
1332 info = getPreferredMixerAttributesInfo(
1333 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001334 mEngine->getProductStrategyForAttributes(*resultAttr),
1335 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001336 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1337 // and it is currently active.
1338 if (info != nullptr && info->getUid() != uid &&
1339 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1340 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001341 info = nullptr;
1342 }
1343 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001344 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001345 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001346 // The client will be active if the client is currently preferred mixer owner and the
1347 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001348 *isBitPerfect = (info != nullptr
1349 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001350 && info->getUid() == uid
1351 && *output != AUDIO_IO_HANDLE_NONE
1352 // When bit-perfect output is selected for the preferred mixer attributes owner,
1353 // only need to consider the config matches.
1354 && mOutputs.valueFor(*output)->isConfigurationMatched(
1355 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001356 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001357 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001358 AudioProfileVector profiles;
1359 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1360 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001361 const auto channels = profiles[0]->getChannels();
1362 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1363 config->channel_mask = *channels.begin();
1364 }
1365 const auto sampleRates = profiles[0]->getSampleRates();
1366 if (!sampleRates.empty() &&
1367 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1368 config->sample_rate = *sampleRates.begin();
1369 }
jiabinf1c73972022-04-14 16:28:52 -07001370 config->format = profiles[0]->getFormat();
1371 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001372 return INVALID_OPERATION;
1373 }
Paul McLeanaa981192015-03-21 09:55:15 -07001374
François Gaffiec005e562018-11-06 15:04:49 +01001375 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001376 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001377 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001378 *selectedDeviceId = outputDevice->getId();
1379 break;
1380 }
1381 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001382
Eric Laurent8a1095a2019-11-08 14:44:16 -08001383 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1384 *outputType = API_OUTPUT_TELEPHONY_TX;
1385 } else {
1386 *outputType = API_OUTPUT_LEGACY;
1387 }
1388
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001389 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1390
1391 return NO_ERROR;
1392}
1393
1394status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1395 audio_io_handle_t *output,
1396 audio_session_t session,
1397 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001398 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001399 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001400 audio_output_flags_t *flags,
1401 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001402 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001403 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001404 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001405 bool *isSpatialized,
1406 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001407{
1408 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1409 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1410 return INVALID_OPERATION;
1411 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001412 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001413 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001414 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001415 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001416 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001417 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001418 const sp<DeviceDescriptor> requestedDevice =
1419 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1420
1421 // Prevent from storing invalid requested device id in clients
1422 const audio_port_handle_t sanitizedRequestedPortId =
1423 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1424 *selectedDeviceId = sanitizedRequestedPortId;
1425
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001426 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001427 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001428 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1429 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001430 if (status != NO_ERROR) {
1431 return status;
1432 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001433 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001434 if (secondaryOutputs != nullptr) {
1435 for (auto &secondaryMix : secondaryMixes) {
1436 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1437 if (outputDesc != nullptr &&
1438 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1439 secondaryOutputs->push_back(outputDesc->mIoHandle);
1440 weakSecondaryOutputDescs.push_back(outputDesc);
1441 }
1442 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001443 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001444
Eric Laurent8fc147b2018-07-22 19:13:55 -07001445 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001446 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001447 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001448 };
jiabin4ef93452019-09-10 14:29:54 -07001449 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001450
Eric Laurentc209fe42020-06-05 18:11:23 -07001451 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001452 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001453 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001454 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001455 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001456 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001457 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001458 std::move(weakSecondaryOutputDescs),
1459 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001460 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001461
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001462 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1463 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001464
Eric Laurente83b55d2014-11-14 10:06:21 -08001465 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001466}
1467
Eric Laurentc529cf62020-04-17 18:19:10 -07001468status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1469 audio_session_t session,
1470 const audio_config_t *config,
1471 audio_output_flags_t flags,
1472 const DeviceVector &devices,
1473 audio_io_handle_t *output) {
1474
1475 *output = AUDIO_IO_HANDLE_NONE;
1476
1477 // skip direct output selection if the request can obviously be attached to a mixed output
1478 // and not explicitly requested
1479 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1480 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1481 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1482 return NAME_NOT_FOUND;
1483 }
1484
1485 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1486 // This prevents creating an offloaded track and tearing it down immediately after start
1487 // when audioflinger detects there is an active non offloadable effect.
1488 // FIXME: We should check the audio session here but we do not have it in this context.
1489 // This may prevent offloading in rare situations where effects are left active by apps
1490 // in the background.
1491 sp<IOProfile> profile;
1492 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1493 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1494 profile = getProfileForOutput(
1495 devices, config->sample_rate, config->format, config->channel_mask,
1496 flags, true /* directOnly */);
1497 }
1498
1499 if (profile == nullptr) {
1500 return NAME_NOT_FOUND;
1501 }
1502
1503 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1504 for (size_t i = 0; i < mOutputs.size(); i++) {
1505 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1506 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1507 // reuse direct output if currently open by the same client
1508 // and configured with same parameters
1509 if ((config->sample_rate == desc->getSamplingRate()) &&
1510 (config->format == desc->getFormat()) &&
1511 (config->channel_mask == desc->getChannelMask()) &&
1512 (session == desc->mDirectClientSession)) {
1513 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001514 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001515 mOutputs.keyAt(i), session);
1516 *output = mOutputs.keyAt(i);
1517 return NO_ERROR;
1518 }
1519 }
1520 }
1521
1522 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001523 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1524 return NAME_NOT_FOUND;
1525 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1526 // MMAP gracefully handles lack of an exclusive track resource by mixing
1527 // above the audio framework. For AAudio to know that the limit is reached,
1528 // return an error.
1529 return NAME_NOT_FOUND;
1530 } else {
1531 // Close outputs on this profile, if available, to free resources for this request
1532 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1533 const auto desc = mOutputs.valueAt(i);
1534 if (desc->mProfile == profile) {
1535 closeOutput(desc->mIoHandle);
1536 }
1537 }
1538 }
1539 }
1540
1541 // Unable to close streams to find free resources for this request
1542 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001543 return NAME_NOT_FOUND;
1544 }
1545
Atneya Nairb16666a2023-12-11 20:18:33 -08001546 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001547
Michael Chan6fb34492020-12-08 15:44:49 +11001548 // An MSD patch may be using the only output stream that can service this request. Release
1549 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001550 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001551
Eric Laurentf1f22e72021-07-13 14:04:14 +02001552 status_t status =
1553 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001554
1555 // only accept an output with the requested parameters
1556 if (status != NO_ERROR ||
1557 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1558 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1559 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1560 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1561 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1562 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1563 config->channel_mask, outputDesc->getChannelMask());
1564 if (*output != AUDIO_IO_HANDLE_NONE) {
1565 outputDesc->close();
1566 }
1567 // fall back to mixer output if possible when the direct output could not be open
1568 if (audio_is_linear_pcm(config->format) &&
1569 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1570 return NAME_NOT_FOUND;
1571 }
1572 *output = AUDIO_IO_HANDLE_NONE;
1573 return BAD_VALUE;
1574 }
1575 outputDesc->mDirectOpenCount = 1;
1576 outputDesc->mDirectClientSession = session;
1577
1578 addOutput(*output, outputDesc);
1579 mPreviousOutputs = mOutputs;
1580 ALOGV("%s returns new direct output %d", __func__, *output);
1581 mpClientInterface->onAudioPortListUpdate();
1582 return NO_ERROR;
1583}
1584
François Gaffie11d30102018-11-02 16:09:09 +01001585audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1586 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001587 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001588 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001589 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001590 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001591 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001592 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001593 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001594{
Andy Hungc88b0642018-04-27 15:42:35 -07001595 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001596
jiabine375d412019-02-26 12:54:53 -08001597 // Discard haptic channel mask when forcing muting haptic channels.
1598 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001599 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1600 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001601
Eric Laurente552edb2014-03-10 17:42:56 -07001602 // open a direct output if required by specified parameters
1603 //force direct flag if offload flag is set: offloading implies a direct output stream
1604 // and all common behaviors are driven by checking only the direct flag
1605 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001606 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1607 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001608 }
Nadav Bar766fb022018-01-07 12:18:03 +02001609 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1610 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001611 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001612
1613 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1614
Eric Laurente83b55d2014-11-14 10:06:21 -08001615 // only allow deep buffering for music stream type
1616 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001617 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001618 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001619 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001620 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1621 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001622 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001623 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001624 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001625 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001626 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001627 audio_is_linear_pcm(config->format) &&
1628 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001629 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001630 AUDIO_OUTPUT_FLAG_DIRECT);
1631 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001632 }
Eric Laurente552edb2014-03-10 17:42:56 -07001633
Carter Hsua3abb402021-10-26 11:11:20 +08001634 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1635 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1636 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1637 }
1638
Eric Laurentf9230d52024-01-26 18:49:09 +01001639 // Use the spatializer output if the content can be spatialized, no preferred mixer
1640 // was specified and offload or direct playback is not explicitly requested.
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001641 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001642 if (mSpatializerOutput != nullptr
jiabin2462ce82024-01-12 20:37:59 +00001643 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())
Eric Laurentf9230d52024-01-26 18:49:09 +01001644 && prefMixerConfigInfo == nullptr
1645 && ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001646 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001647 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001648 }
1649
Eric Laurentc529cf62020-04-17 18:19:10 -07001650 audio_config_t directConfig = *config;
1651 directConfig.channel_mask = channelMask;
1652 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1653 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001654 return output;
1655 }
1656
Eric Laurent14cbfca2016-03-17 09:42:16 -07001657 // A request for HW A/V sync cannot fallback to a mixed output because time
1658 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001659 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001660 return AUDIO_IO_HANDLE_NONE;
1661 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001662 // A request for Tuner cannot fallback to a mixed output
1663 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1664 return AUDIO_IO_HANDLE_NONE;
1665 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001666
Eric Laurente552edb2014-03-10 17:42:56 -07001667 // ignoring channel mask due to downmix capability in mixer
1668
1669 // open a non direct output
1670
1671 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001672 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001673 // get which output is suitable for the specified stream. The actual
1674 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001675 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001676 if (prefMixerConfigInfo != nullptr) {
1677 for (audio_io_handle_t outputHandle : outputs) {
1678 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1679 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1680 output = outputHandle;
1681 break;
1682 }
1683 }
1684 if (output == AUDIO_IO_HANDLE_NONE) {
1685 // No output open with the preferred profile. Open a new one.
1686 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1687 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1688 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1689 config.format = prefMixerConfigInfo->getConfigBase().format;
1690 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1691 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1692 &config, prefMixerConfigInfo->getFlags());
1693 if (preferredOutput == nullptr) {
1694 ALOGE("%s failed to open output with preferred mixer config", __func__);
1695 } else {
1696 output = preferredOutput->mIoHandle;
1697 }
1698 }
1699 } else {
1700 // at this stage we should ignore the DIRECT flag as no direct output could be
1701 // found earlier
1702 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1703 output = selectOutput(
1704 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1705 }
Eric Laurente552edb2014-03-10 17:42:56 -07001706 }
François Gaffie11d30102018-11-02 16:09:09 +01001707 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001708 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001709 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001710
Eric Laurente552edb2014-03-10 17:42:56 -07001711 return output;
1712}
1713
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001714sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001715 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1716 mAvailableInputDevices);
1717 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1718}
1719
1720DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1721 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1722 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723}
1724
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001725const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001726 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001727 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1728 if (msdModule != 0) {
1729 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1730 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1731 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1732 const struct audio_port_config *source = &patch->mPatch.sources[j];
1733 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1734 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001735 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001736 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001737 }
1738 }
1739 }
1740 return msdPatches;
1741}
1742
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001743bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1744 ssize_t index = mAudioPatches.indexOfKey(handle);
1745 if (index < 0) {
1746 return false;
1747 }
1748 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1749 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1750 if (msdModule == nullptr) {
1751 return false;
1752 }
1753 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1754 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1755 return true;
1756 }
1757 index = getMsdOutputPatches().indexOfKey(handle);
1758 if (index < 0) {
1759 return false;
1760 }
1761 return true;
1762}
1763
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001764status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1765 const InputProfileCollection &inputProfiles,
1766 const OutputProfileCollection &outputProfiles,
1767 const sp<DeviceDescriptor> &sourceDevice,
1768 const sp<DeviceDescriptor> &sinkDevice,
1769 AudioProfileVector& sourceProfiles,
1770 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001772 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001773 return NO_INIT;
1774 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001775 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001776 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001777 return NO_INIT;
1778 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001779 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001780 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1781 inProfile->supportsDevice(sourceDevice)) {
1782 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001783 }
1784 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001785 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001786 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001787 outProfile->supportsDevice(sinkDevice)) {
1788 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001789 }
1790 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001791 return NO_ERROR;
1792}
1793
1794status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1795 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1796 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1797{
Dean Wheatley16809da2022-12-09 14:55:46 +11001798 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1799 static const std::vector<audio_format_t> formatsOrder = {{
1800 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001801 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1802 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001803 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1804 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1805 // preferred).
1806 std::vector<audio_channel_mask_t> masks = {{
1807 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1808 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1809 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1810 // insert index masks (higher counts most preferred) as preferred over position masks
1811 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1812 masks.insert(
1813 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1814 }
1815 return masks;
1816 }();
1817
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001818 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001819 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1820 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001821 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001822 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1823 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001824 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001825 }
1826 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1827 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1828 sinkConfig->format = bestSinkConfig.format;
1829 // For encoded streams force direct flag to prevent downstream mixing.
1830 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1831 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001832 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1833 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001834 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001835 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1836 // raw and IEC61937 framed streams.
1837 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1838 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1839 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001840 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1841 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001842 sourceConfig->channel_mask =
1843 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1844 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1845 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001846 sourceConfig->format = bestSinkConfig.format;
1847 // Copy input stream directly without any processing (e.g. resampling).
1848 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1849 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1850 if (hwAvSync) {
1851 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1852 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1853 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1854 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1855 }
1856 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1857 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1858 sinkConfig->config_mask |= config_mask;
1859 sourceConfig->config_mask |= config_mask;
1860 return NO_ERROR;
1861}
1862
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001863PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1864 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001865{
1866 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001867 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1868 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1869 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1870 if (deviceModule == nullptr) {
1871 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1872 return patchBuilder;
1873 }
1874 const InputProfileCollection inputProfiles = msdIsSource ?
1875 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1876 const OutputProfileCollection outputProfiles = msdIsSource ?
1877 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1878
1879 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1880 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1881 device : getMsdAudioOutDevices().itemAt(0);
1882 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1883
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1885 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886 AudioProfileVector sourceProfiles;
1887 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001888 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1889 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001890 for (auto hwAvSync : { true, false }) {
1891 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1892 sourceProfiles, sinkProfiles) != NO_ERROR) {
1893 continue;
1894 }
1895 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1896 &sinkConfig) == NO_ERROR) {
1897 // Found a matching config. Re-create PatchBuilder with this config.
1898 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1899 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001900 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001901 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001902 " supporting PCM format conversion.", __func__);
1903 return patchBuilder;
1904}
1905
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001906status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001907 DeviceVector devices;
1908 if (outputDevices != nullptr && outputDevices->size() > 0) {
1909 devices.add(*outputDevices);
1910 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001911 // Use media strategy for unspecified output device. This should only
1912 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1913 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001914 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001915 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001916 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001917 }
Michael Chan6fb34492020-12-08 15:44:49 +11001918 std::vector<PatchBuilder> patchesToCreate;
1919 for (auto i = 0u; i < devices.size(); ++i) {
1920 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001921 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001922 }
1923 // Retain only the MSD patches associated with outputDevices request.
1924 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001925 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001926 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1927 auto retainedPatch = false;
1928 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1929 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1930 patchesToRemove.removeItemsAt(i);
1931 retainedPatch = true;
1932 break;
1933 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001934 }
Michael Chan6fb34492020-12-08 15:44:49 +11001935 if (retainedPatch) {
1936 it = patchesToCreate.erase(it);
1937 continue;
1938 }
1939 ++it;
1940 }
1941 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1942 return NO_ERROR;
1943 }
1944 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1945 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001946 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001947 }
Michael Chan6fb34492020-12-08 15:44:49 +11001948 status_t status = NO_ERROR;
1949 for (const auto &p : patchesToCreate) {
1950 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1951 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1952 char message[256];
1953 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1954 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1955 currStatus == NO_ERROR ? "Success" : "Error",
1956 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1957 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1958 if (currStatus == NO_ERROR) {
1959 ALOGD("%s", message);
1960 } else {
1961 ALOGE("%s", message);
1962 if (status == NO_ERROR) {
1963 status = currStatus;
1964 }
1965 }
1966 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001967 return status;
1968}
1969
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001970void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1971 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001972 for (size_t i = 0; i < msdPatches.size(); i++) {
1973 const auto& patch = msdPatches[i];
1974 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1975 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1976 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1977 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1978 releaseAudioPatch(patch->getHandle(), mUidCached);
1979 break;
1980 }
1981 }
1982 }
1983}
1984
Dorin Drimus94d94412022-02-02 09:05:02 +01001985bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001986 DeviceVector devicesToCheck =
1987 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001988 AudioPatchCollection msdPatches = getMsdOutputPatches();
1989 for (size_t i = 0; i < msdPatches.size(); i++) {
1990 const auto& patch = msdPatches[i];
1991 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1992 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1993 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1994 const auto& foundDevice = devicesToCheck.getDevice(
1995 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1996 if (foundDevice != nullptr) {
1997 devicesToCheck.remove(foundDevice);
1998 if (devicesToCheck.isEmpty()) {
1999 return true;
2000 }
2001 }
2002 }
2003 }
2004 }
2005 return false;
2006}
2007
Eric Laurente0720872014-03-11 09:30:41 -07002008audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002009 audio_output_flags_t flags,
2010 audio_format_t format,
2011 audio_channel_mask_t channelMask,
2012 uint32_t samplingRate,
2013 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002014{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002015 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2016 "%s called with format %#x", __func__, format);
2017
jiabinebb6af42020-06-09 17:31:17 -07002018 // Return the output that haptic-generating attached to when 1) session id is specified,
2019 // 2) haptic-generating effect exists for given session id and 3) the output that
2020 // haptic-generating effect attached to is in given outputs.
2021 if (sessionId != AUDIO_SESSION_NONE) {
2022 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2023 sessionId, FX_IID_HAPTICGENERATOR);
2024 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2025 return hapticGeneratingOutput;
2026 }
2027 }
2028
Eric Laurent16c66dd2019-05-01 17:54:10 -07002029 // Flags disqualifying an output: the match must happen before calling selectOutput()
2030 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2031 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2032
2033 // Flags expressing a functional request: must be honored in priority over
2034 // other criteria
2035 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2036 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002037 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2038 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002039 // Flags expressing a performance request: have lower priority than serving
2040 // requested sampling rate or channel mask
2041 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2042 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2043 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2044
2045 const audio_output_flags_t functionalFlags =
2046 (audio_output_flags_t)(flags & kFunctionalFlags);
2047 const audio_output_flags_t performanceFlags =
2048 (audio_output_flags_t)(flags & kPerformanceFlags);
2049
2050 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2051
Eric Laurente552edb2014-03-10 17:42:56 -07002052 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002053 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002054 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002055 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002056 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002057 // with tiebreak preferring the minimum number of extra functional flags
2058 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002059 // 3: the output supporting the exact channel mask
2060 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002061 // 5: the output with the highest sampling rate if the requested sample rate is
2062 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002063 // 6: the output with the highest number of requested performance flags
2064 // 7: the output with the bit depth the closest to the requested one
2065 // 8: the primary output
2066 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002067
Eric Laurent16c66dd2019-05-01 17:54:10 -07002068 // matching criteria values in priority order for best matching output so far
2069 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002070
Eric Laurent16c66dd2019-05-01 17:54:10 -07002071 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2072 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2073 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002074
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002075 for (audio_io_handle_t output : outputs) {
2076 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002077 // matching criteria values in priority order for current output
2078 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002079
Eric Laurent16c66dd2019-05-01 17:54:10 -07002080 if (outputDesc->isDuplicated()) {
2081 continue;
2082 }
2083 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2084 continue;
2085 }
Eric Laurent8838a382014-09-08 16:44:28 -07002086
Eric Laurent16c66dd2019-05-01 17:54:10 -07002087 // If haptic channel is specified, use the haptic output if present.
2088 // When using haptic output, same audio format and sample rate are required.
2089 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002090 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002091 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2092 continue;
2093 }
2094 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002095 && format == outputDesc->getFormat()
2096 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002097 currentMatchCriteria[0] = outputHapticChannelCount;
2098 }
2099
2100 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002101 const int matchingFunctionalFlags =
2102 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2103 const int totalFunctionalFlags =
2104 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2105 // Prefer matching functional flags, but subtract unnecessary functional flags.
2106 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002107
2108 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002109 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2110 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002111 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2112 channelCount <= outputChannelCount) {
2113 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002114 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2115 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002116 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002117 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002118 currentMatchCriteria[3] = outputChannelCount;
2119 }
2120
2121 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002122 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002123 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002124 }
2125
2126 // performance flags match
2127 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2128
2129 // format match
2130 if (format != AUDIO_FORMAT_INVALID) {
2131 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002132 PolicyAudioPort::kFormatDistanceMax -
2133 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002134 }
2135
2136 // primary output match
2137 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2138
2139 // compare match criteria by priority then value
2140 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2141 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2142 bestMatchCriteria = currentMatchCriteria;
2143 bestOutput = output;
2144
2145 std::stringstream result;
2146 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2147 std::ostream_iterator<int>(result, " "));
2148 ALOGV("%s new bestOutput %d criteria %s",
2149 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002150 }
2151 }
2152
Eric Laurent16c66dd2019-05-01 17:54:10 -07002153 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002154}
2155
Eric Laurent8fc147b2018-07-22 19:13:55 -07002156status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002157{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002158 ALOGV("%s portId %d", __FUNCTION__, portId);
2159
2160 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2161 if (outputDesc == 0) {
2162 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002163 return BAD_VALUE;
2164 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002165 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002166
Eric Laurent8fc147b2018-07-22 19:13:55 -07002167 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002168 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002169
Eric Laurent733ce942017-12-07 12:18:25 -08002170 status_t status = outputDesc->start();
2171 if (status != NO_ERROR) {
2172 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002173 }
2174
Eric Laurent97ac8712018-07-27 18:59:02 -07002175 uint32_t delayMs;
2176 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002177
2178 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002179 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002180 if (status == DEAD_OBJECT) {
2181 sp<SwAudioOutputDescriptor> desc =
2182 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2183 if (desc == nullptr) {
2184 // This is not common, it may indicate something wrong with the HAL.
2185 ALOGE("%s unable to open output with default config", __func__);
2186 return status;
2187 }
2188 desc->mUsePreferredMixerAttributes = true;
2189 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002190 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002191 }
jiabina84c3d32022-12-02 18:59:55 +00002192
2193 // If the client is the first one active on preferred mixer parameters, reopen the output
2194 // if the current mixer parameters doesn't match the preferred one.
2195 if (outputDesc->devices().size() == 1) {
2196 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2197 outputDesc->devices()[0]->getId(), client->strategy());
2198 if (info != nullptr && info->getUid() == client->uid()) {
2199 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2200 info->getConfigBase(), info->getFlags())) {
2201 stopSource(outputDesc, client);
2202 outputDesc->stop();
2203 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2204 config.channel_mask = info->getConfigBase().channel_mask;
2205 config.sample_rate = info->getConfigBase().sample_rate;
2206 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002207 sp<SwAudioOutputDescriptor> desc =
2208 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2209 if (desc == nullptr) {
2210 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002211 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002212 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002213 // Intentionally return error to let the client side resending request for
2214 // creating and starting.
2215 return DEAD_OBJECT;
2216 }
2217 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002218 if (info->getActiveClientCount() == 1 &&
2219 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2220 // If it is first bit-perfect client, reroute all clients that will be routed to
2221 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2222 PortHandleVector clientsToInvalidate;
2223 for (size_t i = 0; i < mOutputs.size(); i++) {
2224 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002225 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002226 continue;
2227 }
2228 for (const auto& c : mOutputs[i]->getClientIterable()) {
2229 clientsToInvalidate.push_back(c->portId());
2230 }
2231 }
2232 if (!clientsToInvalidate.empty()) {
2233 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2234 __func__);
2235 mpClientInterface->invalidateTracks(clientsToInvalidate);
2236 }
2237 }
jiabina84c3d32022-12-02 18:59:55 +00002238 }
2239 }
2240
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002241 if (client->hasPreferredDevice()) {
2242 // playback activity with preferred device impacts routing occurred, inform upper layers
2243 mpClientInterface->onRoutingUpdated();
2244 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002245 if (delayMs != 0) {
2246 usleep(delayMs * 1000);
2247 }
2248
2249 return status;
2250}
2251
Eric Laurent96d1dda2022-03-14 17:14:19 +01002252bool AudioPolicyManager::isLeUnicastActive() const {
2253 if (isInCall()) {
2254 return true;
2255 }
2256 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2257}
2258
2259bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2260 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2261 return false;
2262 }
2263 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2264 ALOGV("%s active %d", __func__, active);
2265 return active;
2266}
2267
Eric Laurent97ac8712018-07-27 18:59:02 -07002268status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2269 const sp<TrackClientDescriptor>& client,
2270 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002271{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002272 // cannot start playback of STREAM_TTS if any other output is being used
2273 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002274
2275 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002276 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002277 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002278 auto clientStrategy = client->strategy();
2279 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002280 if (stream == AUDIO_STREAM_TTS) {
2281 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002282 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002283 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002284 return INVALID_OPERATION;
2285 } else {
2286 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2287 }
2288 } else {
2289 // some playback other than beacon starts
2290 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2291 }
2292
Eric Laurent77305a62016-07-25 16:39:22 -07002293 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002294 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002295 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002296
François Gaffie11d30102018-11-02 16:09:09 +01002297 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002298 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002299 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002300 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002301 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002302 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002303 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002304 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002305 } else {
2306 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002307 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002308 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2309 AUDIO_FORMAT_DEFAULT);
2310 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2311 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002312 }
2313
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002314 // requiresMuteCheck is false when we can bypass mute strategy.
2315 // It covers a common case when there is no materially active audio
2316 // and muting would result in unnecessary delay and dropped audio.
2317 const uint32_t outputLatencyMs = outputDesc->latency();
2318 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002319 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002320
Eric Laurente552edb2014-03-10 17:42:56 -07002321 // increment usage count for this stream on the requested output:
2322 // NOTE that the usage count is the same for duplicated output and hardware output which is
2323 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002324 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002325
2326 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002327 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002328 // Preferred device may be exclusive, use only if no other active clients on this output
2329 devices = DeviceVector(
2330 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2331 } else {
2332 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2333 }
François Gaffie11d30102018-11-02 16:09:09 +01002334 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002335 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002336 }
2337 }
Eric Laurente552edb2014-03-10 17:42:56 -07002338
François Gaffiec005e562018-11-06 15:04:49 +01002339 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002340 selectOutputForMusicEffects();
2341 }
2342
François Gaffie1c878552018-11-22 16:53:21 +01002343 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002344 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002345 if (devices.isEmpty()) {
2346 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002347 }
François Gaffiec005e562018-11-06 15:04:49 +01002348 bool shouldWait =
2349 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2350 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2351 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002352 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002353 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002354 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002355 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002356 // An output has a shared device if
2357 // - managed by the same hw module
2358 // - supports the currently selected device
2359 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002360 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002361
Eric Laurent77305a62016-07-25 16:39:22 -07002362 // force a device change if any other output is:
2363 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002364 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002365 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002366 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002367 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002368 // change the device currently selected by the other output.
2369 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002370 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002371 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002372 force = true;
2373 }
2374 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002375 // a notification so that audio focus effect can propagate, or that a mute/unmute
2376 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002377 const uint32_t latencyMs = desc->latency();
2378 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2379
2380 if (shouldWait && isActive && (waitMs < latencyMs)) {
2381 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002382 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002383
2384 // Require mute check if another output is on a shared device
2385 // and currently active to have proper drain and avoid pops.
2386 // Note restoring AudioTracks onto this output needs to invoke
2387 // a volume ramp if there is no mute.
2388 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002389 }
2390 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002391
jiabin3ff8d7d2022-12-13 06:27:44 +00002392 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2393 // If the output is open with preferred mixer attributes, but the routed device is
2394 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2395 // changed.
2396 return DEAD_OBJECT;
2397 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002398 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302399 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2400 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002401
Eric Laurente552edb2014-03-10 17:42:56 -07002402 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002403 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002404 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002405 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002406 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002407 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002408 outputDesc->useHwGain() /*force*/)) {
2409 // request AudioService to reinitialize the volume curves asynchronously
2410 ALOGE("checkAndSetVolume failed, requesting volume range init");
2411 mpClientInterface->onVolumeRangeInitRequest();
2412 };
Eric Laurente552edb2014-03-10 17:42:56 -07002413
2414 // update the outputs if starting an output with a stream that can affect notification
2415 // routing
2416 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002417
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002418 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002419 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002420 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002421 }
Eric Laurentdc462862016-07-19 12:29:53 -07002422
2423 if (waitMs > muteWaitMs) {
2424 *delayMs = waitMs - muteWaitMs;
2425 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002426
2427 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2428 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2429 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2430 // change occurs after the MixerThread starts and causes a stream volume
2431 // glitch.
2432 //
2433 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002434 }
Eric Laurentdc462862016-07-19 12:29:53 -07002435
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002436 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002437 mEngine->getForceUse(
2438 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002439 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002440 }
2441
Eric Laurent97ac8712018-07-27 18:59:02 -07002442 // Automatically enable the remote submix input when output is started on a re routing mix
2443 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002444 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2445 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002446 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2447 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2448 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002449 "remote-submix",
2450 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002451 }
2452
Eric Laurent96d1dda2022-03-14 17:14:19 +01002453 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2454
Eric Laurente552edb2014-03-10 17:42:56 -07002455 return NO_ERROR;
2456}
2457
Eric Laurent96d1dda2022-03-14 17:14:19 +01002458void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2459 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2460 bool isUnicastActive = isLeUnicastActive();
2461
2462 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002463 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002464 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2465 for (size_t i = 0; i < mOutputs.size(); i++) {
2466 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2467 if (desc != ignoredOutput && desc->isActive()
2468 && ((isUnicastActive &&
2469 !desc->devices().
2470 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2471 || (wasUnicastActive &&
2472 !desc->devices().getDevicesFromTypes(
2473 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2474 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2475 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002476 if (desc->mUsePreferredMixerAttributes && force) {
2477 // If the device is using preferred mixer attributes, the output need to reopen
2478 // with default configuration when the new selected devices are different from
2479 // current routing devices.
2480 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2481 continue;
2482 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302483 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002484 // re-apply device specific volume if not done by setOutputDevice()
2485 if (!force) {
2486 applyStreamVolumes(desc, newDevices.types(), delayMs);
2487 }
2488 }
2489 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002490 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002491 }
2492}
2493
Eric Laurent8fc147b2018-07-22 19:13:55 -07002494status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002495{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002496 ALOGV("%s portId %d", __FUNCTION__, portId);
2497
2498 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2499 if (outputDesc == 0) {
2500 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002501 return BAD_VALUE;
2502 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002503 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002504
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002505 if (client->hasPreferredDevice(true)) {
2506 // playback activity with preferred device impacts routing occurred, inform upper layers
2507 mpClientInterface->onRoutingUpdated();
2508 }
2509
Eric Laurent97ac8712018-07-27 18:59:02 -07002510 ALOGV("stopOutput() output %d, stream %d, session %d",
2511 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002512
Eric Laurent97ac8712018-07-27 18:59:02 -07002513 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002514
Eric Laurent733ce942017-12-07 12:18:25 -08002515 if (status == NO_ERROR ) {
2516 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002517 } else {
2518 return status;
2519 }
2520
2521 if (outputDesc->devices().size() == 1) {
2522 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2523 outputDesc->devices()[0]->getId(), client->strategy());
2524 if (info != nullptr && info->getUid() == client->uid()) {
2525 info->decreaseActiveClient();
2526 if (info->getActiveClientCount() == 0) {
2527 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2528 }
2529 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002530 }
2531 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002532}
2533
Eric Laurent97ac8712018-07-27 18:59:02 -07002534status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2535 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002536{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002537 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002538 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002539 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002540 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002541
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002542 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2543
François Gaffie1c878552018-11-22 16:53:21 +01002544 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2545 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002546 // Automatically disable the remote submix input when output is stopped on a
2547 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002548 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002549 if (isSingleDeviceType(
2550 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002551 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002552 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002553 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2554 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002555 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002556 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002557 }
2558 }
2559 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002560 if (client->hasPreferredDevice(true) &&
2561 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002562 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002563 forceDeviceUpdate = true;
2564 }
2565
Eric Laurente552edb2014-03-10 17:42:56 -07002566 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002567 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002568
Eric Laurente552edb2014-03-10 17:42:56 -07002569 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002570 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002571 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002572 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002573
2574 // If the routing does not change, if an output is routed on a device using HwGain
2575 // (aka setAudioPortConfig) and there are still active clients following different
2576 // volume group(s), force reapply volume
2577 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2578 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2579
Eric Laurente552edb2014-03-10 17:42:56 -07002580 // delay the device switch by twice the latency because stopOutput() is executed when
2581 // the track stop() command is received and at that time the audio track buffer can
2582 // still contain data that needs to be drained. The latency only covers the audio HAL
2583 // and kernel buffers. Also the latency does not always include additional delay in the
2584 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302585 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002586 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002587
2588 // force restoring the device selection on other active outputs if it differs from the
2589 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002590 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002591 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002592 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002593 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002594 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002595 desc->isActive() &&
2596 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002597 (newDevices != desc->devices())) {
2598 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2599 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002600
jiabin3ff8d7d2022-12-13 06:27:44 +00002601 if (desc->mUsePreferredMixerAttributes && force) {
2602 // If the device is using preferred mixer attributes, the output need to
2603 // reopen with default configuration when the new selected devices are
2604 // different from current routing devices.
2605 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2606 continue;
2607 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302608 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002609
Eric Laurent57de36c2016-09-28 16:59:11 -07002610 // re-apply device specific volume if not done by setOutputDevice()
2611 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002612 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002613 }
Eric Laurente552edb2014-03-10 17:42:56 -07002614 }
2615 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002616 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002617 // update the outputs if stopping one with a stream that can affect notification routing
2618 handleNotificationRoutingForStream(stream);
2619 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002620
2621 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2622 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002623 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002624 }
2625
François Gaffiec005e562018-11-06 15:04:49 +01002626 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002627 selectOutputForMusicEffects();
2628 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002629
2630 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2631
Eric Laurente552edb2014-03-10 17:42:56 -07002632 return NO_ERROR;
2633 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002634 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002635 return INVALID_OPERATION;
2636 }
2637}
2638
jiabinbce0c1d2020-10-05 11:20:18 -07002639bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002640{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002641 ALOGV("%s portId %d", __FUNCTION__, portId);
2642
2643 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2644 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002645 // If an output descriptor is closed due to a device routing change,
2646 // then there are race conditions with releaseOutput from tracks
2647 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2648 // destroyed shortly thereafter.
2649 //
2650 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002651 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002652 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002653 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002654
2655 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002656
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302657 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2658 if (outputDesc->isClientActive(client)) {
2659 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2660 stopOutput(portId);
2661 }
2662
Eric Laurent8fc147b2018-07-22 19:13:55 -07002663 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2664 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002665 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002666 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002667 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002668 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002669 if (--outputDesc->mDirectOpenCount == 0) {
2670 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002671 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002672 }
2673 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302674
Andy Hung39efb7a2018-09-26 15:39:28 -07002675 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002676 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2677 // The output is pending reopened to query dynamic profiles and
2678 // there is no active clients
2679 closeOutput(outputDesc->mIoHandle);
2680 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2681 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2682 if (newOutputDesc == nullptr) {
2683 ALOGE("%s failed to open output", __func__);
2684 }
2685 return true;
2686 }
2687 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002688}
2689
Eric Laurentcaf7f482014-11-25 17:50:47 -08002690status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2691 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002692 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002693 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002694 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002695 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002696 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002697 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002698 input_type_t *inputType,
2699 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002700{
François Gaffiec005e562018-11-06 15:04:49 +01002701 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002702 "flags %#x attributes=%s requested device ID %d",
2703 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2704 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002705
Eric Laurentad2e7b92017-09-14 20:06:42 -07002706 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002707 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002708 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002709 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002710 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002711 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002712 sp<RecordClientDescriptor> clientDesc;
2713 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002714 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002715 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002716
2717 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2718 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2719 return INVALID_OPERATION;
2720 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002721
Francois Gaffie716e1432019-01-14 16:58:59 +01002722 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2723 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002724 }
2725
Paul McLean466dc8e2015-04-17 13:15:36 -06002726 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002727 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002728 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002729
Eric Laurentad2e7b92017-09-14 20:06:42 -07002730 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2731 // possible
2732 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2733 *input != AUDIO_IO_HANDLE_NONE) {
2734 ssize_t index = mInputs.indexOfKey(*input);
2735 if (index < 0) {
2736 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2737 status = BAD_VALUE;
2738 goto error;
2739 }
2740 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002741 RecordClientVector clients = inputDesc->getClientsForSession(session);
2742 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002743 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2744 status = BAD_VALUE;
2745 goto error;
2746 }
2747 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2748 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002749 // corresponds to a new client and is only permitted from the same UID.
2750 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002751 if (clients.size() > 1) {
2752 for (const auto& client : clients) {
2753 // The client map is ordered by key values (portId) and portIds are allocated
2754 // incrementaly. So the first client in this list is the one opened by audio flinger
2755 // when the mmap stream is created and should be ignored as it does not correspond
2756 // to an actual client
2757 if (client == *clients.cbegin()) {
2758 continue;
2759 }
2760 if (uid != client->uid() && !client->isSilenced()) {
2761 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2762 uid, client->portId(), client->uid());
2763 status = INVALID_OPERATION;
2764 goto error;
2765 }
Eric Laurent331679c2018-04-16 17:03:16 -07002766 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002767 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002768 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002769 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002770
Eric Laurentfecbceb2021-02-09 14:46:43 +01002771 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002772 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002773 }
2774
2775 *input = AUDIO_IO_HANDLE_NONE;
2776 *inputType = API_INPUT_INVALID;
2777
Francois Gaffie716e1432019-01-14 16:58:59 +01002778 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002779 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002780 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002781 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002782 ALOGW("%s could not find input mix for attr %s",
2783 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002784 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002785 }
jiabinc1de2df2019-05-07 14:26:40 -07002786 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2787 String8(attr->tags + strlen("addr=")),
2788 AUDIO_FORMAT_DEFAULT);
2789 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002790 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002791 __func__, attributes.source, attributes.tags);
2792 status = BAD_VALUE;
2793 goto error;
2794 }
2795
Kevin Rocard25f9b052019-02-27 15:08:54 -08002796 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2797 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2798 } else {
2799 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2800 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002801 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002802 if (explicitRoutingDevice != nullptr) {
2803 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002804 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002805 // Prevent from storing invalid requested device id in clients
2806 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002807 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002808 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2809 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002810 }
François Gaffie11d30102018-11-02 16:09:09 +01002811 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002812 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002813 status = BAD_VALUE;
2814 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002815 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002816 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2817 *inputType = API_INPUT_MIX_CAPTURE;
2818 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002819 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2820 // there is an external policy, but this input is attached to a mix of recorders,
2821 // meaning it receives audio injected into the framework, so the recorder doesn't
2822 // know about it and is therefore considered "legacy"
2823 *inputType = API_INPUT_LEGACY;
2824 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002825 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002826 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002827 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002828 } else {
2829 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002830 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002831
Eric Laurent599c7582015-12-07 18:05:55 -08002832 }
2833
François Gaffiec005e562018-11-06 15:04:49 +01002834 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002835 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002836 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002837 AudioProfileVector profiles;
2838 status_t ret = getProfilesForDevices(
2839 DeviceVector(device), profiles, flags, true /*isInput*/);
2840 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002841 const auto channels = profiles[0]->getChannels();
2842 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2843 config->channel_mask = *channels.begin();
2844 }
2845 const auto sampleRates = profiles[0]->getSampleRates();
2846 if (!sampleRates.empty() &&
2847 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2848 config->sample_rate = *sampleRates.begin();
2849 }
jiabinf1c73972022-04-14 16:28:52 -07002850 config->format = profiles[0]->getFormat();
2851 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002852 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002853 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002854
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855exit:
2856
François Gaffiec005e562018-11-06 15:04:49 +01002857 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2858 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002859
Francois Gaffie716e1432019-01-14 16:58:59 +01002860 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002861 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002862 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002863
Mikhail Naganov2996f672019-04-18 12:29:59 -07002864 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002865 requestedDeviceId, attributes.source, flags,
2866 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002867 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002868 // Move (if found) effect for the client session to its input
2869 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002870 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002871
2872 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2873 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002874
Eric Laurent599c7582015-12-07 18:05:55 -08002875 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002876
2877error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002878 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002879}
2880
2881
François Gaffie11d30102018-11-02 16:09:09 +01002882audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002883 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002884 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002885 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002886 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002887 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002888{
2889 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002890 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002891 bool isSoundTrigger = false;
2892
François Gaffiec005e562018-11-06 15:04:49 +01002893 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002894 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2895 if (index >= 0) {
2896 input = mSoundTriggerSessions.valueFor(session);
2897 isSoundTrigger = true;
2898 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2899 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2900 } else {
2901 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002902 }
François Gaffiec005e562018-11-06 15:04:49 +01002903 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002904 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002905 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002906 }
2907
Carter Hsua3abb402021-10-26 11:11:20 +08002908 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2909 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2910 }
2911
Eric Laurentfe231122017-11-17 17:48:06 -08002912 // sampling rate and flags may be updated by getInputProfile
2913 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2914 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002915 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002916 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002917 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002918 // find a compatible input profile (not necessarily identical in parameters)
2919 sp<IOProfile> profile = getInputProfile(
2920 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2921 if (profile == nullptr) {
2922 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002923 }
jiabin2fd710d2022-05-02 23:20:22 +00002924
Glenn Kasten05ddca52016-02-11 08:17:12 -08002925 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002926 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002927 if (samplingRate == 0) {
2928 samplingRate = profileSamplingRate;
2929 }
Eric Laurente552edb2014-03-10 17:42:56 -07002930
Eric Laurent322b4d22015-04-03 15:57:54 -07002931 if (profile->getModuleHandle() == 0) {
2932 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002933 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002934 }
2935
Eric Laurentec376dc2021-04-08 20:41:22 +02002936 // Reuse an already opened input if a client with the same session ID already exists
2937 // on that input
2938 for (size_t i = 0; i < mInputs.size(); i++) {
2939 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2940 if (desc->mProfile != profile) {
2941 continue;
2942 }
2943 RecordClientVector clients = desc->clientsList();
2944 for (const auto &client : clients) {
2945 if (session == client->session()) {
2946 return desc->mIoHandle;
2947 }
2948 }
2949 }
2950
Eric Laurent3974e3b2017-12-07 17:58:43 -08002951 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002952 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002953 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002954 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002955 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002956 continue;
2957 }
2958 // if sound trigger, reuse input if used by other sound trigger on same session
2959 // else
2960 // reuse input if active client app is not in IDLE state
2961 //
2962 RecordClientVector clients = desc->clientsList();
2963 bool doClose = false;
2964 for (const auto& client : clients) {
2965 if (isSoundTrigger != client->isSoundTrigger()) {
2966 continue;
2967 }
2968 if (client->isSoundTrigger()) {
2969 if (session == client->session()) {
2970 return desc->mIoHandle;
2971 }
2972 continue;
2973 }
2974 if (client->active() && client->appState() != APP_STATE_IDLE) {
2975 return desc->mIoHandle;
2976 }
2977 doClose = true;
2978 }
2979 if (doClose) {
2980 closeInput(desc->mIoHandle);
2981 } else {
2982 i++;
2983 }
2984 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002985 }
2986
Eric Laurentfe231122017-11-17 17:48:06 -08002987 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002988
Eric Laurentfe231122017-11-17 17:48:06 -08002989 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2990 lConfig.sample_rate = profileSamplingRate;
2991 lConfig.channel_mask = profileChannelMask;
2992 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002993
François Gaffie11d30102018-11-02 16:09:09 +01002994 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002995
2996 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002997 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002998 (profileSamplingRate != lConfig.sample_rate) ||
2999 !audio_formats_match(profileFormat, lConfig.format) ||
3000 (profileChannelMask != lConfig.channel_mask)) {
3001 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003002 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003003 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003004 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003005 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003006 }
Eric Laurent599c7582015-12-07 18:05:55 -08003007 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003008 }
3009
Eric Laurentc722f302014-12-10 11:21:49 -08003010 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003011
Eric Laurent599c7582015-12-07 18:05:55 -08003012 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003013 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003014
Eric Laurent599c7582015-12-07 18:05:55 -08003015 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003016}
3017
Eric Laurent4eb58f12018-12-07 16:41:02 -08003018status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003019{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003020 ALOGV("%s portId %d", __FUNCTION__, portId);
3021
3022 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3023 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003024 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003025 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003026 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003027 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003028 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003029 if (client->active()) {
3030 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3031 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003032 }
3033
Eric Laurent8f42ea12018-08-08 09:08:25 -07003034 audio_session_t session = client->session();
3035
Eric Laurent4eb58f12018-12-07 16:41:02 -08003036 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003037
Eric Laurent4eb58f12018-12-07 16:41:02 -08003038 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003039
Eric Laurent4eb58f12018-12-07 16:41:02 -08003040 status_t status = inputDesc->start();
3041 if (status != NO_ERROR) {
3042 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003043 }
Eric Laurente552edb2014-03-10 17:42:56 -07003044
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003045 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003046 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003047 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003048
Eric Laurent8f42ea12018-08-08 09:08:25 -07003049 // indicate active capture to sound trigger service if starting capture from a mic on
3050 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003051 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003052 if (device != nullptr) {
3053 status = setInputDevice(input, device, true /* force */);
3054 } else {
3055 ALOGW("%s no new input device can be found for descriptor %d",
3056 __FUNCTION__, inputDesc->getId());
3057 status = BAD_VALUE;
3058 }
Eric Laurente552edb2014-03-10 17:42:56 -07003059
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003060 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003061 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003063 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003064 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3065 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003066 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003067 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003068
François Gaffie11d30102018-11-02 16:09:09 +01003069 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3070 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003072 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003073 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003074
Eric Laurent8f42ea12018-08-08 09:08:25 -07003075 // automatically enable the remote submix output when input is started if not
3076 // used by a policy mix of type MIX_TYPE_RECORDERS
3077 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003078 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003079 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003080 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003081 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003082 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3083 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003084 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003085 if (address != "") {
3086 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3087 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003088 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003089 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003090 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003091 } else if (status != NO_ERROR) {
3092 // Restore client activity state.
3093 inputDesc->setClientActive(client, false);
3094 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003095 }
3096
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003097 ALOGV("%s input %d source = %d status = %d exit",
3098 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003099
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003100 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003101}
3102
Eric Laurent8fc147b2018-07-22 19:13:55 -07003103status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003104{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003105 ALOGV("%s portId %d", __FUNCTION__, portId);
3106
3107 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3108 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003109 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003110 return BAD_VALUE;
3111 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003112 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003113 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003114 if (!client->active()) {
3115 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003116 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003117 }
Carter Hsue6139d52021-07-08 10:30:20 +08003118 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003119 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003120
Eric Laurent8f42ea12018-08-08 09:08:25 -07003121 inputDesc->stop();
3122 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003123 auto current_source = inputDesc->source();
3124 setInputDevice(input, getNewInputDevice(inputDesc),
3125 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003126 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003127 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003128 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003129 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003130 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3131 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003132 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003133 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003134
3135 // automatically disable the remote submix output when input is stopped if not
3136 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003137 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003138 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003139 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003140 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003141 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3142 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003143 }
3144 if (address != "") {
3145 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3146 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003147 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003148 }
3149 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003150 resetInputDevice(input);
3151
3152 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3153 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003154 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3155 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003156 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003157 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003158 }
3159 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003160 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003161 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003162}
3163
Eric Laurent8fc147b2018-07-22 19:13:55 -07003164void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003165{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003166 ALOGV("%s portId %d", __FUNCTION__, portId);
3167
3168 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3169 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003170 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003171 return;
3172 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003173 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003174 audio_io_handle_t input = inputDesc->mIoHandle;
3175
Eric Laurent8f42ea12018-08-08 09:08:25 -07003176 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003177
Andy Hung39efb7a2018-09-26 15:39:28 -07003178 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003179 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003180 if (inputDesc->getClientCount() > 0) {
3181 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003182 return;
3183 }
3184
Eric Laurent05b90f82014-08-27 15:32:29 -07003185 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003186 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003187 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003188}
3189
Eric Laurent8f42ea12018-08-08 09:08:25 -07003190void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003191{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003192 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003193
3194 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003195 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003196 }
3197}
3198
Eric Laurent8f42ea12018-08-08 09:08:25 -07003199void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3200{
3201 stopInput(portId);
3202 releaseInput(portId);
3203}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003204
Eric Laurent0dd51852019-04-19 18:18:58 -07003205void AudioPolicyManager::checkCloseInputs() {
3206 // After connecting or disconnecting an input device, close input if:
3207 // - it has no client (was just opened to check profile) OR
3208 // - none of its supported devices are connected anymore OR
3209 // - one of its clients cannot be routed to one of its supported
3210 // devices anymore. Otherwise update device selection
3211 std::vector<audio_io_handle_t> inputsToClose;
3212 for (size_t i = 0; i < mInputs.size(); i++) {
3213 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3214 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003215 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003216 inputsToClose.push_back(mInputs.keyAt(i));
3217 } else {
3218 bool close = false;
3219 for (const auto& client : input->clientsList()) {
3220 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003221 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3222 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003223 if (!input->supportedDevices().contains(device)) {
3224 close = true;
3225 break;
3226 }
3227 }
3228 if (close) {
3229 inputsToClose.push_back(mInputs.keyAt(i));
3230 } else {
3231 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3232 }
3233 }
3234 }
3235
3236 for (const audio_io_handle_t handle : inputsToClose) {
3237 ALOGV("%s closing input %d", __func__, handle);
3238 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003239 }
Eric Laurentd4692962014-05-05 18:13:44 -07003240}
3241
François Gaffie251c7f02018-11-07 10:41:08 +01003242void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003243{
3244 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003245 if (indexMin < 0 || indexMax < 0) {
3246 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3247 return;
3248 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003249 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003250
3251 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003252 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3253 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003254 continue;
3255 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003256 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003257 }
Eric Laurente552edb2014-03-10 17:42:56 -07003258}
3259
Eric Laurente0720872014-03-11 09:30:41 -07003260status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003261 int index,
3262 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003263{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003264 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003265 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3266 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3267 return NO_ERROR;
3268 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003269 ALOGV("%s: stream %s attributes=%s", __func__,
3270 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003271 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003272}
3273
Eric Laurente0720872014-03-11 09:30:41 -07003274status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003275 int *index,
3276 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003277{
François Gaffiec005e562018-11-06 15:04:49 +01003278 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3279 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003280 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003281 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003282 deviceTypes = mEngine->getOutputDevicesForStream(
3283 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003284 }
jiabin9a3361e2019-10-01 09:38:30 -07003285 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003286}
3287
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003288status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003289 int index,
3290 audio_devices_t device)
3291{
3292 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003293 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3294 if (group == VOLUME_GROUP_NONE) {
3295 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003296 return BAD_VALUE;
3297 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003298 ALOGV("%s: group %d matching with %s index %d",
3299 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003300 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003301 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003302 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003303 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3304 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3305 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3306 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003307 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3308
3309 status = setVolumeCurveIndex(index, device, curves);
3310 if (status != NO_ERROR) {
3311 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3312 return status;
3313 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003314
jiabin9a3361e2019-10-01 09:38:30 -07003315 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003316 auto curCurvAttrs = curves.getAttributes();
3317 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3318 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003319 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003320 } else if (!curves.getStreamTypes().empty()) {
3321 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003322 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003323 } else {
3324 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3325 return BAD_VALUE;
3326 }
jiabin9a3361e2019-10-01 09:38:30 -07003327 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3328 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003329
François Gaffiecfe17322018-11-07 13:41:29 +01003330 // update volume on all outputs and streams matching the following:
3331 // - The requested stream (or a stream matching for volume control) is active on the output
3332 // - The device (or devices) selected by the engine for this stream includes
3333 // the requested device
3334 // - For non default requested device, currently selected device on the output is either the
3335 // requested device or one of the devices selected by the engine for this stream
3336 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3337 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003338 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003339 for (size_t i = 0; i < mOutputs.size(); i++) {
3340 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003341 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003342
jiabin9a3361e2019-10-01 09:38:30 -07003343 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3344 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003345 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003346
3347 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003348 continue;
3349 }
3350 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3351 curDevices.find(device) == curDevices.end()) {
3352 continue;
3353 }
3354 bool applyVolume = false;
3355 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3356 curSrcDevices.insert(device);
3357 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003358 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3359 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003360 } else {
3361 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3362 }
3363 if (!applyVolume) {
3364 continue; // next output
3365 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003366 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3367 // If a higher priority strategy is active, and the output is routed to a device with a
3368 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003369 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003370 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003371 // If the volume source is active with higher priority source, ensure at least Sw Muted
3372 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003373 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3374 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3375 false /*preferredDevice*/);
3376 if (activeClients.empty()) {
3377 continue;
3378 }
3379 bool isPreempted = false;
3380 bool isHigherPriority = productStrategy < strategy;
3381 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003382 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003383 ALOGV("%s: Strategy=%d (\nrequester:\n"
3384 " group %d, volumeGroup=%d attributes=%s)\n"
3385 " higher priority source active:\n"
3386 " volumeGroup=%d attributes=%s) \n"
3387 " on output %zu, bailing out", __func__, productStrategy,
3388 group, group, toString(attributes).c_str(),
3389 client->volumeSource(), toString(client->attributes()).c_str(), i);
3390 applyVolume = false;
3391 isPreempted = true;
3392 break;
3393 }
3394 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003395 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003396 applyVolume = true;
3397 }
3398 }
3399 if (isPreempted || applyVolume) {
3400 break;
3401 }
3402 }
3403 if (!applyVolume) {
3404 continue; // next output
3405 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003406 }
François Gaffieed91f582020-01-31 10:35:37 +01003407 //FIXME: workaround for truncated touch sounds
3408 // delayed volume change for system stream to be removed when the problem is
3409 // handled by system UI
3410 status_t volStatus = checkAndSetVolume(
3411 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003412 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003413 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3414 if (volStatus != NO_ERROR) {
3415 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003416 }
3417 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003418
3419 // update voice volume if the an active call route exists
3420 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3421 && (curSrcDevices.find(
3422 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3423 != curSrcDevices.end())) {
3424 bool isVoiceVolSrc;
3425 bool isBtScoVolSrc;
3426 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3427 isVoiceVolSrc, isBtScoVolSrc, __func__)
3428 && (isVoiceVolSrc || isBtScoVolSrc)) {
3429 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3430 }
3431 }
3432
François Gaffiecfe17322018-11-07 13:41:29 +01003433 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3434 return status;
3435}
3436
François Gaffieaaac0fd2018-11-22 17:56:39 +01003437status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003438 audio_devices_t device,
3439 IVolumeCurves &volumeCurves)
3440{
3441 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3442 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003443 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3444 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003445 (index > volumeCurves.getVolumeIndexMax())) {
3446 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3447 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3448 return BAD_VALUE;
3449 }
3450 if (!audio_is_output_device(device)) {
3451 return BAD_VALUE;
3452 }
3453
3454 // Force max volume if stream cannot be muted
3455 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3456
François Gaffieaaac0fd2018-11-22 17:56:39 +01003457 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003458 volumeCurves.addCurrentVolumeIndex(device, index);
3459 return NO_ERROR;
3460}
3461
3462status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3463 int &index,
3464 audio_devices_t device)
3465{
3466 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3467 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003468 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003469 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003470 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003471 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003472 }
jiabin9a3361e2019-10-01 09:38:30 -07003473 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003474}
3475
3476status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3477 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003478 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003479{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003480 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003481 return BAD_VALUE;
3482 }
jiabin9a3361e2019-10-01 09:38:30 -07003483 index = curves.getVolumeIndex(deviceTypes);
3484 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003485 return NO_ERROR;
3486}
3487
3488status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3489 int &index)
3490{
3491 index = getVolumeCurves(attr).getVolumeIndexMin();
3492 return NO_ERROR;
3493}
3494
3495status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3496 int &index)
3497{
3498 index = getVolumeCurves(attr).getVolumeIndexMax();
3499 return NO_ERROR;
3500}
3501
Eric Laurent36829f92017-04-07 19:04:42 -07003502audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003503{
3504 // select one output among several suitable for global effects.
3505 // The priority is as follows:
3506 // 1: An offloaded output. If the effect ends up not being offloadable,
3507 // AudioFlinger will invalidate the track and the offloaded output
3508 // will be closed causing the effect to be moved to a PCM output.
3509 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003510 // 3: The primary output
3511 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003512
François Gaffiec005e562018-11-06 15:04:49 +01003513 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3514 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003515 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003516
Eric Laurent36829f92017-04-07 19:04:42 -07003517 if (outputs.size() == 0) {
3518 return AUDIO_IO_HANDLE_NONE;
3519 }
Eric Laurente552edb2014-03-10 17:42:56 -07003520
Eric Laurent36829f92017-04-07 19:04:42 -07003521 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3522 bool activeOnly = true;
3523
3524 while (output == AUDIO_IO_HANDLE_NONE) {
3525 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3526 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3527 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3528
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003529 for (audio_io_handle_t output : outputs) {
3530 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003531 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003532 continue;
3533 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003534 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3535 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003536 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003537 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003538 }
3539 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003540 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003541 }
3542 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003543 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003544 }
3545 }
3546 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3547 output = outputOffloaded;
3548 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3549 output = outputDeepBuffer;
3550 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3551 output = outputPrimary;
3552 } else {
3553 output = outputs[0];
3554 }
3555 activeOnly = false;
3556 }
3557
3558 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003559 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3560 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003561 mMusicEffectOutput = output;
3562 }
3563
3564 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003565 return output;
3566}
3567
Eric Laurent36829f92017-04-07 19:04:42 -07003568audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3569{
3570 return selectOutputForMusicEffects();
3571}
3572
Eric Laurente0720872014-03-11 09:30:41 -07003573status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003574 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003575 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003576 int session,
3577 int id)
3578{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003579 if (session != AUDIO_SESSION_DEVICE) {
3580 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003581 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003582 index = mInputs.indexOfKey(io);
3583 if (index < 0) {
3584 ALOGW("registerEffect() unknown io %d", io);
3585 return INVALID_OPERATION;
3586 }
Eric Laurente552edb2014-03-10 17:42:56 -07003587 }
3588 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003589 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3590 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3591 || strategy == PRODUCT_STRATEGY_NONE));
3592 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003593}
3594
Eric Laurentc241b0d2018-11-28 09:08:49 -08003595status_t AudioPolicyManager::unregisterEffect(int id)
3596{
3597 if (mEffects.getEffect(id) == nullptr) {
3598 return INVALID_OPERATION;
3599 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003600 if (mEffects.isEffectEnabled(id)) {
3601 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3602 setEffectEnabled(id, false);
3603 }
3604 return mEffects.unregisterEffect(id);
3605}
3606
3607status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3608{
3609 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3610 if (effect == nullptr) {
3611 return INVALID_OPERATION;
3612 }
3613
3614 status_t status = mEffects.setEffectEnabled(id, enabled);
3615 if (status == NO_ERROR) {
3616 mInputs.trackEffectEnabled(effect, enabled);
3617 }
3618 return status;
3619}
3620
Eric Laurent6c796322019-04-09 14:13:17 -07003621
3622status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3623{
3624 mEffects.moveEffects(ids, io);
3625 return NO_ERROR;
3626}
3627
Eric Laurentc75307b2015-03-17 15:29:32 -07003628bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3629{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003630 auto vs = toVolumeSource(stream, false);
3631 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003632}
3633
3634bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3635{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003636 auto vs = toVolumeSource(stream, false);
3637 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003638}
3639
Eric Laurente0720872014-03-11 09:30:41 -07003640bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003641{
3642 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003643 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003644 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003645 return true;
3646 }
3647 }
3648 return false;
3649}
3650
Eric Laurent275e8e92014-11-30 15:14:47 -08003651// Register a list of custom mixes with their attributes and format.
3652// When a mix is registered, corresponding input and output profiles are
3653// added to the remote submix hw module. The profile contains only the
3654// parameters (sampling rate, format...) specified by the mix.
3655// The corresponding input remote submix device is also connected.
3656//
3657// When a remote submix device is connected, the address is checked to select the
3658// appropriate profile and the corresponding input or output stream is opened.
3659//
3660// When capture starts, getInputForAttr() will:
3661// - 1 look for a mix matching the address passed in attribtutes tags if any
3662// - 2 if none found, getDeviceForInputSource() will:
3663// - 2.1 look for a mix matching the attributes source
3664// - 2.2 if none found, default to device selection by policy rules
3665// At this time, the corresponding output remote submix device is also connected
3666// and active playback use cases can be transferred to this mix if needed when reconnecting
3667// after AudioTracks are invalidated
3668//
3669// When playback starts, getOutputForAttr() will:
3670// - 1 look for a mix matching the address passed in attribtutes tags if any
3671// - 2 if none found, look for a mix matching the attributes usage
3672// - 3 if none found, default to device and output selection by policy rules.
3673
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003674status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003675{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003676 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3677 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003678 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003679 sp<HwModule> rSubmixModule;
3680 // examine each mix's route type
3681 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003682 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003683 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3684 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3685 ALOGE("Unsupported Policy Mix %zu of %zu: "
3686 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3687 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003688 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003689 break;
3690 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003691 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3692 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003693 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003694 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3695 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003696 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003697 rSubmixModule = mHwModules.getModuleFromName(
3698 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3699 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003700 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003701 i);
3702 res = INVALID_OPERATION;
3703 break;
3704 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003705 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003706
Eric Laurent97ac8712018-07-27 18:59:02 -07003707 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003708 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003709 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003710 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003711 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3712 } else {
3713 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3714 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003715 }
François Gaffie036e1e92015-03-19 10:16:24 +01003716
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003717 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003718 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003719 res = INVALID_OPERATION;
3720 break;
3721 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003722 audio_config_t outputConfig = mix.mFormat;
3723 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003724 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3725 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003726 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3727 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003728 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003729 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3730 audio_is_linear_pcm(outputConfig.format)
3731 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003732 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003733 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3734 audio_is_linear_pcm(inputConfig.format)
3735 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003736
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003737 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003738 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003739 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003740 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003741 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003742 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003743 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003744 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3745 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003746 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003747 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003748 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003749
3750 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3751 mix.mDeviceType, mix.mDeviceAddress,
3752 String8(), AUDIO_FORMAT_DEFAULT);
3753 if (device == nullptr) {
3754 res = INVALID_OPERATION;
3755 break;
3756 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003757
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003758 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003759 // First try to find an already opened output supporting the device
3760 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003761 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003762
Eric Laurentc529cf62020-04-17 18:19:10 -07003763 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003764 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003765 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003766 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003767 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003768 } else {
3769 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003770 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003771 }
3772 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003773 // If no output found, try to find a direct output profile supporting the device
3774 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3775 sp<HwModule> module = mHwModules[i];
3776 for (size_t j = 0;
3777 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3778 j++) {
3779 sp<IOProfile> profile = module->getOutputProfiles()[j];
3780 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3781 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3782 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003783 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003784 res = INVALID_OPERATION;
3785 } else {
3786 foundOutput = true;
3787 }
3788 }
3789 }
3790 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003791 if (res != NO_ERROR) {
3792 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003793 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003794 res = INVALID_OPERATION;
3795 break;
3796 } else if (!foundOutput) {
3797 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003798 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003799 res = INVALID_OPERATION;
3800 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003801 } else {
3802 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003803 }
Eric Laurentc722f302014-12-10 11:21:49 -08003804 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003805 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003806 if (res != NO_ERROR) {
3807 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003808 } else if (checkOutputs) {
3809 checkForDeviceAndOutputChanges();
3810 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003811 }
3812 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003813}
3814
3815status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3816{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003817 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003818 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003819 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003820 sp<HwModule> rSubmixModule;
3821 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003822 for (const auto& mix : mixes) {
3823 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003824
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003825 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003826 rSubmixModule = mHwModules.getModuleFromName(
3827 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3828 if (rSubmixModule == 0) {
3829 res = INVALID_OPERATION;
3830 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003831 }
3832 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003833
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003834 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003835
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003836 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003837 res = INVALID_OPERATION;
3838 continue;
3839 }
3840
Kevin Rocard04ed0462019-05-02 17:53:24 -07003841 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003842 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003843 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3844 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003845 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003846 AUDIO_FORMAT_DEFAULT);
3847 if (res != OK) {
3848 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003849 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003850 }
3851 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003852 }
jiabin5740f082019-08-19 15:08:30 -07003853 rSubmixModule->removeOutputProfile(address.c_str());
3854 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003855
Kevin Rocard153f92d2018-12-18 18:33:28 -08003856 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003857 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003858 res = INVALID_OPERATION;
3859 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003860 } else {
3861 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003862 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003863 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003864 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003865 if (res == NO_ERROR && checkOutputs) {
3866 checkForDeviceAndOutputChanges();
3867 updateCallAndOutputRouting();
3868 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003869 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003870}
3871
Marvin Raminbdefaf02023-11-01 09:10:32 +01003872status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
3873 if (!audio_flags::audio_mix_test_api()) {
3874 return INVALID_OPERATION;
3875 }
3876
3877 _aidl_return.clear();
3878 _aidl_return.reserve(mPolicyMixes.size());
3879 for (const auto &policyMix: mPolicyMixes) {
3880 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
3881 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
3882 policyMix->mCbFlags);
3883 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
3884 }
3885
3886 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return->size());
3887 return OK;
3888}
3889
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003890status_t AudioPolicyManager::updatePolicyMix(
3891 const AudioMix& mix,
3892 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3893 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3894 if (res == NO_ERROR) {
3895 checkForDeviceAndOutputChanges();
3896 updateCallAndOutputRouting();
3897 }
3898 return res;
3899}
3900
Mikhail Naganov100f0122018-11-29 11:22:16 -08003901void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3902{
3903 size_t i = 0;
3904 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3905 for (const auto& fmt : mManualSurroundFormats) {
3906 if (i++ != 0) dst->append(", ");
3907 std::string sfmt;
3908 FormatConverter::toString(fmt, sfmt);
3909 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3910 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3911 }
3912}
3913
Eric Laurentc529cf62020-04-17 18:19:10 -07003914// Returns true if all devices types match the predicate and are supported by one HW module
3915bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003916 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003917 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003918 const char *context,
3919 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003920 for (size_t i = 0; i < devices.size(); i++) {
3921 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003922 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003923 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003924 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003925 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003926 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003927 return false;
3928 }
3929 }
3930 return true;
3931}
3932
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003933void AudioPolicyManager::changeOutputDevicesMuteState(
3934 const AudioDeviceTypeAddrVector& devices) {
3935 ALOGVV("%s() num devices %zu", __func__, devices.size());
3936
3937 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3938 getSoftwareOutputsForDevices(devices);
3939
3940 for (size_t i = 0; i < outputs.size(); i++) {
3941 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3942 DeviceVector prevDevices = outputDesc->devices();
3943 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3944 }
3945}
3946
3947std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3948 const AudioDeviceTypeAddrVector& devices) const
3949{
3950 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3951 DeviceVector deviceDescriptors;
3952 for (size_t j = 0; j < devices.size(); j++) {
3953 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3954 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3955 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3956 ALOGE("%s: device type %#x address %s not supported or not an output device",
3957 __func__, devices[j].mType, devices[j].getAddress());
3958 continue;
3959 }
3960 deviceDescriptors.add(desc);
3961 }
3962 for (size_t i = 0; i < mOutputs.size(); i++) {
3963 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3964 continue;
3965 }
3966 outputs.push_back(mOutputs.valueAt(i));
3967 }
3968 return outputs;
3969}
3970
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003971status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003972 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003973 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003974 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3975 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003976 }
3977 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003978 if (res != NO_ERROR) {
3979 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3980 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003981 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003982
3983 checkForDeviceAndOutputChanges();
3984 updateCallAndOutputRouting();
3985
3986 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003987}
3988
3989status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3990 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003991 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3992 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003993 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003994 __FUNCTION__, uid);
3995 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003996 }
3997
Eric Laurentc529cf62020-04-17 18:19:10 -07003998 checkForDeviceAndOutputChanges();
3999 updateCallAndOutputRouting();
4000
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004001 return res;
4002}
4003
Eric Laurent2517af32020-11-25 15:31:27 +01004004
jiabin0a488932020-08-07 17:32:40 -07004005status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4006 device_role_t role,
4007 const AudioDeviceTypeAddrVector &devices) {
4008 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4009 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004010
Eric Laurentc529cf62020-04-17 18:19:10 -07004011 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004012 return BAD_VALUE;
4013 }
jiabin0a488932020-08-07 17:32:40 -07004014 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004015 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004016 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4017 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004018 return status;
4019 }
4020
4021 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004022
4023 bool forceVolumeReeval = false;
4024 // FIXME: workaround for truncated touch sounds
4025 // to be removed when the problem is handled by system UI
4026 uint32_t delayMs = 0;
4027 if (strategy == mCommunnicationStrategy) {
4028 forceVolumeReeval = true;
4029 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4030 updateInputRouting();
4031 }
4032 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004033
4034 return NO_ERROR;
4035}
4036
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004037void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4038 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004039{
4040 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004041 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004042 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004043 // Only apply special touch sound delay once
4044 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004045 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004046 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004047 for (size_t i = 0; i < mOutputs.size(); i++) {
4048 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4049 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004050 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4051 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004052 // As done in setDeviceConnectionState, we could also fix default device issue by
4053 // preventing the force re-routing in case of default dev that distinguishes on address.
4054 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004055 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004056 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4057 // If the device is using preferred mixer attributes, the output need to reopen
4058 // with default configuration when the new selected devices are different from
4059 // current routing devices.
4060 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4061 continue;
4062 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304063
4064 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4065 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004066 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004067 // Only apply special touch sound delay once
4068 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004069 }
4070 if (forceVolumeReeval && !newDevices.isEmpty()) {
4071 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4072 }
4073 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004074 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004075 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004076}
4077
Eric Laurent2517af32020-11-25 15:31:27 +01004078void AudioPolicyManager::updateInputRouting() {
4079 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304080 // Skip for hotword recording as the input device switch
4081 // is handled within sound trigger HAL
4082 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4083 continue;
4084 }
Eric Laurent2517af32020-11-25 15:31:27 +01004085 auto newDevice = getNewInputDevice(activeDesc);
4086 // Force new input selection if the new device can not be reached via current input
4087 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4088 setInputDevice(activeDesc->mIoHandle, newDevice);
4089 } else {
4090 closeInput(activeDesc->mIoHandle);
4091 }
4092 }
4093}
4094
Paul Wang5d7cdb52022-11-22 09:45:06 +00004095status_t
4096AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4097 device_role_t role,
4098 const AudioDeviceTypeAddrVector &devices) {
4099 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4100 dumpAudioDeviceTypeAddrVector(devices).c_str());
4101
Eric Laurent78fedbf2023-03-09 14:40:44 +01004102 if (!areAllDevicesSupported(
4103 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004104 return BAD_VALUE;
4105 }
4106 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4107 if (status != NO_ERROR) {
4108 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4109 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4110 return status;
4111 }
4112
4113 checkForDeviceAndOutputChanges();
4114
4115 bool forceVolumeReeval = false;
4116 // TODO(b/263479999): workaround for truncated touch sounds
4117 // to be removed when the problem is handled by system UI
4118 uint32_t delayMs = 0;
4119 if (strategy == mCommunnicationStrategy) {
4120 forceVolumeReeval = true;
4121 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4122 updateInputRouting();
4123 }
4124 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4125
4126 return NO_ERROR;
4127}
4128
4129status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4130 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004131{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004132 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004133
Paul Wang5d7cdb52022-11-22 09:45:06 +00004134 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004135 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004136 ALOGW_IF(status != NAME_NOT_FOUND,
4137 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004138 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004139 return status;
4140 }
4141
4142 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004143
4144 bool forceVolumeReeval = false;
4145 // FIXME: workaround for truncated touch sounds
4146 // to be removed when the problem is handled by system UI
4147 uint32_t delayMs = 0;
4148 if (strategy == mCommunnicationStrategy) {
4149 forceVolumeReeval = true;
4150 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4151 updateInputRouting();
4152 }
4153 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004154
4155 return NO_ERROR;
4156}
4157
jiabin0a488932020-08-07 17:32:40 -07004158status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4159 device_role_t role,
4160 AudioDeviceTypeAddrVector &devices) {
4161 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004162}
4163
Jiabin Huang3b98d322020-09-03 17:54:16 +00004164status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4165 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4166 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4167 dumpAudioDeviceTypeAddrVector(devices).c_str());
4168
Mikhail Naganov55773032020-10-01 15:08:13 -07004169 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004170 return BAD_VALUE;
4171 }
4172 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4173 ALOGW_IF(status != NO_ERROR,
4174 "Engine could not set preferred devices %s for audio source %d role %d",
4175 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4176
4177 return status;
4178}
4179
4180status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4181 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4182 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4183 dumpAudioDeviceTypeAddrVector(devices).c_str());
4184
Mikhail Naganov55773032020-10-01 15:08:13 -07004185 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004186 return BAD_VALUE;
4187 }
4188 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4189 ALOGW_IF(status != NO_ERROR,
4190 "Engine could not add preferred devices %s for audio source %d role %d",
4191 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4192
Eric Laurent2517af32020-11-25 15:31:27 +01004193 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004194 return status;
4195}
4196
4197status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4198 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4199{
4200 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4201 dumpAudioDeviceTypeAddrVector(devices).c_str());
4202
Eric Laurent78fedbf2023-03-09 14:40:44 +01004203 if (!areAllDevicesSupported(
4204 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004205 return BAD_VALUE;
4206 }
4207
4208 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4209 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004210 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004211 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004212 if (status == NO_ERROR) {
4213 updateInputRouting();
4214 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004215 return status;
4216}
4217
4218status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4219 device_role_t role) {
4220 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4221
4222 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004223 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004224 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004225 if (status == NO_ERROR) {
4226 updateInputRouting();
4227 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004228 return status;
4229}
4230
4231status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4232 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4233 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4234}
4235
Oscar Azucena90e77632019-11-27 17:12:28 -08004236status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004237 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004238 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004239 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4240 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004241 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004242 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4243 if (status != NO_ERROR) {
4244 ALOGE("%s() could not set device affinity for userId %d",
4245 __FUNCTION__, userId);
4246 return status;
4247 }
4248
4249 // reevaluate outputs for all devices
4250 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004251 changeOutputDevicesMuteState(devices);
4252 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4253 true /* skipDelays */);
4254 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004255
4256 return NO_ERROR;
4257}
4258
4259status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004260 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004261 AudioDeviceTypeAddrVector devices;
4262 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004263 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4264 if (status != NO_ERROR) {
4265 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4266 __FUNCTION__, userId);
4267 return status;
4268 }
4269
4270 // reevaluate outputs for all devices
4271 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004272 changeOutputDevicesMuteState(devices);
4273 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4274 true /* skipDelays */);
4275 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004276
4277 return NO_ERROR;
4278}
4279
Andy Hungc29d82b2018-10-05 12:23:17 -07004280void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004281{
Andy Hungc29d82b2018-10-05 12:23:17 -07004282 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004283 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004284 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004285 std::string stateLiteral;
4286 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004287 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004288 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4289 "communications", "media", "record", "dock", "system",
4290 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4291 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4292 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004293 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4294 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4295 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4296 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4297 dst->append(" (MANUAL: ");
4298 dumpManualSurroundFormats(dst);
4299 dst->append(")");
4300 }
4301 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004302 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004303 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4304 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004305 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004306 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004307
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004308 dst->append("\n");
4309 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4310 dst->append("\n");
4311 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004312 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004313 mOutputs.dump(dst);
4314 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004315 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004316 mAudioPatches.dump(dst);
4317 mPolicyMixes.dump(dst);
4318 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004319
Kevin Rocardb99cc752019-03-21 20:52:24 -07004320 dst->appendFormat(" AllowedCapturePolicies:\n");
4321 for (auto& policy : mAllowedCapturePolicies) {
4322 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4323 }
4324
jiabina84c3d32022-12-02 18:59:55 +00004325 dst->appendFormat(" Preferred mixer audio configuration:\n");
4326 for (const auto it : mPreferredMixerAttrInfos) {
4327 dst->appendFormat(" - device port id: %d\n", it.first);
4328 for (const auto preferredMixerInfoIt : it.second) {
4329 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4330 preferredMixerInfoIt.second->dump(dst);
4331 }
4332 }
4333
François Gaffiec005e562018-11-06 15:04:49 +01004334 dst->appendFormat("\nPolicy Engine dump:\n");
4335 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004336}
4337
4338status_t AudioPolicyManager::dump(int fd)
4339{
4340 String8 result;
4341 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004342 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004343 return NO_ERROR;
4344}
4345
Kevin Rocardb99cc752019-03-21 20:52:24 -07004346status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4347{
4348 mAllowedCapturePolicies[uid] = capturePolicy;
4349 return NO_ERROR;
4350}
4351
Eric Laurente552edb2014-03-10 17:42:56 -07004352// This function checks for the parameters which can be offloaded.
4353// This can be enhanced depending on the capability of the DSP and policy
4354// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004355audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004356{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004357 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004358 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004359 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004360 offloadInfo.format,
4361 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4362 offloadInfo.has_video);
4363
jiabin2b9d5a12021-12-10 01:06:29 +00004364 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004365 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004366 }
4367
4368 // See if there is a profile to support this.
4369 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004370 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004371 offloadInfo.sample_rate,
4372 offloadInfo.format,
4373 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004374 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4375 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004376 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4377 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4378 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004379 if (profile == nullptr) {
4380 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4381 }
4382 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4383 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4384 }
4385 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004386}
4387
Michael Chana94fbb22018-04-24 14:31:19 +10004388bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4389 const audio_attributes_t& attributes) {
4390 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004391 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004392 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4393 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004394 config.sample_rate,
4395 config.format,
4396 config.channel_mask,
4397 output_flags,
4398 true /* directOnly */);
4399 ALOGV("%s() profile %sfound with name: %s, "
4400 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4401 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004402 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004403 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004404
4405 // also try the MSD module if compatible profile not found
4406 if (profile == nullptr) {
4407 profile = getMsdProfileForOutput(outputDevices,
4408 config.sample_rate,
4409 config.format,
4410 config.channel_mask,
4411 output_flags,
4412 true /* directOnly */);
4413 ALOGV("%s() MSD profile %sfound with name: %s, "
4414 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4415 __FUNCTION__, profile != 0 ? "" : "NOT ",
4416 (profile != 0 ? profile->getTagName().c_str() : "null"),
4417 config.sample_rate, config.format, config.channel_mask, output_flags);
4418 }
4419 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004420}
4421
jiabin2b9d5a12021-12-10 01:06:29 +00004422bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4423 bool durationIgnored) {
4424 if (mMasterMono) {
4425 return false; // no offloading if mono is set.
4426 }
4427
4428 // Check if offload has been disabled
4429 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4430 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4431 return false;
4432 }
4433
4434 // Check if stream type is music, then only allow offload as of now.
4435 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4436 {
4437 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4438 return false;
4439 }
4440
4441 //TODO: enable audio offloading with video when ready
4442 const bool allowOffloadWithVideo =
4443 property_get_bool("audio.offload.video", false /* default_value */);
4444 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4445 ALOGV("%s: has_video == true, returning false", __func__);
4446 return false;
4447 }
4448
4449 //If duration is less than minimum value defined in property, return false
4450 const int min_duration_secs = property_get_int32(
4451 "audio.offload.min.duration.secs", -1 /* default_value */);
4452 if (!durationIgnored) {
4453 if (min_duration_secs >= 0) {
4454 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4455 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4456 __func__, min_duration_secs);
4457 return false;
4458 }
4459 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4460 ALOGV("%s: Offload denied by duration < default min(=%u)",
4461 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4462 return false;
4463 }
4464 }
4465
4466 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4467 // creating an offloaded track and tearing it down immediately after start when audioflinger
4468 // detects there is an active non offloadable effect.
4469 // FIXME: We should check the audio session here but we do not have it in this context.
4470 // This may prevent offloading in rare situations where effects are left active by apps
4471 // in the background.
4472 if (mEffects.isNonOffloadableEffectEnabled()) {
4473 return false;
4474 }
4475
4476 return true;
4477}
4478
4479audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4480 const audio_config_t *config) {
4481 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4482 offloadInfo.format = config->format;
4483 offloadInfo.sample_rate = config->sample_rate;
4484 offloadInfo.channel_mask = config->channel_mask;
4485 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4486 offloadInfo.has_video = false;
4487 offloadInfo.is_streaming = false;
4488 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4489
4490 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4491 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4492 audio_flags_to_audio_output_flags(attr->flags, &flags);
4493 // only retain flags that will drive compressed offload or passthrough
4494 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4495 if (offloadPossible) {
4496 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4497 }
4498 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4499
Dorin Drimusfae3c642022-03-17 18:36:30 +01004500 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004501 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004502 DeviceVector outputDevices = engineOutputDevices;
4503 // the MSD module checks for different conditions and output devices
4504 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4505 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4506 continue;
4507 }
4508 outputDevices = getMsdAudioOutDevices();
4509 }
jiabin2b9d5a12021-12-10 01:06:29 +00004510 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004511 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004512 config->sample_rate, nullptr /*updatedSamplingRate*/,
4513 config->format, nullptr /*updatedFormat*/,
4514 config->channel_mask, nullptr /*updatedChannelMask*/,
4515 flags)) {
4516 continue;
4517 }
4518 // reject profiles not corresponding to a device currently available
4519 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4520 continue;
4521 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004522 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4523 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004524 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004525 != AUDIO_DIRECT_NOT_SUPPORTED) {
4526 // Already reports offload gapless supported. No need to report offload support.
4527 continue;
4528 }
4529 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4530 != AUDIO_OUTPUT_FLAG_NONE) {
4531 // If offload gapless is reported, no need to report offload support.
4532 directMode = (audio_direct_mode_t) ((directMode &
4533 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4534 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4535 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004536 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004537 }
4538 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004539 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004540 }
4541 }
4542 }
4543 return directMode;
4544}
4545
Dorin Drimusf2196d82022-01-03 12:11:18 +01004546status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4547 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004548 if (mEffects.isNonOffloadableEffectEnabled()) {
4549 return OK;
4550 }
jiabinf1c73972022-04-14 16:28:52 -07004551 DeviceVector devices;
4552 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004553 if (status != OK) {
4554 return status;
4555 }
4556 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4557 if (devices.empty()) {
4558 return OK; // no output devices for the attributes
4559 }
jiabinf1c73972022-04-14 16:28:52 -07004560 return getProfilesForDevices(devices, audioProfilesVector,
4561 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004562}
4563
jiabina84c3d32022-12-02 18:59:55 +00004564status_t AudioPolicyManager::getSupportedMixerAttributes(
4565 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4566 ALOGV("%s, portId=%d", __func__, portId);
4567 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4568 if (deviceDescriptor == nullptr) {
4569 ALOGE("%s the requested device is currently unavailable", __func__);
4570 return BAD_VALUE;
4571 }
jiabin96daffc2023-05-11 17:51:55 +00004572 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4573 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4574 deviceDescriptor->type());
4575 return BAD_VALUE;
4576 }
jiabina84c3d32022-12-02 18:59:55 +00004577 for (const auto& hwModule : mHwModules) {
4578 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4579 if (curProfile->supportsDevice(deviceDescriptor)) {
4580 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4581 }
4582 }
4583 }
4584 return NO_ERROR;
4585}
4586
4587status_t AudioPolicyManager::setPreferredMixerAttributes(
4588 const audio_attributes_t *attr,
4589 audio_port_handle_t portId,
4590 uid_t uid,
4591 const audio_mixer_attributes_t *mixerAttributes) {
4592 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4593 "mixerBehavior=%d}, uid=%d, portId=%u",
4594 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4595 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4596 mixerAttributes->mixer_behavior, uid, portId);
4597 if (attr->usage != AUDIO_USAGE_MEDIA) {
4598 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4599 return BAD_VALUE;
4600 }
4601 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4602 if (deviceDescriptor == nullptr) {
4603 ALOGE("%s the requested device is currently unavailable", __func__);
4604 return BAD_VALUE;
4605 }
4606 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4607 ALOGE("%s(%d), type=%d, is not a usb output device",
4608 __func__, portId, deviceDescriptor->type());
4609 return BAD_VALUE;
4610 }
4611
4612 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4613 audio_flags_to_audio_output_flags(attr->flags, &flags);
4614 flags = (audio_output_flags_t) (flags |
4615 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4616 sp<IOProfile> profile = nullptr;
4617 DeviceVector devices(deviceDescriptor);
4618 for (const auto& hwModule : mHwModules) {
4619 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4620 if (curProfile->hasDynamicAudioProfile()
4621 && curProfile->isCompatibleProfile(devices,
4622 mixerAttributes->config.sample_rate,
4623 nullptr /*updatedSamplingRate*/,
4624 mixerAttributes->config.format,
4625 nullptr /*updatedFormat*/,
4626 mixerAttributes->config.channel_mask,
4627 nullptr /*updatedChannelMask*/,
4628 flags,
4629 false /*exactMatchRequiredForInputFlags*/)) {
4630 profile = curProfile;
4631 break;
4632 }
4633 }
4634 }
4635 if (profile == nullptr) {
4636 ALOGE("%s, there is no compatible profile found", __func__);
4637 return BAD_VALUE;
4638 }
4639
4640 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4641 sp<PreferredMixerAttributesInfo>::make(
4642 uid, portId, profile, flags, *mixerAttributes);
4643 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4644 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4645
4646 // If 1) there is any client from the preferred mixer configuration owner that is currently
4647 // active and matches the strategy and 2) current output is on the preferred device and the
4648 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4649 // configuration.
4650 std::vector<audio_io_handle_t> outputsToReopen;
4651 for (size_t i = 0; i < mOutputs.size(); i++) {
4652 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004653 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4654 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4655 output->mUsePreferredMixerAttributes = true;
4656 } else {
4657 for (const auto &client: output->getActiveClients()) {
4658 if (client->uid() == uid && client->strategy() == strategy) {
4659 client->setIsInvalid();
4660 outputsToReopen.push_back(output->mIoHandle);
4661 }
jiabina84c3d32022-12-02 18:59:55 +00004662 }
4663 }
4664 }
4665 }
4666 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4667 config.sample_rate = mixerAttributes->config.sample_rate;
4668 config.channel_mask = mixerAttributes->config.channel_mask;
4669 config.format = mixerAttributes->config.format;
4670 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004671 sp<SwAudioOutputDescriptor> desc =
4672 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4673 if (desc == nullptr) {
4674 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4675 continue;
4676 }
4677 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004678 }
4679
4680 return NO_ERROR;
4681}
4682
4683sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004684 audio_port_handle_t devicePortId,
4685 product_strategy_t strategy,
4686 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004687 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4688 if (it == mPreferredMixerAttrInfos.end()) {
4689 return nullptr;
4690 }
jiabind9a58d32023-06-01 17:57:30 +00004691 if (activeBitPerfectPreferred) {
4692 for (auto [strategy, info] : it->second) {
4693 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4694 && info->getActiveClientCount() != 0) {
4695 return info;
4696 }
4697 }
jiabina84c3d32022-12-02 18:59:55 +00004698 }
jiabind9a58d32023-06-01 17:57:30 +00004699 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4700 return strategyMatchedMixerAttrInfoIt == it->second.end()
4701 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004702}
4703
4704status_t AudioPolicyManager::getPreferredMixerAttributes(
4705 const audio_attributes_t *attr,
4706 audio_port_handle_t portId,
4707 audio_mixer_attributes_t* mixerAttributes) {
4708 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4709 portId, mEngine->getProductStrategyForAttributes(*attr));
4710 if (info == nullptr) {
4711 return NAME_NOT_FOUND;
4712 }
4713 *mixerAttributes = info->getMixerAttributes();
4714 return NO_ERROR;
4715}
4716
4717status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4718 audio_port_handle_t portId,
4719 uid_t uid) {
4720 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4721 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4722 if (preferredMixerAttrInfo == nullptr) {
4723 return NAME_NOT_FOUND;
4724 }
4725 if (preferredMixerAttrInfo->getUid() != uid) {
4726 ALOGE("%s, requested uid=%d, owned uid=%d",
4727 __func__, uid, preferredMixerAttrInfo->getUid());
4728 return PERMISSION_DENIED;
4729 }
4730 mPreferredMixerAttrInfos[portId].erase(strategy);
4731 if (mPreferredMixerAttrInfos[portId].empty()) {
4732 mPreferredMixerAttrInfos.erase(portId);
4733 }
4734
4735 // Reconfig existing output
4736 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4737 for (size_t i = 0; i < mOutputs.size(); i++) {
4738 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4739 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4740 }
4741 }
4742 for (const auto output : potentialOutputsToReopen) {
4743 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4744 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4745 preferredMixerAttrInfo->getFlags())) {
4746 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4747 }
4748 }
4749 return NO_ERROR;
4750}
4751
Eric Laurent6a94d692014-05-20 11:18:06 -07004752status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4753 audio_port_type_t type,
4754 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004755 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004756 unsigned int *generation)
4757{
jiabin19cdba52020-11-24 11:28:58 -08004758 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4759 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004760 return BAD_VALUE;
4761 }
4762 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004763 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004764 *num_ports = 0;
4765 }
4766
4767 size_t portsWritten = 0;
4768 size_t portsMax = *num_ports;
4769 *num_ports = 0;
4770 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004771 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4772 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004773 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004774 for (const auto& dev : mAvailableOutputDevices) {
4775 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004776 continue;
4777 }
4778 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004779 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004780 }
4781 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004782 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004783 }
4784 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004785 for (const auto& dev : mAvailableInputDevices) {
4786 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004787 continue;
4788 }
4789 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004790 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004791 }
4792 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004793 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004794 }
4795 }
4796 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4797 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4798 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4799 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4800 }
4801 *num_ports += mInputs.size();
4802 }
4803 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004804 size_t numOutputs = 0;
4805 for (size_t i = 0; i < mOutputs.size(); i++) {
4806 if (!mOutputs[i]->isDuplicated()) {
4807 numOutputs++;
4808 if (portsWritten < portsMax) {
4809 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4810 }
4811 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004812 }
Eric Laurent84c70242014-06-23 08:46:27 -07004813 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 }
4815 }
jiabina84c3d32022-12-02 18:59:55 +00004816
Eric Laurent6a94d692014-05-20 11:18:06 -07004817 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004818 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004819 return NO_ERROR;
4820}
4821
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004822status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4823 std::vector<media::AudioPortFw>* _aidl_return) {
4824 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4825 audio_port_v7 port;
4826 dev->toAudioPort(&port);
4827 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4828 _aidl_return->push_back(std::move(aidlPort));
4829 return OK;
4830 };
4831
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004832 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004833 for (const auto& dev : module->getDeclaredDevices()) {
4834 if (role == media::AudioPortRole::NONE ||
4835 ((role == media::AudioPortRole::SOURCE)
4836 == audio_is_input_device(dev->type()))) {
4837 RETURN_STATUS_IF_ERROR(pushPort(dev));
4838 }
4839 }
4840 }
4841 return OK;
4842}
4843
jiabin19cdba52020-11-24 11:28:58 -08004844status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004845{
Eric Laurent99fcae42018-05-17 16:59:18 -07004846 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4847 return BAD_VALUE;
4848 }
4849 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4850 if (dev != 0) {
4851 dev->toAudioPort(port);
4852 return NO_ERROR;
4853 }
4854 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4855 if (dev != 0) {
4856 dev->toAudioPort(port);
4857 return NO_ERROR;
4858 }
4859 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4860 if (out != 0) {
4861 out->toAudioPort(port);
4862 return NO_ERROR;
4863 }
4864 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4865 if (in != 0) {
4866 in->toAudioPort(port);
4867 return NO_ERROR;
4868 }
4869 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004870}
4871
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004872status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4873 audio_patch_handle_t *handle,
4874 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004875{
François Gaffieafd4cea2019-11-18 15:50:22 +01004876 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004877 if (handle == NULL || patch == NULL) {
4878 return BAD_VALUE;
4879 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004880 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004881 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004882 return BAD_VALUE;
4883 }
4884 // only one source per audio patch supported for now
4885 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004886 return INVALID_OPERATION;
4887 }
Eric Laurent874c42872014-08-08 15:13:39 -07004888 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004889 return INVALID_OPERATION;
4890 }
Eric Laurent874c42872014-08-08 15:13:39 -07004891 for (size_t i = 0; i < patch->num_sinks; i++) {
4892 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4893 return INVALID_OPERATION;
4894 }
4895 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004896
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004897 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4898 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4899 if (srcDevice == nullptr || sinkDevice == nullptr) {
4900 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4901 return BAD_VALUE;
4902 }
4903 ALOGV("%s between source %s and sink %s", __func__,
4904 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4905 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4906 // Default attributes, default volume priority, not to infer with non raw audio patches.
4907 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4908 const struct audio_port_config *source = &patch->sources[0];
4909 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004910 new SourceClientDescriptor(
4911 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4912 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4913 true);
4914 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004915
4916 status_t status =
4917 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4918
4919 if (status != NO_ERROR) {
4920 return INVALID_OPERATION;
4921 }
4922 mAudioSources.add(portId, sourceDesc);
4923 return NO_ERROR;
4924}
4925
4926status_t AudioPolicyManager::connectAudioSourceToSink(
4927 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4928 const struct audio_patch *patch,
4929 audio_patch_handle_t &handle,
4930 uid_t uid, uint32_t delayMs)
4931{
4932 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4933 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4934 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4935 return INVALID_OPERATION;
4936 }
4937 sourceDesc->connect(handle, sinkDevice);
4938 if (isMsdPatch(handle)) {
4939 return NO_ERROR;
4940 }
4941 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4942 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4943 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4944 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4945 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4946 goto FailurePatchAdded;
4947 }
4948 status = swOutput->start();
4949 if (status != NO_ERROR) {
4950 goto FailureSourceAdded;
4951 }
4952 swOutput->addClient(sourceDesc);
4953 status = startSource(swOutput, sourceDesc, &delayMs);
4954 if (status != NO_ERROR) {
4955 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4956 goto FailureSourceActive;
4957 }
4958 if (delayMs != 0) {
4959 usleep(delayMs * 1000);
4960 }
4961 return NO_ERROR;
4962
4963FailureSourceActive:
4964 swOutput->stop();
4965 releaseOutput(sourceDesc->portId());
4966FailureSourceAdded:
4967 sourceDesc->setSwOutput(nullptr);
4968FailurePatchAdded:
4969 releaseAudioPatchInternal(handle);
4970 return INVALID_OPERATION;
4971}
4972
4973status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4974 audio_patch_handle_t *handle,
4975 uid_t uid, uint32_t delayMs,
4976 const sp<SourceClientDescriptor>& sourceDesc)
4977{
4978 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004979 sp<AudioPatch> patchDesc;
4980 ssize_t index = mAudioPatches.indexOfKey(*handle);
4981
François Gaffieafd4cea2019-11-18 15:50:22 +01004982 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4983 patch->sources[0].role,
4984 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004985#if LOG_NDEBUG == 0
4986 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004987 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4988 patch->sinks[i].role,
4989 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004990 }
4991#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004992
4993 if (index >= 0) {
4994 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004995 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4996 __func__, mUidCached, patchDesc->getUid(), uid);
4997 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004998 return INVALID_OPERATION;
4999 }
5000 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005001 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 }
5003
5004 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005005 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005006 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005007 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005008 return BAD_VALUE;
5009 }
Eric Laurent84c70242014-06-23 08:46:27 -07005010 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5011 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005012 if (patchDesc != 0) {
5013 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005014 ALOGV("%s source id differs for patch current id %d new id %d",
5015 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 return BAD_VALUE;
5017 }
5018 }
Eric Laurent874c42872014-08-08 15:13:39 -07005019 DeviceVector devices;
5020 for (size_t i = 0; i < patch->num_sinks; i++) {
5021 // Only support mix to devices connection
5022 // TODO add support for mix to mix connection
5023 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005024 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005025 return INVALID_OPERATION;
5026 }
5027 sp<DeviceDescriptor> devDesc =
5028 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5029 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005030 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005031 return BAD_VALUE;
5032 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005033
François Gaffie11d30102018-11-02 16:09:09 +01005034 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07005035 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01005036 NULL, // updatedSamplingRate
5037 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005038 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01005039 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005040 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01005041 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005042 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005043 return INVALID_OPERATION;
5044 }
5045 devices.add(devDesc);
5046 }
5047 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005048 return INVALID_OPERATION;
5049 }
Eric Laurent874c42872014-08-08 15:13:39 -07005050
Eric Laurent6a94d692014-05-20 11:18:06 -07005051 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005052 ALOGV("%s setting device %s on output %d",
5053 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305054 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005055 index = mAudioPatches.indexOfKey(*handle);
5056 if (index >= 0) {
5057 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005058 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005059 }
5060 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005061 patchDesc->setUid(uid);
5062 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005063 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005064 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005065 return INVALID_OPERATION;
5066 }
5067 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5068 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5069 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005070 // only one sink supported when connecting an input device to a mix
5071 if (patch->num_sinks > 1) {
5072 return INVALID_OPERATION;
5073 }
François Gaffie53615e22015-03-19 09:24:12 +01005074 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005075 if (inputDesc == NULL) {
5076 return BAD_VALUE;
5077 }
5078 if (patchDesc != 0) {
5079 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5080 return BAD_VALUE;
5081 }
5082 }
François Gaffie11d30102018-11-02 16:09:09 +01005083 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005084 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005085 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005086 return BAD_VALUE;
5087 }
5088
François Gaffie11d30102018-11-02 16:09:09 +01005089 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005090 patch->sinks[0].sample_rate,
5091 NULL, /*updatedSampleRate*/
5092 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005093 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005094 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005095 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005096 // FIXME for the parameter type,
5097 // and the NONE
5098 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005099 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005100 return INVALID_OPERATION;
5101 }
5102 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005103 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005104 device->toString().c_str(), inputDesc->mIoHandle);
5105 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005106 index = mAudioPatches.indexOfKey(*handle);
5107 if (index >= 0) {
5108 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005109 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005110 }
5111 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005112 patchDesc->setUid(uid);
5113 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005114 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005115 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005116 return INVALID_OPERATION;
5117 }
5118 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5119 // device to device connection
5120 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005121 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005122 return BAD_VALUE;
5123 }
5124 }
François Gaffie11d30102018-11-02 16:09:09 +01005125 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005126 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005127 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005128 return BAD_VALUE;
5129 }
Eric Laurent874c42872014-08-08 15:13:39 -07005130
Eric Laurent6a94d692014-05-20 11:18:06 -07005131 //update source and sink with our own data as the data passed in the patch may
5132 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005133 PatchBuilder patchBuilder;
5134 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005135
5136 // if first sink is to MSD, establish single MSD patch
5137 if (getMsdAudioOutDevices().contains(
5138 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5139 ALOGV("%s patching to MSD", __FUNCTION__);
5140 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5141 goto installPatch;
5142 }
5143
François Gaffieafd4cea2019-11-18 15:50:22 +01005144 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5145 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005146
Eric Laurent874c42872014-08-08 15:13:39 -07005147 for (size_t i = 0; i < patch->num_sinks; i++) {
5148 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005149 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005150 return INVALID_OPERATION;
5151 }
François Gaffie11d30102018-11-02 16:09:09 +01005152 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005153 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005154 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005155 return BAD_VALUE;
5156 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005157 audio_port_config sinkPortConfig = {};
5158 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5159 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005160
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005161 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5162 // volume management purpose (tracking activity)
5163 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5164 // in config XML to reach the sink so that is can be declared as available.
5165 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005166 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005167 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005168 // take care of dynamic routing for SwOutput selection,
5169 audio_attributes_t attributes = sourceDesc->attributes();
5170 audio_stream_type_t stream = sourceDesc->stream();
5171 audio_attributes_t resultAttr;
5172 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5173 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005174 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5175 config.channel_mask =
5176 (audio_channel_mask_get_representation(sourceMask)
5177 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5178 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005179 config.format = sourceDesc->config().format;
5180 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5181 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5182 bool isRequestedDeviceForExclusiveUse = false;
5183 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005184 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005185 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005186 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5187 &stream, sourceDesc->uid(), &config, &flags,
5188 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005189 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005190 if (output == AUDIO_IO_HANDLE_NONE) {
5191 ALOGV("%s no output for device %s",
5192 __FUNCTION__, sinkDevice->toString().c_str());
5193 return INVALID_OPERATION;
5194 }
5195 outputDesc = mOutputs.valueFor(output);
5196 if (outputDesc->isDuplicated()) {
5197 ALOGE("%s output is duplicated", __func__);
5198 return INVALID_OPERATION;
5199 }
François Gaffie7e39df22022-04-26 12:48:49 +02005200 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5201 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005202 } else {
5203 // Same for "raw patches" aka created from createAudioPatch API
5204 SortedVector<audio_io_handle_t> outputs =
5205 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5206 // if the sink device is reachable via an opened output stream, request to
5207 // go via this output stream by adding a second source to the patch
5208 // description
5209 output = selectOutput(outputs);
5210 if (output == AUDIO_IO_HANDLE_NONE) {
5211 ALOGE("%s no output available for internal patch sink", __func__);
5212 return INVALID_OPERATION;
5213 }
5214 outputDesc = mOutputs.valueFor(output);
5215 if (outputDesc->isDuplicated()) {
5216 ALOGV("%s output for device %s is duplicated",
5217 __func__, sinkDevice->toString().c_str());
5218 return INVALID_OPERATION;
5219 }
François Gaffie7e39df22022-04-26 12:48:49 +02005220 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005221 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005222 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005223 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005224 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005225 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005226 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5227 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005228 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5229 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005230 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005231 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005232 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005233 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005234 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005235 return INVALID_OPERATION;
5236 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005237 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005238 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005239 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005240 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005241 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005242 srcMixPortConfig.ext.mix.usecase.stream =
5243 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005244 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5245 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005246 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005247 }
Eric Laurent83b88082014-06-20 18:31:16 -07005248 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 }
5250 // TODO: check from routing capabilities in config file and other conflicting patches
5251
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005252installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005253 status_t status = installPatch(
5254 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005255 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005256 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 return INVALID_OPERATION;
5258 }
5259 } else {
5260 return BAD_VALUE;
5261 }
5262 } else {
5263 return BAD_VALUE;
5264 }
5265 return NO_ERROR;
5266}
5267
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005268status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005269{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005270 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 ssize_t index = mAudioPatches.indexOfKey(handle);
5272
5273 if (index < 0) {
5274 return BAD_VALUE;
5275 }
5276 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005277 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5278 __func__, mUidCached, patchDesc->getUid(), uid);
5279 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 return INVALID_OPERATION;
5281 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005282 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5283 for (size_t i = 0; i < mAudioSources.size(); i++) {
5284 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5285 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5286 portId = sourceDesc->portId();
5287 break;
5288 }
5289 }
5290 return portId != AUDIO_PORT_HANDLE_NONE ?
5291 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005292}
Eric Laurent6a94d692014-05-20 11:18:06 -07005293
François Gaffieafd4cea2019-11-18 15:50:22 +01005294status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005295 uint32_t delayMs,
5296 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005297{
5298 ALOGV("%s patch %d", __func__, handle);
5299 if (mAudioPatches.indexOfKey(handle) < 0) {
5300 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5301 return BAD_VALUE;
5302 }
5303 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005304 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005305 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005306 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005307 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005308 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005309 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005310 return BAD_VALUE;
5311 }
5312
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305313 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005314 getNewOutputDevices(outputDesc, true /*fromCache*/),
5315 true,
5316 0,
5317 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5319 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005320 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005322 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005323 return BAD_VALUE;
5324 }
5325 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005326 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005327 true,
5328 NULL);
5329 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005330 status_t status =
5331 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5332 ALOGV("%s patch panel returned %d patchHandle %d",
5333 __func__, status, patchDesc->getAfHandle());
5334 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005335 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005336 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005337 // SW or HW Bridge
5338 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5339 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005340 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005341 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5342 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5343 outputDesc = sourceDesc->swOutput().promote();
5344 }
5345 if (outputDesc == nullptr) {
5346 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5347 // releaseOutput has already called closeOutput in case of direct output
5348 return NO_ERROR;
5349 }
François Gaffie7e39df22022-04-26 12:48:49 +02005350 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005351 // While using a HwBridge, force reconsidering device only if not reusing an existing
5352 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005353 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005354 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5355 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5356 // Reconsider device only for cases:
5357 // 1 / Active Output
5358 // 2 / Inactive Output previously hosting HwBridge
5359 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5360 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5361 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305362 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005363 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5364 outputDesc->devices(),
5365 force,
5366 0,
5367 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005368 } else {
5369 return BAD_VALUE;
5370 }
5371 } else {
5372 return BAD_VALUE;
5373 }
5374 return NO_ERROR;
5375}
5376
5377status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5378 struct audio_patch *patches,
5379 unsigned int *generation)
5380{
François Gaffie53615e22015-03-19 09:24:12 +01005381 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005382 return BAD_VALUE;
5383 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005384 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005385 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005386}
5387
Eric Laurente1715a42014-05-20 11:30:42 -07005388status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005389{
Eric Laurente1715a42014-05-20 11:30:42 -07005390 ALOGV("setAudioPortConfig()");
5391
5392 if (config == NULL) {
5393 return BAD_VALUE;
5394 }
5395 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5396 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005397 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5398 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005399 }
5400
Eric Laurenta121f902014-06-03 13:32:54 -07005401 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005402 if (config->type == AUDIO_PORT_TYPE_MIX) {
5403 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005404 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005405 if (outputDesc == NULL) {
5406 return BAD_VALUE;
5407 }
Eric Laurent84c70242014-06-23 08:46:27 -07005408 ALOG_ASSERT(!outputDesc->isDuplicated(),
5409 "setAudioPortConfig() called on duplicated output %d",
5410 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005411 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005412 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005413 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005414 if (inputDesc == NULL) {
5415 return BAD_VALUE;
5416 }
Eric Laurenta121f902014-06-03 13:32:54 -07005417 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005418 } else {
5419 return BAD_VALUE;
5420 }
5421 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5422 sp<DeviceDescriptor> deviceDesc;
5423 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5424 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5425 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5426 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5427 } else {
5428 return BAD_VALUE;
5429 }
5430 if (deviceDesc == NULL) {
5431 return BAD_VALUE;
5432 }
Eric Laurenta121f902014-06-03 13:32:54 -07005433 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005434 } else {
5435 return BAD_VALUE;
5436 }
5437
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005438 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005439 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5440 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005441 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005442 audioPortConfig->toAudioPortConfig(&newConfig, config);
5443 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005444 }
Eric Laurenta121f902014-06-03 13:32:54 -07005445 if (status != NO_ERROR) {
5446 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005447 }
Eric Laurente1715a42014-05-20 11:30:42 -07005448
5449 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005450}
5451
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005452void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5453{
Eric Laurentd60560a2015-04-10 11:31:20 -07005454 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005455 clearAudioPatches(uid);
5456 clearSessionRoutes(uid);
5457}
5458
Eric Laurent6a94d692014-05-20 11:18:06 -07005459void AudioPolicyManager::clearAudioPatches(uid_t uid)
5460{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005461 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005462 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005463 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005464 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005465 }
5466 }
5467}
5468
François Gaffiec005e562018-11-06 15:04:49 +01005469void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005470{
François Gaffiec005e562018-11-06 15:04:49 +01005471 // Take the first attributes following the product strategy as it is used to retrieve the routed
5472 // device. All attributes wihin a strategy follows the same "routing strategy"
5473 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5474 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005475 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005476 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005477 for (size_t j = 0; j < mOutputs.size(); j++) {
5478 if (mOutputs.keyAt(j) == ouptutToSkip) {
5479 continue;
5480 }
5481 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005482 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005483 continue;
5484 }
5485 // If the default device for this strategy is on another output mix,
5486 // invalidate all tracks in this strategy to force re connection.
5487 // Otherwise select new device on the output mix.
5488 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005489 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005490 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005491 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5492 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5493 // If the device is using preferred mixer attributes, the output need to reopen
5494 // with default configuration when the new selected devices are different from
5495 // current routing devices.
5496 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5497 continue;
5498 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305499 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005500 }
5501 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005502 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005503}
5504
5505void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5506{
5507 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005508 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005509 for (size_t i = 0; i < mOutputs.size(); i++) {
5510 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005511 for (const auto& client : outputDesc->getClientIterable()) {
5512 if (client->hasPreferredDevice() && client->uid() == uid) {
5513 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005514 auto clientStrategy = client->strategy();
5515 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5516 end(affectedStrategies)) {
5517 continue;
5518 }
5519 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005520 }
5521 }
5522 }
5523 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005524 for (const auto& strategy : affectedStrategies) {
5525 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005526 }
5527
5528 // remove input routes associated with this uid
5529 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005530 for (size_t i = 0; i < mInputs.size(); i++) {
5531 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005532 for (const auto& client : inputDesc->getClientIterable()) {
5533 if (client->hasPreferredDevice() && client->uid() == uid) {
5534 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5535 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005536 }
5537 }
5538 }
5539 // reroute inputs if necessary
5540 SortedVector<audio_io_handle_t> inputsToClose;
5541 for (size_t i = 0; i < mInputs.size(); i++) {
5542 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005543 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005544 inputsToClose.add(inputDesc->mIoHandle);
5545 }
5546 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005547 for (const auto& input : inputsToClose) {
5548 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005549 }
5550}
5551
Eric Laurentd60560a2015-04-10 11:31:20 -07005552void AudioPolicyManager::clearAudioSources(uid_t uid)
5553{
5554 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005555 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5556 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005557 stopAudioSource(mAudioSources.keyAt(i));
5558 }
5559 }
5560}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005561
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005562status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5563 audio_io_handle_t *ioHandle,
5564 audio_devices_t *device)
5565{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005566 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5567 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005568 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005569 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5570 if (deviceDesc == nullptr) {
5571 return INVALID_OPERATION;
5572 }
5573 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005574
François Gaffiedf372692015-03-19 10:43:27 +01005575 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005576}
5577
Eric Laurentd60560a2015-04-10 11:31:20 -07005578status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005579 const audio_attributes_t *attributes,
5580 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005581 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005582{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005583 ALOGV("%s", __FUNCTION__);
5584 *portId = AUDIO_PORT_HANDLE_NONE;
5585
5586 if (source == NULL || attributes == NULL || portId == NULL) {
5587 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5588 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005589 return BAD_VALUE;
5590 }
5591
Eric Laurentd60560a2015-04-10 11:31:20 -07005592 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5593 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005594 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5595 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005596 return INVALID_OPERATION;
5597 }
5598
François Gaffie11d30102018-11-02 16:09:09 +01005599 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005600 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005601 String8(source->ext.device.address),
5602 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005603 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005604 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005605 return BAD_VALUE;
5606 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005607
jiabin4ef93452019-09-10 14:29:54 -07005608 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005609
François Gaffieaaac0fd2018-11-22 17:56:39 +01005610 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005611 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005612 mEngine->getStreamTypeForAttributes(*attributes),
5613 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005614 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005615
5616 status_t status = connectAudioSource(sourceDesc);
5617 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005618 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005619 }
5620 return status;
5621}
5622
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005623status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005624{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005625 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005626
5627 // make sure we only have one patch per source.
5628 disconnectAudioSource(sourceDesc);
5629
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005630 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005631 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5632 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5633 sourceDesc->srcDevice()->type(),
5634 String8(sourceDesc->srcDevice()->address().c_str()),
5635 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005636 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005637 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005638 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005639 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005640 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5641 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5642 return INVALID_OPERATION;
5643 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005644 PatchBuilder patchBuilder;
5645 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5646 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005647
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005648 return connectAudioSourceToSink(
5649 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005650}
5651
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005652status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005653{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005654 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5655 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005656 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005657 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005658 return BAD_VALUE;
5659 }
5660 status_t status = disconnectAudioSource(sourceDesc);
5661
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005662 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005663 return status;
5664}
5665
Andy Hung2ddee192015-12-18 17:34:44 -08005666status_t AudioPolicyManager::setMasterMono(bool mono)
5667{
5668 if (mMasterMono == mono) {
5669 return NO_ERROR;
5670 }
5671 mMasterMono = mono;
5672 // if enabling mono we close all offloaded devices, which will invalidate the
5673 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5674 // for recreating the new AudioTrack as non-offloaded PCM.
5675 //
5676 // If disabling mono, we leave all tracks as is: we don't know which clients
5677 // and tracks are able to be recreated as offloaded. The next "song" should
5678 // play back offloaded.
5679 if (mMasterMono) {
5680 Vector<audio_io_handle_t> offloaded;
5681 for (size_t i = 0; i < mOutputs.size(); ++i) {
5682 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5683 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5684 offloaded.push(desc->mIoHandle);
5685 }
5686 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005687 for (const auto& handle : offloaded) {
5688 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005689 }
5690 }
5691 // update master mono for all remaining outputs
5692 for (size_t i = 0; i < mOutputs.size(); ++i) {
5693 updateMono(mOutputs.keyAt(i));
5694 }
5695 return NO_ERROR;
5696}
5697
5698status_t AudioPolicyManager::getMasterMono(bool *mono)
5699{
5700 *mono = mMasterMono;
5701 return NO_ERROR;
5702}
5703
Eric Laurentac9cef52017-06-09 15:46:26 -07005704float AudioPolicyManager::getStreamVolumeDB(
5705 audio_stream_type_t stream, int index, audio_devices_t device)
5706{
jiabin9a3361e2019-10-01 09:38:30 -07005707 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005708}
5709
jiabin81772902018-04-02 17:52:27 -07005710status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5711 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005712 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005713{
Kriti Dang6537def2021-03-02 13:46:59 +01005714 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5715 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005716 return BAD_VALUE;
5717 }
Kriti Dang6537def2021-03-02 13:46:59 +01005718 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5719 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005720
5721 size_t formatsWritten = 0;
5722 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005723
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005724 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005725 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5726 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005727 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005728 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005729 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005730 bool formatEnabled = true;
5731 switch (forceUse) {
5732 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005733 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005734 break;
5735 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5736 formatEnabled = false;
5737 break;
5738 default: // AUTO or ALWAYS => true
5739 break;
jiabin81772902018-04-02 17:52:27 -07005740 }
5741 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5742 }
jiabin81772902018-04-02 17:52:27 -07005743 }
5744 return NO_ERROR;
5745}
5746
Kriti Dang6537def2021-03-02 13:46:59 +01005747status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5748 audio_format_t *surroundFormats) {
5749 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5750 return BAD_VALUE;
5751 }
5752 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5753 __func__, *numSurroundFormats, surroundFormats);
5754
5755 size_t formatsWritten = 0;
5756 size_t formatsMax = *numSurroundFormats;
5757 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5758
5759 // Return formats from all device profiles that have already been resolved by
5760 // checkOutputsForDevice().
5761 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5762 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5763 audio_devices_t deviceType = device->type();
5764 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5765 // returns formats reported by HDMI devices.
5766 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5767 continue;
5768 }
5769 // Formats reported by sink devices
5770 std::unordered_set<audio_format_t> formatset;
5771 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5772 formatset.insert(it->second.begin(), it->second.end());
5773 }
5774
5775 // Formats hard-coded in the in policy configuration file (if any).
5776 FormatVector encodedFormats = device->encodedFormats();
5777 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5778 // Filter the formats which are supported by the vendor hardware.
5779 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005780 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005781 formats.insert(*it);
5782 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005783 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005784 if (pair.second.count(*it) != 0) {
5785 formats.insert(pair.first);
5786 break;
5787 }
5788 }
5789 }
5790 }
5791 }
5792 *numSurroundFormats = formats.size();
5793 for (const auto& format: formats) {
5794 if (formatsWritten < formatsMax) {
5795 surroundFormats[formatsWritten++] = format;
5796 }
5797 }
5798 return NO_ERROR;
5799}
5800
jiabin81772902018-04-02 17:52:27 -07005801status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5802{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005803 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005804 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5805 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005806 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005807 return BAD_VALUE;
5808 }
5809
Mikhail Naganov100f0122018-11-29 11:22:16 -08005810 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5811 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005812 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005813 return INVALID_OPERATION;
5814 }
5815
Mikhail Naganov100f0122018-11-29 11:22:16 -08005816 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005817 return NO_ERROR;
5818 }
5819
Mikhail Naganov100f0122018-11-29 11:22:16 -08005820 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005821 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005822 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005823 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005824 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005825 }
5826 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005827 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005828 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005829 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005830 }
5831 }
5832
5833 sp<SwAudioOutputDescriptor> outputDesc;
5834 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005835 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5836 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005837 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5838 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005839 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005840 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005841 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5842 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5843 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005844 name.c_str(),
5845 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005846 if (status != NO_ERROR) {
5847 continue;
5848 }
5849 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5850 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5851 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005852 name.c_str(),
5853 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005854 profileUpdated |= (status == NO_ERROR);
5855 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005856 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005857 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005858 AUDIO_DEVICE_IN_HDMI);
5859 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5860 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005861 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005862 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005863 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5864 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5865 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005866 name.c_str(),
5867 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005868 if (status != NO_ERROR) {
5869 continue;
5870 }
5871 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5872 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5873 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005874 name.c_str(),
5875 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005876 profileUpdated |= (status == NO_ERROR);
5877 }
5878
jiabin81772902018-04-02 17:52:27 -07005879 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005880 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005881 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005882 }
5883
5884 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5885}
5886
Eric Laurent5ada82e2019-08-29 17:53:54 -07005887void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005888{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005889 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005890 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005891 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005892 }
5893}
5894
jiabin6012f912018-11-02 17:06:30 -07005895bool AudioPolicyManager::isHapticPlaybackSupported()
5896{
5897 for (const auto& hwModule : mHwModules) {
5898 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5899 for (const auto &outProfile : outputProfiles) {
5900 struct audio_port audioPort;
5901 outProfile->toAudioPort(&audioPort);
5902 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5903 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5904 return true;
5905 }
5906 }
5907 }
5908 }
5909 return false;
5910}
5911
Carter Hsu325a8eb2022-01-19 19:56:51 +08005912bool AudioPolicyManager::isUltrasoundSupported()
5913{
5914 bool hasUltrasoundOutput = false;
5915 bool hasUltrasoundInput = false;
5916 for (const auto& hwModule : mHwModules) {
5917 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5918 if (!hasUltrasoundOutput) {
5919 for (const auto &outProfile : outputProfiles) {
5920 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5921 hasUltrasoundOutput = true;
5922 break;
5923 }
5924 }
5925 }
5926
5927 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5928 if (!hasUltrasoundInput) {
5929 for (const auto &inputProfile : inputProfiles) {
5930 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5931 hasUltrasoundInput = true;
5932 break;
5933 }
5934 }
5935 }
5936
5937 if (hasUltrasoundOutput && hasUltrasoundInput)
5938 return true;
5939 }
5940 return false;
5941}
5942
Atneya Nair698f5ef2022-12-15 16:15:09 -08005943bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5944{
5945 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5946 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5947 for (const auto& hwModule : mHwModules) {
5948 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5949 for (const auto &inputProfile : inputProfiles) {
5950 if ((inputProfile->getFlags() & mask) == mask) {
5951 return true;
5952 }
5953 }
5954 }
5955 return false;
5956}
5957
Eric Laurent8340e672019-11-06 11:01:08 -08005958bool AudioPolicyManager::isCallScreenModeSupported()
5959{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005960 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005961}
5962
5963
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005964status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005965{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005966 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005967 if (!sourceDesc->isConnected()) {
5968 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5969 return NO_ERROR;
5970 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005971 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5972 if (swOutput != 0) {
5973 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005974 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005975 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005976 }
jiabinbce0c1d2020-10-05 11:20:18 -07005977 if (releaseOutput(sourceDesc->portId())) {
5978 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5979 // no need to release audio patch here but just return NO_ERROR.
5980 return NO_ERROR;
5981 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005982 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005983 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005984 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005985 // close Hwoutput and remove from mHwOutputs
5986 } else {
5987 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5988 }
5989 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005990 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005991 sourceDesc->disconnect();
5992 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005993}
5994
François Gaffiec005e562018-11-06 15:04:49 +01005995sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5996 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005997{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005998 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005999 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006000 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006001 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006002 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6003 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006004 source = sourceDesc;
6005 break;
6006 }
6007 }
6008 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006009}
6010
Eric Laurentb4f42a92022-01-17 17:37:31 +01006011bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006012 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006013 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006014{
6015 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6016 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006017 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006018 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006019 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6020 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6021 return false;
6022 }
6023 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6024 return false;
6025 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006026 }
6027
Eric Laurentd332bc82023-08-04 11:45:23 +02006028 // The caller can have the audio config criteria ignored by either passing a null ptr or
6029 // the AUDIO_CONFIG_INITIALIZER value.
6030 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006031 // some positional channel masks and PCM format and for stereo if low latency performance
6032 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006033
6034 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006035 static const bool stereo_spatialization_enabled =
6036 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006037 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006038 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006039 ? audio_channel_mask_contains_stereo(config->channel_mask)
6040 : audio_is_channel_mask_spatialized(config->channel_mask);
6041 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006042 return false;
6043 }
6044 if (!audio_is_linear_pcm(config->format)) {
6045 return false;
6046 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006047 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6048 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6049 return false;
6050 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006051 }
6052
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006053 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006054 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006055 if (profile == nullptr) {
6056 return false;
6057 }
6058
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006059 return true;
6060}
6061
6062void AudioPolicyManager::checkVirtualizerClientRoutes() {
6063 std::set<audio_stream_type_t> streamsToInvalidate;
6064 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006065 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6066 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006067 audio_attributes_t attr = client->attributes();
6068 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6069 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6070 audio_config_base_t clientConfig = client->config();
6071 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006072 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006073 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006074 streamsToInvalidate.insert(client->stream());
6075 }
6076 }
6077 }
6078
jiabinc44b3462022-12-08 12:52:31 -08006079 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006080}
6081
Eric Laurente191d1b2022-04-15 11:59:25 +02006082
6083bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6084 const sp<SwAudioOutputDescriptor>& outputDesc) {
6085 if (outputDesc->isDuplicated()) {
6086 return false;
6087 }
6088 DeviceVector devices = outputDesc->supportedDevices();
6089 for (size_t i = 0; i < mOutputs.size(); i++) {
6090 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6091 if (desc == outputDesc || desc->isDuplicated()) {
6092 continue;
6093 }
6094 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6095 if (!sharedDevices.isEmpty()
6096 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6097 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6098 return false;
6099 }
6100 }
6101 return true;
6102}
6103
6104
Eric Laurentfa0f6742021-08-17 18:39:44 +02006105status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006106 const audio_attributes_t *attr,
6107 audio_io_handle_t *output) {
6108 *output = AUDIO_IO_HANDLE_NONE;
6109
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006110 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6111 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6112 audio_config_t *configPtr = nullptr;
6113 audio_config_t config;
6114 if (mixerConfig != nullptr) {
6115 config = audio_config_initializer(mixerConfig);
6116 configPtr = &config;
6117 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006118 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006119 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006120 return BAD_VALUE;
6121 }
6122
6123 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006124 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006125 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006126 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006127 return BAD_VALUE;
6128 }
6129
Eric Laurente191d1b2022-04-15 11:59:25 +02006130 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006131 for (size_t i = 0; i < mOutputs.size(); i++) {
6132 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006133 if (!desc->isDuplicated()
6134 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6135 spatializerOutputs.push_back(desc);
6136 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006137 }
6138 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006139 mSpatializerOutput.clear();
6140 bool outputsChanged = false;
6141 for (const auto& desc : spatializerOutputs) {
6142 if (desc->mProfile == profile
6143 && (configPtr == nullptr
6144 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6145 mSpatializerOutput = desc;
6146 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6147 } else {
6148 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6149 " and devices %s", __func__, desc->mIoHandle,
6150 configPtr != nullptr ? configPtr->channel_mask : 0,
6151 devices.toString().c_str());
6152 closeOutput(desc->mIoHandle);
6153 outputsChanged = true;
6154 }
Eric Laurent39095982021-08-24 18:29:27 +02006155 }
6156
Eric Laurente191d1b2022-04-15 11:59:25 +02006157 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006158 sp<SwAudioOutputDescriptor> desc =
6159 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006160 if (desc != nullptr) {
6161 mSpatializerOutput = desc;
6162 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006163 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006164 }
6165
6166 checkVirtualizerClientRoutes();
6167
Eric Laurente191d1b2022-04-15 11:59:25 +02006168 if (outputsChanged) {
6169 mPreviousOutputs = mOutputs;
6170 mpClientInterface->onAudioPortListUpdate();
6171 }
6172
6173 if (mSpatializerOutput == nullptr) {
6174 ALOGV("%s could not open spatializer output with requested config", __func__);
6175 return BAD_VALUE;
6176 }
Eric Laurent39095982021-08-24 18:29:27 +02006177 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006178 ALOGV("%s returning new spatializer output %d", __func__, *output);
6179 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006180}
6181
Eric Laurentfa0f6742021-08-17 18:39:44 +02006182status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6183 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006184 return INVALID_OPERATION;
6185 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006186 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006187 return BAD_VALUE;
6188 }
Eric Laurent39095982021-08-24 18:29:27 +02006189
Eric Laurente191d1b2022-04-15 11:59:25 +02006190 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6191 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6192 closeOutput(mSpatializerOutput->mIoHandle);
6193 //from now on mSpatializerOutput is null
6194 checkVirtualizerClientRoutes();
6195 }
Eric Laurent39095982021-08-24 18:29:27 +02006196
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006197 return NO_ERROR;
6198}
6199
Eric Laurente552edb2014-03-10 17:42:56 -07006200// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006201// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006202// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006203uint32_t AudioPolicyManager::nextAudioPortGeneration()
6204{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006205 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006206}
6207
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006208AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006209 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006210 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006211 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006212 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006213 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006214 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006215 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006216 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006217 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006218 mAudioPortGeneration(1),
6219 mBeaconMuteRefCount(0),
6220 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006221 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006222 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006223 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006224 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006225{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006226}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006227
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006228status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006229 if (mEngine == nullptr) {
6230 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006231 }
6232 mEngine->setObserver(this);
6233 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006234 if (status != NO_ERROR) {
6235 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6236 return status;
6237 }
François Gaffie2110e042015-03-24 08:41:51 +01006238
jiabin29230182023-04-04 21:02:36 +00006239 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6240 // at the end of this function.
6241 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006242 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6243 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6244
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006245 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006246 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006247 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006248
Eric Laurent3a4311c2014-03-17 12:00:47 -07006249 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006250 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6251 defaultOutputDevice == nullptr ||
6252 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6253 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6254 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006255 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006256 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006257 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006258
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006259 // Silence ALOGV statements
6260 property_set("log.tag." LOG_TAG, "D");
6261
Eric Laurente552edb2014-03-10 17:42:56 -07006262 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006263 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006264}
6265
Eric Laurente0720872014-03-11 09:30:41 -07006266AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006267{
Eric Laurente552edb2014-03-10 17:42:56 -07006268 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006269 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006270 }
6271 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006272 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006273 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006274 mAvailableOutputDevices.clear();
6275 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006276 mOutputs.clear();
6277 mInputs.clear();
6278 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006279 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006280 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006281}
6282
Eric Laurente0720872014-03-11 09:30:41 -07006283status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006284{
Eric Laurent87ffa392015-05-22 10:32:38 -07006285 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006286}
6287
Eric Laurente552edb2014-03-10 17:42:56 -07006288// ---
6289
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006290void AudioPolicyManager::onNewAudioModulesAvailable()
6291{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006292 DeviceVector newDevices;
6293 onNewAudioModulesAvailableInt(&newDevices);
6294 if (!newDevices.empty()) {
6295 nextAudioPortGeneration();
6296 mpClientInterface->onAudioPortListUpdate();
6297 }
6298}
6299
6300void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6301{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006302 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006303 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6304 continue;
6305 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006306 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006307 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6308 handle != AUDIO_MODULE_HANDLE_NONE) {
6309 hwModule->setHandle(handle);
6310 } else {
6311 ALOGW("could not load HW module %s", hwModule->getName());
6312 continue;
6313 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006314 }
6315 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006316 // open all output streams needed to access attached devices.
6317 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006318 // This also validates mAvailableOutputDevices list
6319 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6320 if (!outProfile->canOpenNewIo()) {
6321 ALOGE("Invalid Output profile max open count %u for profile %s",
6322 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6323 continue;
6324 }
6325 if (!outProfile->hasSupportedDevices()) {
6326 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6327 continue;
6328 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006329 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6330 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006331 mTtsOutputAvailable = true;
6332 }
6333
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006334 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006335 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006336 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006337 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6338 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006339 } else {
6340 // choose first device present in profile's SupportedDevices also part of
6341 // mAvailableOutputDevices.
6342 if (availProfileDevices.isEmpty()) {
6343 continue;
6344 }
6345 supportedDevice = availProfileDevices.itemAt(0);
6346 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006347 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006348 continue;
6349 }
6350 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6351 mpClientInterface);
6352 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006353 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6354 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006355 AUDIO_STREAM_DEFAULT,
6356 AUDIO_OUTPUT_FLAG_NONE, &output);
6357 if (status != NO_ERROR) {
6358 ALOGW("Cannot open output stream for devices %s on hw module %s",
6359 supportedDevice->toString().c_str(), hwModule->getName());
6360 continue;
6361 }
6362 for (const auto &device : availProfileDevices) {
6363 // give a valid ID to an attached device once confirmed it is reachable
6364 if (!device->isAttached()) {
6365 device->attach(hwModule);
6366 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006367 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006368 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006369 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6370 }
6371 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006372 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006373 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6374 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006375 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006376 }
Eric Laurent39095982021-08-24 18:29:27 +02006377 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006378 outputDesc->close();
6379 } else {
6380 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306381 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006382 DeviceVector(supportedDevice),
6383 true,
6384 0,
6385 NULL);
6386 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006387 }
6388 // open input streams needed to access attached devices to validate
6389 // mAvailableInputDevices list
6390 for (const auto& inProfile : hwModule->getInputProfiles()) {
6391 if (!inProfile->canOpenNewIo()) {
6392 ALOGE("Invalid Input profile max open count %u for profile %s",
6393 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6394 continue;
6395 }
6396 if (!inProfile->hasSupportedDevices()) {
6397 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6398 continue;
6399 }
6400 // chose first device present in profile's SupportedDevices also part of
6401 // available input devices
6402 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006403 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006404 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006405 ALOGV("%s: Input device list is empty! for profile %s",
6406 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006407 continue;
6408 }
6409 sp<AudioInputDescriptor> inputDesc =
6410 new AudioInputDescriptor(inProfile, mpClientInterface);
6411
6412 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6413 status_t status = inputDesc->open(nullptr,
6414 availProfileDevices.itemAt(0),
6415 AUDIO_SOURCE_MIC,
6416 AUDIO_INPUT_FLAG_NONE,
6417 &input);
6418 if (status != NO_ERROR) {
6419 ALOGW("Cannot open input stream for device %s on hw module %s",
6420 availProfileDevices.toString().c_str(),
6421 hwModule->getName());
6422 continue;
6423 }
6424 for (const auto &device : availProfileDevices) {
6425 // give a valid ID to an attached device once confirmed it is reachable
6426 if (!device->isAttached()) {
6427 device->attach(hwModule);
6428 device->importAudioPortAndPickAudioProfile(inProfile, true);
6429 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006430 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006431 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6432 }
6433 }
6434 inputDesc->close();
6435 }
6436 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006437
6438 // Check if spatializer outputs can be closed until used.
6439 // mOutputs vector never contains duplicated outputs at this point.
6440 std::vector<audio_io_handle_t> outputsClosed;
6441 for (size_t i = 0; i < mOutputs.size(); i++) {
6442 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6443 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6444 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6445 outputsClosed.push_back(desc->mIoHandle);
6446 desc->close();
6447 }
6448 }
6449 for (auto output : outputsClosed) {
6450 removeOutput(output);
6451 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006452}
6453
Eric Laurent98e38192018-02-15 18:31:53 -08006454void AudioPolicyManager::addOutput(audio_io_handle_t output,
6455 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006456{
Eric Laurent1c333e22014-05-20 10:48:17 -07006457 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006458 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006459 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006460 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006461 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006462}
6463
François Gaffie53615e22015-03-19 09:24:12 +01006464void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6465{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006466 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6467 ALOGV("%s: removing primary output", __func__);
6468 mPrimaryOutput = nullptr;
6469 }
François Gaffie53615e22015-03-19 09:24:12 +01006470 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006471 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006472}
6473
Eric Laurent98e38192018-02-15 18:31:53 -08006474void AudioPolicyManager::addInput(audio_io_handle_t input,
6475 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006476{
Eric Laurent1c333e22014-05-20 10:48:17 -07006477 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006478 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006479}
Eric Laurente552edb2014-03-10 17:42:56 -07006480
François Gaffie11d30102018-11-02 16:09:09 +01006481status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006482 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006483 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006484{
François Gaffie11d30102018-11-02 16:09:09 +01006485 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006486 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006487 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006488
François Gaffie11d30102018-11-02 16:09:09 +01006489 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006490 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006491 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006492 }
Eric Laurente552edb2014-03-10 17:42:56 -07006493
Eric Laurent3b73df72014-03-11 09:06:29 -07006494 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006495 // first call getAudioPort to get the supported attributes from the HAL
6496 struct audio_port_v7 port = {};
6497 device->toAudioPort(&port);
6498 status_t status = mpClientInterface->getAudioPort(&port);
6499 if (status == NO_ERROR) {
6500 device->importAudioPort(port);
6501 }
6502
6503 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006504 for (size_t i = 0; i < mOutputs.size(); i++) {
6505 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006506 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006507 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006508 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6509 mOutputs.keyAt(i), device->toString().c_str());
6510 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006511 }
6512 }
6513 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006514 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006515 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006516 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6517 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006518 if (profile->supportsDevice(device)) {
6519 profiles.add(profile);
6520 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6521 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006522 }
6523 }
6524 }
6525
Eric Laurent7b279bb2015-12-14 10:18:23 -08006526 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006527
Eric Laurente552edb2014-03-10 17:42:56 -07006528 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006529 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006530 return BAD_VALUE;
6531 }
6532
6533 // open outputs for matching profiles if needed. Direct outputs are also opened to
6534 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6535 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006536 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006537
6538 // nothing to do if one output is already opened for this profile
6539 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006540 for (j = 0; j < outputs.size(); j++) {
6541 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006542 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006543 // matching profile: save the sample rates, format and channel masks supported
6544 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006545 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006546 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006547 }
Eric Laurente552edb2014-03-10 17:42:56 -07006548 break;
6549 }
6550 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006551 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006552 continue;
6553 }
6554
Eric Laurent3974e3b2017-12-07 17:58:43 -08006555 if (!profile->canOpenNewIo()) {
6556 ALOGW("Max Output number %u already opened for this profile %s",
6557 profile->maxOpenCount, profile->getTagName().c_str());
6558 continue;
6559 }
6560
Eric Laurent83efe1c2017-07-09 16:51:08 -07006561 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006562 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006563 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6564 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006565 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006566 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006567 profiles.removeAt(profile_index);
6568 profile_index--;
6569 } else {
6570 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006571 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006572 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006573 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6574 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006575 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006576 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006577
François Gaffie11d30102018-11-02 16:09:09 +01006578 if (device_distinguishes_on_address(deviceType)) {
6579 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6580 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306581 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6582 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006583 }
Eric Laurente552edb2014-03-10 17:42:56 -07006584 ALOGV("checkOutputsForDevice(): adding output %d", output);
6585 }
6586 }
6587
6588 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006589 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006590 return BAD_VALUE;
6591 }
Eric Laurentd4692962014-05-05 18:13:44 -07006592 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006593 // check if one opened output is not needed any more after disconnecting one device
6594 for (size_t i = 0; i < mOutputs.size(); i++) {
6595 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006596 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006597 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006598 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006599 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006600 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006601 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006602 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6603 mOutputs.keyAt(i));
6604 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006605 }
Eric Laurente552edb2014-03-10 17:42:56 -07006606 }
6607 }
Eric Laurentd4692962014-05-05 18:13:44 -07006608 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006609 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006610 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6611 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006612 if (!profile->supportsDevice(device)) {
6613 continue;
6614 }
6615 ALOGV("checkOutputsForDevice(): "
6616 "clearing direct output profile %zu on module %s",
6617 j, hwModule->getName());
6618 profile->clearAudioProfiles();
6619 if (!profile->hasDynamicAudioProfile()) {
6620 continue;
6621 }
6622 // When a device is disconnected, if there is an IOProfile that contains dynamic
6623 // profiles and supports the disconnected device, call getAudioPort to repopulate
6624 // the capabilities of the devices that is supported by the IOProfile.
6625 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6626 if (supportedDevice == device ||
6627 !mAvailableOutputDevices.contains(supportedDevice)) {
6628 continue;
6629 }
6630 struct audio_port_v7 port;
6631 supportedDevice->toAudioPort(&port);
6632 status_t status = mpClientInterface->getAudioPort(&port);
6633 if (status == NO_ERROR) {
6634 supportedDevice->importAudioPort(port);
6635 }
Eric Laurente552edb2014-03-10 17:42:56 -07006636 }
6637 }
6638 }
6639 }
6640 return NO_ERROR;
6641}
6642
François Gaffie11d30102018-11-02 16:09:09 +01006643status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006644 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006645{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006646 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006647
François Gaffie11d30102018-11-02 16:09:09 +01006648 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006649 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006650 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006651 }
6652
Eric Laurentd4692962014-05-05 18:13:44 -07006653 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006654 // first call getAudioPort to get the supported attributes from the HAL
6655 struct audio_port_v7 port = {};
6656 device->toAudioPort(&port);
6657 status_t status = mpClientInterface->getAudioPort(&port);
6658 if (status == NO_ERROR) {
6659 device->importAudioPort(port);
6660 }
6661
Eric Laurent0dd51852019-04-19 18:18:58 -07006662 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006663 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006664 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006665 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006666 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006667 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006668 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006669
François Gaffie11d30102018-11-02 16:09:09 +01006670 if (profile->supportsDevice(device)) {
6671 profiles.add(profile);
6672 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6673 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006674 }
6675 }
6676 }
6677
Eric Laurent0dd51852019-04-19 18:18:58 -07006678 if (profiles.isEmpty()) {
6679 ALOGW("%s: No input profile available for device %s",
6680 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006681 return BAD_VALUE;
6682 }
6683
6684 // open inputs for matching profiles if needed. Direct inputs are also opened to
6685 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6686 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6687
Eric Laurent1c333e22014-05-20 10:48:17 -07006688 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006689
Eric Laurentd4692962014-05-05 18:13:44 -07006690 // nothing to do if one input is already opened for this profile
6691 size_t input_index;
6692 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6693 desc = mInputs.valueAt(input_index);
6694 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006695 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006696 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006697 }
Eric Laurentd4692962014-05-05 18:13:44 -07006698 break;
6699 }
6700 }
6701 if (input_index != mInputs.size()) {
6702 continue;
6703 }
6704
Eric Laurent3974e3b2017-12-07 17:58:43 -08006705 if (!profile->canOpenNewIo()) {
6706 ALOGW("Max Input number %u already opened for this profile %s",
6707 profile->maxOpenCount, profile->getTagName().c_str());
6708 continue;
6709 }
6710
Eric Laurentfe231122017-11-17 17:48:06 -08006711 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006712 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006713 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006714
Eric Laurentcf2c0212014-07-25 16:20:43 -07006715 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006716 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006717 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006718 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006719 mpClientInterface->setParameters(input, String8(param));
6720 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006721 }
jiabin12537fc2023-10-12 17:56:08 +00006722 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006723 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006724 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006725 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006726 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006727 }
6728
Eric Laurent0dd51852019-04-19 18:18:58 -07006729 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006730 addInput(input, desc);
6731 }
6732 } // endif input != 0
6733
Eric Laurentcf2c0212014-07-25 16:20:43 -07006734 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006735 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006736 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006737 profiles.removeAt(profile_index);
6738 profile_index--;
6739 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006740 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006741 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006742 }
Eric Laurentd4692962014-05-05 18:13:44 -07006743 ALOGV("checkInputsForDevice(): adding input %d", input);
6744 }
6745 } // end scan profiles
6746
6747 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006748 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006749 return BAD_VALUE;
6750 }
6751 } else {
6752 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006753 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006754 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006755 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006756 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006757 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006758 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006759 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006760 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6761 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006762 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006763 }
6764 }
6765 }
6766 } // end disconnect
6767
6768 return NO_ERROR;
6769}
6770
6771
Eric Laurente0720872014-03-11 09:30:41 -07006772void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006773{
6774 ALOGV("closeOutput(%d)", output);
6775
François Gaffie1c878552018-11-22 16:53:21 +01006776 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6777 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006778 ALOGW("closeOutput() unknown output %d", output);
6779 return;
6780 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006781 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006782 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006783
Eric Laurente552edb2014-03-10 17:42:56 -07006784 // look for duplicated outputs connected to the output being removed.
6785 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006786 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6787 if (dupOutput->isDuplicated() &&
6788 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6789 sp<SwAudioOutputDescriptor> remainingOutput =
6790 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006791 // As all active tracks on duplicated output will be deleted,
6792 // and as they were also referenced on the other output, the reference
6793 // count for their stream type must be adjusted accordingly on
6794 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006795 const bool wasActive = remainingOutput->isActive();
6796 // Note: no-op on the closing output where all clients has already been set inactive
6797 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006798 // stop() will be a no op if the output is still active but is needed in case all
6799 // active streams refcounts where cleared above
6800 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006801 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006802 }
Eric Laurente552edb2014-03-10 17:42:56 -07006803 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6804 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6805
6806 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006807 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006808 }
6809 }
6810
Eric Laurent05b90f82014-08-27 15:32:29 -07006811 nextAudioPortGeneration();
6812
François Gaffie1c878552018-11-22 16:53:21 +01006813 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006814 if (index >= 0) {
6815 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006816 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6817 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006818 mAudioPatches.removeItemsAt(index);
6819 mpClientInterface->onAudioPatchListUpdate();
6820 }
6821
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006822 if (closingOutputWasActive) {
6823 closingOutput->stop();
6824 }
François Gaffie1c878552018-11-22 16:53:21 +01006825 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006826 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6827 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6828 for (const auto device : closingOutput->devices()) {
6829 device->setPreferredConfig(nullptr);
6830 }
6831 }
Eric Laurente552edb2014-03-10 17:42:56 -07006832
François Gaffie53615e22015-03-19 09:24:12 +01006833 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006834 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006835 if (closingOutput == mSpatializerOutput) {
6836 mSpatializerOutput.clear();
6837 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006838
6839 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6840 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006841 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006842 bool directOutputOpen = false;
6843 for (size_t i = 0; i < mOutputs.size(); i++) {
6844 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6845 directOutputOpen = true;
6846 break;
6847 }
6848 }
6849 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006850 ALOGV("no direct outputs open, reset MSD patches");
6851 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6852 // how output devices for patching are resolved. Avoid by caching and reusing the
6853 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6854 // devices to patch to. This may be complicated by the fact that devices may become
6855 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006856 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006857 }
6858 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006859}
6860
6861void AudioPolicyManager::closeInput(audio_io_handle_t input)
6862{
6863 ALOGV("closeInput(%d)", input);
6864
6865 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6866 if (inputDesc == NULL) {
6867 ALOGW("closeInput() unknown input %d", input);
6868 return;
6869 }
6870
Eric Laurent6a94d692014-05-20 11:18:06 -07006871 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006872
François Gaffie11d30102018-11-02 16:09:09 +01006873 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006874 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006875 if (index >= 0) {
6876 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006877 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6878 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006879 mAudioPatches.removeItemsAt(index);
6880 mpClientInterface->onAudioPatchListUpdate();
6881 }
6882
François Gaffie6ebbce02023-07-19 13:27:53 +02006883 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006884 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006885 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006886
François Gaffie11d30102018-11-02 16:09:09 +01006887 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6888 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006889 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006890 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006891 }
Eric Laurente552edb2014-03-10 17:42:56 -07006892}
6893
François Gaffie11d30102018-11-02 16:09:09 +01006894SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6895 const DeviceVector &devices,
6896 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006897{
6898 SortedVector<audio_io_handle_t> outputs;
6899
François Gaffie11d30102018-11-02 16:09:09 +01006900 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006901 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006902 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006903 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006904 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006905 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006906 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006907 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006908 outputs.add(openOutputs.keyAt(i));
6909 }
6910 }
6911 return outputs;
6912}
6913
Mikhail Naganov37977152018-07-11 15:54:44 -07006914void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6915{
6916 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6917 // output is suspended before any tracks are moved to it
6918 checkA2dpSuspend();
6919 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006920 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006921 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006922 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006923 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006924 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6925 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6926 // configuration changes will ultimately be rerouted correctly. We can still avoid
6927 // unnecessary rerouting by caching and reusing the arguments to
6928 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6929 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006930 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006931 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006932 // an event that changed routing likely occurred, inform upper layers
6933 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006934}
6935
François Gaffiec005e562018-11-06 15:04:49 +01006936bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6937 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006938{
François Gaffiec005e562018-11-06 15:04:49 +01006939 return mEngine->getProductStrategyForAttributes(lAttr) ==
6940 mEngine->getProductStrategyForAttributes(rAttr);
6941}
6942
Francois Gaffieff1eb522020-05-06 18:37:04 +02006943void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6944{
6945 for (size_t i = 0; i < mAudioSources.size(); i++) {
6946 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6947 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006948 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006949 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006950 connectAudioSource(sourceDesc);
6951 }
6952 }
6953}
6954
6955void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6956{
6957 for (size_t i = 0; i < mAudioSources.size(); i++) {
6958 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6959 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6960 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6961 disconnectAudioSource(sourceDesc);
6962 }
6963 }
6964}
6965
François Gaffiec005e562018-11-06 15:04:49 +01006966void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6967{
6968 auto psId = mEngine->getProductStrategyForAttributes(attr);
6969
6970 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6971 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006972
François Gaffie11d30102018-11-02 16:09:09 +01006973 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6974 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006975
Eric Laurentc209fe42020-06-05 18:11:23 -07006976 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006977 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006978 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006979 // take into account dynamic audio policies related changes: if a client is now associated
6980 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006981 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006982 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6983 if (desc->isDuplicated()) {
6984 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006985 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006986 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6987 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6988 continue;
6989 }
6990 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006991 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006992 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6993 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6994 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006995 if (status != OK) {
6996 continue;
6997 }
yucliuf4de36d2020-09-14 14:57:56 -07006998 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006999 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007000 maxLatency = desc->latency();
7001 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007002 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007003 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007004 }
7005 }
7006
Eric Laurent56ed8842022-11-15 16:04:41 +01007007 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007008 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7009 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007010 for (audio_io_handle_t srcOut : srcOutputs) {
7011 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007012 if (desc == nullptr) continue;
7013
7014 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007015 maxLatency = desc->latency();
7016 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007017
Eric Laurent56ed8842022-11-15 16:04:41 +01007018 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007019 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007020 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007021 // a client on a non direct outputs has necessarily a linear PCM format
7022 // so we can call selectOutput() safely
7023 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7024 client->flags(),
7025 client->config().format,
7026 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007027 client->config().sample_rate,
7028 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007029 if (newOutput != srcOut) {
7030 invalidate = true;
7031 break;
7032 }
7033 } else {
7034 sp<IOProfile> profile = getProfileForOutput(newDevices,
7035 client->config().sample_rate,
7036 client->config().format,
7037 client->config().channel_mask,
7038 client->flags(),
7039 true /* directOnly */);
7040 if (profile != desc->mProfile) {
7041 invalidate = true;
7042 break;
7043 }
7044 }
7045 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007046 // mute strategy while moving tracks from one output to another
7047 if (invalidate) {
7048 invalidatedOutputs.push_back(desc);
7049 if (desc->isStrategyActive(psId)) {
7050 setStrategyMute(psId, true, desc);
7051 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7052 newDevices.types());
7053 }
Eric Laurente552edb2014-03-10 17:42:56 -07007054 }
François Gaffiec005e562018-11-06 15:04:49 +01007055 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007056 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007057 connectAudioSource(source);
7058 }
Eric Laurente552edb2014-03-10 17:42:56 -07007059 }
7060
Eric Laurent56ed8842022-11-15 16:04:41 +01007061 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7062 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7063 std::to_string(srcOutputs[0]).c_str(),
7064 std::to_string(dstOutputs[0]).c_str());
7065
François Gaffiec005e562018-11-06 15:04:49 +01007066 // Move effects associated to this stream from previous output to new output
7067 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007068 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007069 }
François Gaffiec005e562018-11-06 15:04:49 +01007070 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007071 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007072 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007073 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007074 desc->setTracksInvalidatedStatusByStrategy(psId);
7075 }
Eric Laurente552edb2014-03-10 17:42:56 -07007076 }
7077 }
7078}
7079
Eric Laurente0720872014-03-11 09:30:41 -07007080void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007081{
François Gaffiec005e562018-11-06 15:04:49 +01007082 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7083 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7084 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007085 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007086 }
Eric Laurente552edb2014-03-10 17:42:56 -07007087}
7088
Kevin Rocard153f92d2018-12-18 18:33:28 -08007089void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007090 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007091 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007092 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007093 for (size_t i = 0; i < mOutputs.size(); i++) {
7094 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7095 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007096 sp<AudioPolicyMix> primaryMix;
7097 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007098 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007099 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7100 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7101 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007102 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7103 for (auto &secondaryMix : secondaryMixes) {
7104 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7105 if (outputDesc != nullptr &&
7106 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7107 secondaryDescs.push_back(outputDesc);
7108 }
7109 }
7110
jiabinc44b3462022-12-08 12:52:31 -08007111 if (status != OK &&
7112 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7113 // When it failed to query secondary output, only invalidate the client that is not
7114 // MMAP. The reason is that MMAP stream will not support secondary output.
7115 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007116 } else if (!std::equal(
7117 client->getSecondaryOutputs().begin(),
7118 client->getSecondaryOutputs().end(),
7119 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007120 if (!audio_is_linear_pcm(client->config().format)) {
7121 // If the format is not PCM, the tracks should be invalidated to get correct
7122 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007123 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007124 } else {
7125 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7126 std::vector<audio_io_handle_t> secondaryOutputIds;
7127 for (const auto &secondaryDesc: secondaryDescs) {
7128 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7129 weakSecondaryDescs.push_back(secondaryDesc);
7130 }
7131 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7132 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007133 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007134 }
7135 }
7136 }
jiabin10a03f12021-05-07 23:46:28 +00007137 if (!trackSecondaryOutputs.empty()) {
7138 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7139 }
jiabinc44b3462022-12-08 12:52:31 -08007140 if (!clientsToInvalidate.empty()) {
7141 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7142 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007143 }
7144}
7145
Eric Laurent2517af32020-11-25 15:31:27 +01007146bool AudioPolicyManager::isScoRequestedForComm() const {
7147 AudioDeviceTypeAddrVector devices;
7148 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7149 for (const auto &device : devices) {
7150 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7151 return true;
7152 }
7153 }
7154 return false;
7155}
7156
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007157bool AudioPolicyManager::isHearingAidUsedForComm() const {
7158 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7159 true /*fromCache*/);
7160 for (const auto &device : devices) {
7161 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7162 return true;
7163 }
7164 }
7165 return false;
7166}
7167
7168
Eric Laurente0720872014-03-11 09:30:41 -07007169void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007170{
François Gaffie53615e22015-03-19 09:24:12 +01007171 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007172 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007173 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007174 return;
7175 }
7176
Eric Laurent3a4311c2014-03-17 12:00:47 -07007177 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007178 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7179 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007180 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007181
7182 // if suspended, restore A2DP output if:
7183 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007184 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007185 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007186 //
Eric Laurentf732e072016-08-03 19:30:28 -07007187 // if not suspended, suspend A2DP output if:
7188 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007189 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007190 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007191 //
7192 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007193 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007194 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007195 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007196 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007197
7198 mpClientInterface->restoreOutput(a2dpOutput);
7199 mA2dpSuspended = false;
7200 }
7201 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007202 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007203 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007204 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007205 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007206
7207 mpClientInterface->suspendOutput(a2dpOutput);
7208 mA2dpSuspended = true;
7209 }
7210 }
7211}
7212
François Gaffie11d30102018-11-02 16:09:09 +01007213DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7214 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007215{
François Gaffiedb1755b2023-09-01 11:50:35 +02007216 if (outputDesc == nullptr) {
7217 return DeviceVector{};
7218 }
François Gaffie11d30102018-11-02 16:09:09 +01007219
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007220 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007221 if (index >= 0) {
7222 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007223 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007224 ALOGV("%s device %s forced by patch %d", __func__,
7225 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7226 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007227 }
7228 }
7229
Dean Wheatley514b4312020-06-17 21:45:00 +10007230 // Do not retrieve engine device for outputs through MSD
7231 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7232 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7233 return outputDesc->devices();
7234 }
7235
Eric Laurent97ac8712018-07-27 18:59:02 -07007236 // Honor explicit routing requests only if no client using default routing is active on this
7237 // input: a specific app can not force routing for other apps by setting a preferred device.
7238 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007239 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007240 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007241 if (device != nullptr) {
7242 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007243 }
7244
François Gaffiea807ef92018-11-05 10:44:33 +01007245 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7246 // of setForceUse / Default Bus device here
7247 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7248 if (device != nullptr) {
7249 return DeviceVector(device);
7250 }
7251
François Gaffiedb1755b2023-09-01 11:50:35 +02007252 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007253 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7254 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7255 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307256 auto hasStreamActive = [&](auto stream) {
7257 return hasStream(streams, stream) && isStreamActive(stream, 0);
7258 };
Eric Laurent484e9272018-06-07 17:29:23 -07007259
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307260 auto doGetOutputDevicesForVoice = [&]() {
7261 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007262 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307263 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007264 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7265 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307266 };
7267
7268 // With low-latency playing on speaker, music on WFD, when the first low-latency
7269 // output is stopped, getNewOutputDevices checks for a product strategy
7270 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007271 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307272 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7273 // stream is associated to the output descriptor.
7274 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7275 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7276 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7277 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007278 // Retrieval of devices for voice DL is done on primary output profile, cannot
7279 // check the route (would force modifying configuration file for this profile)
7280 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7281 break;
7282 }
Eric Laurente552edb2014-03-10 17:42:56 -07007283 }
François Gaffiec005e562018-11-06 15:04:49 +01007284 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007285 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007286}
7287
François Gaffie11d30102018-11-02 16:09:09 +01007288sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7289 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007290{
François Gaffie11d30102018-11-02 16:09:09 +01007291 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007292
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007293 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007294 if (index >= 0) {
7295 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007296 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007297 ALOGV("getNewInputDevice() device %s forced by patch %d",
7298 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7299 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007300 }
7301 }
7302
Eric Laurent97ac8712018-07-27 18:59:02 -07007303 // Honor explicit routing requests only if no client using default routing is active on this
7304 // input: a specific app can not force routing for other apps by setting a preferred device.
7305 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007306 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7307 if (device != nullptr) {
7308 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007309 }
7310
Eric Laurentdc95a252018-04-12 12:46:56 -07007311 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007312 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007313 audio_attributes_t attributes;
7314 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007315 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007316 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7317 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007318 attributes = topClient->attributes();
7319 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007320 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007321 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007322 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7323 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007324 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007325 }
7326
Francois Gaffie716e1432019-01-14 16:58:59 +01007327 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7328 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007329 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007330 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007331 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007332 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007333
Eric Laurente552edb2014-03-10 17:42:56 -07007334 return device;
7335}
7336
Eric Laurent794fde22016-03-11 09:50:45 -08007337bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7338 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007339 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007340}
7341
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007342status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007343 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007344 if (devices == nullptr) {
7345 return BAD_VALUE;
7346 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007347
Andy Hung6d23c0f2022-02-16 09:37:15 -08007348 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007349 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7350 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007351 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007352 for (const auto& device : curDevices) {
7353 devices->push_back(device->getDeviceTypeAddr());
7354 }
7355 return NO_ERROR;
7356}
7357
Eric Laurente0720872014-03-11 09:30:41 -07007358void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007359 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007360 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007361 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007362 updateDevicesAndOutputs();
7363 break;
7364 default:
7365 break;
7366 }
7367}
7368
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007369uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007370
7371 // skip beacon mute management if a dedicated TTS output is available
7372 if (mTtsOutputAvailable) {
7373 return 0;
7374 }
7375
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007376 switch(event) {
7377 case STARTING_OUTPUT:
7378 mBeaconMuteRefCount++;
7379 break;
7380 case STOPPING_OUTPUT:
7381 if (mBeaconMuteRefCount > 0) {
7382 mBeaconMuteRefCount--;
7383 }
7384 break;
7385 case STARTING_BEACON:
7386 mBeaconPlayingRefCount++;
7387 break;
7388 case STOPPING_BEACON:
7389 if (mBeaconPlayingRefCount > 0) {
7390 mBeaconPlayingRefCount--;
7391 }
7392 break;
7393 }
7394
7395 if (mBeaconMuteRefCount > 0) {
7396 // any playback causes beacon to be muted
7397 return setBeaconMute(true);
7398 } else {
7399 // no other playback: unmute when beacon starts playing, mute when it stops
7400 return setBeaconMute(mBeaconPlayingRefCount == 0);
7401 }
7402}
7403
7404uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7405 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7406 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7407 // keep track of muted state to avoid repeating mute/unmute operations
7408 if (mBeaconMuted != mute) {
7409 // mute/unmute AUDIO_STREAM_TTS on all outputs
7410 ALOGV("\t muting %d", mute);
7411 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007412 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7413 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7414 ALOGV("\t no tts volume source available");
7415 return 0;
7416 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007417 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007418 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007419 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007420 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007421 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007422 maxLatency = latency;
7423 }
7424 }
7425 mBeaconMuted = mute;
7426 return maxLatency;
7427 }
7428 return 0;
7429}
7430
Eric Laurente0720872014-03-11 09:30:41 -07007431void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007432{
François Gaffiec005e562018-11-06 15:04:49 +01007433 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007434 mPreviousOutputs = mOutputs;
7435}
7436
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007437uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007438 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007439 uint32_t delayMs)
7440{
7441 // mute/unmute strategies using an incompatible device combination
7442 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7443 // if unmuting, unmute only after the specified delay
7444 if (outputDesc->isDuplicated()) {
7445 return 0;
7446 }
7447
7448 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007449 DeviceVector devices = outputDesc->devices();
7450 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007451
François Gaffiec005e562018-11-06 15:04:49 +01007452 auto productStrategies = mEngine->getOrderedProductStrategies();
7453 for (const auto &productStrategy : productStrategies) {
7454 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7455 DeviceVector curDevices =
7456 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7457 curDevices = curDevices.filter(outputDesc->supportedDevices());
7458 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007459 bool doMute = false;
7460
François Gaffiec005e562018-11-06 15:04:49 +01007461 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007462 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007463 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7464 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007465 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007466 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007467 }
Eric Laurent99401132014-05-07 19:48:15 -07007468 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007469 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007470 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007471 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007472 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007473 continue;
7474 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307475 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007476 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7477 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7478 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007479 if (mute) {
7480 // FIXME: should not need to double latency if volume could be applied
7481 // immediately by the audioflinger mixer. We must account for the delay
7482 // between now and the next time the audioflinger thread for this output
7483 // will process a buffer (which corresponds to one buffer size,
7484 // usually 1/2 or 1/4 of the latency).
7485 if (muteWaitMs < desc->latency() * 2) {
7486 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007487 }
7488 }
7489 }
7490 }
7491 }
7492 }
7493
Eric Laurent99401132014-05-07 19:48:15 -07007494 // temporary mute output if device selection changes to avoid volume bursts due to
7495 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007496 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007497 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007498
Eric Laurentdc462862016-07-19 12:29:53 -07007499 if (muteWaitMs < tempMuteWaitMs) {
7500 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007501 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007502
7503 // If recommended duration is defined, replace temporary mute duration to avoid
7504 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7505 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7506 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7507 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7508 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7509
François Gaffieaaac0fd2018-11-22 17:56:39 +01007510 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7511 // make sure that we do not start the temporary mute period too early in case of
7512 // delayed device change
7513 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7514 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007515 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007516 }
7517 }
7518
Eric Laurente552edb2014-03-10 17:42:56 -07007519 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7520 if (muteWaitMs > delayMs) {
7521 muteWaitMs -= delayMs;
7522 usleep(muteWaitMs * 1000);
7523 return muteWaitMs;
7524 }
7525 return 0;
7526}
7527
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307528uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7529 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007530 const DeviceVector &devices,
7531 bool force,
7532 int delayMs,
7533 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007534 bool requiresMuteCheck, bool requiresVolumeCheck,
7535 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007536{
jiabin3ff8d7d2022-12-13 06:27:44 +00007537 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307538 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7539 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7540 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007541 uint32_t muteWaitMs;
7542
7543 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307544 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007545 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307546 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007547 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007548 return muteWaitMs;
7549 }
Eric Laurente552edb2014-03-10 17:42:56 -07007550
7551 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007552 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007553 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007554 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007555
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307556 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7557 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007558
7559 if (!filteredDevices.isEmpty()) {
7560 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007561 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007562
7563 // if the outputs are not materially active, there is no need to mute.
7564 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007565 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007566 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307567 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7568 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007569 muteWaitMs = 0;
7570 }
Eric Laurente552edb2014-03-10 17:42:56 -07007571
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007572 bool outputRouted = outputDesc->isRouted();
7573
Eric Laurent79ea9582020-06-11 18:49:24 -07007574 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7575 // output profile or if new device is not supported AND previous device(s) is(are) still
7576 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007577 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307578 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7579 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007580 // restore previous device after evaluating strategy mute state
7581 outputDesc->setDevices(prevDevices);
7582 return muteWaitMs;
7583 }
7584
Eric Laurente552edb2014-03-10 17:42:56 -07007585 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007586 // the requested device is AUDIO_DEVICE_NONE
7587 // OR the requested device is the same as current device
7588 // AND force is not specified
7589 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007590 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007591 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307592 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7593 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7594 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007595 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307596 ALOGV("%s %s setting same device on routed output, force apply volumes",
7597 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007598 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7599 }
Eric Laurente552edb2014-03-10 17:42:56 -07007600 return muteWaitMs;
7601 }
7602
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307603 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7604 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007605
Eric Laurente552edb2014-03-10 17:42:56 -07007606 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007607 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007608 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007609 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007610 PatchBuilder patchBuilder;
7611 patchBuilder.addSource(outputDesc);
7612 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7613 for (const auto &filteredDevice : filteredDevices) {
7614 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007615 }
7616
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007617 // Add half reported latency to delayMs when muteWaitMs is null in order
7618 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007619 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7620 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7621 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007622 }
Eric Laurente552edb2014-03-10 17:42:56 -07007623
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007624 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7625 if (!skipMuteDelay) {
7626 // update stream volumes according to new device
7627 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7628 }
Eric Laurente552edb2014-03-10 17:42:56 -07007629
7630 return muteWaitMs;
7631}
7632
Eric Laurentc75307b2015-03-17 15:29:32 -07007633status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007634 int delayMs,
7635 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007636{
Eric Laurent6a94d692014-05-20 11:18:06 -07007637 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007638 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7639 return INVALID_OPERATION;
7640 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007641 if (patchHandle) {
7642 index = mAudioPatches.indexOfKey(*patchHandle);
7643 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007644 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007645 }
7646 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007647 return INVALID_OPERATION;
7648 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007649 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007650 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007651 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007652 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007653 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007654 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007655 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007656 return status;
7657}
7658
7659status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007660 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007661 bool force,
7662 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007663{
7664 status_t status = NO_ERROR;
7665
Eric Laurent1f2f2232014-06-02 12:01:23 -07007666 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007667 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7668 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007669
François Gaffie11d30102018-11-02 16:09:09 +01007670 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007671 PatchBuilder patchBuilder;
7672 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007673 // AUDIO_SOURCE_HOTWORD is for internal use only:
7674 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007675 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7676 auto result = usecase;
7677 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7678 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7679 }
7680 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007681 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007682 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007683 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007684 }
7685 }
7686 return status;
7687}
7688
Eric Laurent6a94d692014-05-20 11:18:06 -07007689status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7690 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007691{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007692 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007693 ssize_t index;
7694 if (patchHandle) {
7695 index = mAudioPatches.indexOfKey(*patchHandle);
7696 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007697 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007698 }
7699 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007700 return INVALID_OPERATION;
7701 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007702 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007703 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007704 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007705 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007706 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007707 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007708 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007709 return status;
7710}
7711
François Gaffie11d30102018-11-02 16:09:09 +01007712sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007713 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007714 audio_format_t& format,
7715 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007716 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007717{
7718 // Choose an input profile based on the requested capture parameters: select the first available
7719 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007720 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007721 //
7722 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7723 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007724
Atneya Nair0f0a8032022-12-12 16:20:12 -08007725 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7726 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7727 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7728
7729 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007730
jiabin2fd710d2022-05-02 23:20:22 +00007731 for (;;) {
7732 sp<IOProfile> firstInexact = nullptr;
7733 uint32_t updatedSamplingRate = 0;
7734 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7735 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7736 for (const auto& hwModule : mHwModules) {
7737 for (const auto& profile : hwModule->getInputProfiles()) {
7738 // profile->log();
7739 //updatedFormat = format;
7740 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7741 &samplingRate /*updatedSamplingRate*/,
7742 format,
7743 &format, /*updatedFormat*/
7744 channelMask,
7745 &channelMask /*updatedChannelMask*/,
7746 // FIXME ugly cast
7747 (audio_output_flags_t) flags,
7748 true /*exactMatchRequiredForInputFlags*/)) {
7749 return profile;
7750 }
7751 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7752 samplingRate,
7753 &updatedSamplingRate,
7754 format,
7755 &updatedFormat,
7756 channelMask,
7757 &updatedChannelMask,
7758 // FIXME ugly cast
7759 (audio_output_flags_t) flags,
7760 false /*exactMatchRequiredForInputFlags*/)) {
7761 firstInexact = profile;
7762 }
7763 }
7764 }
7765
7766 if (firstInexact != nullptr) {
7767 samplingRate = updatedSamplingRate;
7768 format = updatedFormat;
7769 channelMask = updatedChannelMask;
7770 return firstInexact;
7771 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7772 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7773 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7774 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7775 flags = AUDIO_INPUT_FLAG_NONE;
7776 } else { // fail
7777 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7778 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7779 samplingRate, format, channelMask, oriFlags);
7780 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007781 }
7782 }
jiabin2fd710d2022-05-02 23:20:22 +00007783
7784 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007785}
7786
François Gaffieaaac0fd2018-11-22 17:56:39 +01007787float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7788 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007789 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007790 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007791{
jiabin9a3361e2019-10-01 09:38:30 -07007792 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007793
7794 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7795 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7796 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7797 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007798 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7799 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7800 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7801 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7802 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007803 // Verify that the current volume source is not the ringer volume to prevent recursively
7804 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7805 // to the same volume group.
7806 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007807 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7808 mOutputs.isActive(ringVolumeSrc, 0)) {
7809 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007810 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007811 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007812 }
7813
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007814 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007815 if ((volumeSource != callVolumeSrc && (isInCall() ||
7816 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007817 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007818 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7819 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007820 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7821 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7822 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007823 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007824 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007825 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007826 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007827 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007828 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007829 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7830 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7831 // programmatically muted.
7832 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7833 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7834 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007835 bool exemptFromCapping =
7836 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7837 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007838 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7839 volumeSource, volumeDb);
7840 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007841 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7842 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7843 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007844 }
7845 }
Eric Laurente552edb2014-03-10 17:42:56 -07007846 // if a headset is connected, apply the following rules to ring tones and notifications
7847 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007848 // - always attenuate notifications volume by 6dB
7849 // - attenuate ring tones volume by 6dB unless music is not playing and
7850 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007851 // - if music is playing, always limit the volume to current music volume,
7852 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007853 if (!Intersection(deviceTypes,
7854 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7855 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007856 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7857 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007858 ((volumeSource == alarmVolumeSrc ||
7859 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007860 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7861 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7862 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007863 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7864 curves.canBeMuted()) {
7865
Eric Laurente552edb2014-03-10 17:42:56 -07007866 // when the phone is ringing we must consider that music could have been paused just before
7867 // by the music application and behave as if music was active if the last music track was
7868 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007869 // Verify that the current volume source is not the music volume to prevent recursively
7870 // calling to compute volume. This could happen in cases where music and
7871 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7872 if (volumeSource != musicVolumeSrc &&
7873 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7874 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007875 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007876 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007877 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7878 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007879 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007880 float musicVolDb = computeVolume(musicCurves,
7881 musicVolumeSrc,
7882 musicCurves.getVolumeIndex(musicDevice),
7883 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007884 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7885 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7886 if (volumeDb > minVolDb) {
7887 volumeDb = minVolDb;
7888 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007889 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007890 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7891 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7892 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007893 // on A2DP, also ensure notification volume is not too low compared to media when
7894 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007895 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007896 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007897 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7898 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007899 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7900 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007901 }
7902 }
jiabin9a3361e2019-10-01 09:38:30 -07007903 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007904 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007905 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007906 }
7907 }
7908
François Gaffie43c73442018-11-08 08:21:55 +01007909 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007910}
7911
Eric Laurent3839bc02018-07-10 18:33:34 -07007912int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007913 VolumeSource fromVolumeSource,
7914 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007915{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007916 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007917 return srcIndex;
7918 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007919 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7920 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007921 float minSrc = (float)srcCurves.getVolumeIndexMin();
7922 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7923 float minDst = (float)dstCurves.getVolumeIndexMin();
7924 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007925
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007926 // preserve mute request or correct range
7927 if (srcIndex < minSrc) {
7928 if (srcIndex == 0) {
7929 return 0;
7930 }
7931 srcIndex = minSrc;
7932 } else if (srcIndex > maxSrc) {
7933 srcIndex = maxSrc;
7934 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007935 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7936}
7937
François Gaffieaaac0fd2018-11-22 17:56:39 +01007938status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7939 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007940 int index,
7941 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007942 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007943 int delayMs,
7944 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007945{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007946 // do not change actual attributes volume if the attributes is muted
7947 if (outputDesc->isMuted(volumeSource)) {
7948 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7949 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007950 return NO_ERROR;
7951 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007952
Eric Laurentae6e88c2024-01-10 14:42:57 +01007953 bool isVoiceVolSrc;
7954 bool isBtScoVolSrc;
7955 if (!isVolumeConsistentForCalls(
7956 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07007957 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01007958 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07007959 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007960 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01007961
jiabin9a3361e2019-10-01 09:38:30 -07007962 if (deviceTypes.empty()) {
7963 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007964 index = curves.getVolumeIndex(deviceTypes);
7965 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7966 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007967 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007968
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007969 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7970 ALOGE("invalid volume index range");
7971 return BAD_VALUE;
7972 }
7973
jiabin9a3361e2019-10-01 09:38:30 -07007974 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7975 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007976 // Force VoIP volume to max for bluetooth SCO device except if muted
7977 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007978 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007979 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007980 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007981 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007982 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7983 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007984
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007985 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01007986 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007987 }
Eric Laurente552edb2014-03-10 17:42:56 -07007988 return NO_ERROR;
7989}
7990
Eric Laurentae6e88c2024-01-10 14:42:57 +01007991void AudioPolicyManager::setVoiceVolume(
7992 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
7993 float voiceVolume;
7994 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
7995 // by the headset
7996 if (isVoiceVolSrc) {
7997 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
7998 } else {
7999 voiceVolume = index == 0 ? 0.0 : 1.0;
8000 }
8001 if (voiceVolume != mLastVoiceVolume) {
8002 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8003 mLastVoiceVolume = voiceVolume;
8004 }
8005}
8006
8007bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8008 const DeviceTypeSet& deviceTypes,
8009 bool& isVoiceVolSrc,
8010 bool& isBtScoVolSrc,
8011 const char* caller) {
8012 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8013 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8014 const bool isScoRequested = isScoRequestedForComm();
8015 const bool isHAUsed = isHearingAidUsedForComm();
8016
8017 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8018 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8019
8020 if ((callVolSrc != btScoVolSrc) &&
8021 ((isVoiceVolSrc && isScoRequested) ||
8022 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8023 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8024 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8025 volumeSource, isScoRequested ? " " : " not ");
8026 return false;
8027 }
8028 return true;
8029}
8030
Eric Laurentc75307b2015-03-17 15:29:32 -07008031void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008032 const DeviceTypeSet& deviceTypes,
8033 int delayMs,
8034 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008035{
jiabincd510522020-01-22 09:40:55 -08008036 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008037 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8038 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8039 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008040 curves.getVolumeIndex(deviceTypes),
8041 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008042 }
8043}
8044
François Gaffiec005e562018-11-06 15:04:49 +01008045void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8046 bool on,
8047 const sp<AudioOutputDescriptor>& outputDesc,
8048 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008049 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008050{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008051 std::vector<VolumeSource> sourcesToMute;
8052 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8053 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8054 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008055 VolumeSource source = toVolumeSource(attributes, false);
8056 if ((source != VOLUME_SOURCE_NONE) &&
8057 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8058 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008059 sourcesToMute.push_back(source);
8060 }
Eric Laurente552edb2014-03-10 17:42:56 -07008061 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008062 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008063 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008064 }
8065
Eric Laurente552edb2014-03-10 17:42:56 -07008066}
8067
François Gaffieaaac0fd2018-11-22 17:56:39 +01008068void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8069 bool on,
8070 const sp<AudioOutputDescriptor>& outputDesc,
8071 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008072 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008073{
jiabin9a3361e2019-10-01 09:38:30 -07008074 if (deviceTypes.empty()) {
8075 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008076 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008077 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008078 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008079 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008080 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008081 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008082 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8083 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008084 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008085 }
8086 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008087 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8088 // ignored
8089 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008090 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008091 if (!outputDesc->isMuted(volumeSource)) {
8092 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008093 return;
8094 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008095 if (outputDesc->decMuteCount(volumeSource) == 0) {
8096 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008097 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008098 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008099 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008100 delayMs);
8101 }
8102 }
8103}
8104
François Gaffie53615e22015-03-19 09:24:12 +01008105bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8106{
François Gaffiec005e562018-11-06 15:04:49 +01008107 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008108 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8109 return true;
8110 }
8111
8112 // has known usage?
8113 switch (paa->usage) {
8114 case AUDIO_USAGE_UNKNOWN:
8115 case AUDIO_USAGE_MEDIA:
8116 case AUDIO_USAGE_VOICE_COMMUNICATION:
8117 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8118 case AUDIO_USAGE_ALARM:
8119 case AUDIO_USAGE_NOTIFICATION:
8120 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8121 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8122 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8123 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8124 case AUDIO_USAGE_NOTIFICATION_EVENT:
8125 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8126 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8127 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8128 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008129 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008130 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008131 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008132 case AUDIO_USAGE_EMERGENCY:
8133 case AUDIO_USAGE_SAFETY:
8134 case AUDIO_USAGE_VEHICLE_STATUS:
8135 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008136 break;
8137 default:
8138 return false;
8139 }
8140 return true;
8141}
8142
François Gaffie2110e042015-03-24 08:41:51 +01008143audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8144{
8145 return mEngine->getForceUse(usage);
8146}
8147
Eric Laurent96d1dda2022-03-14 17:14:19 +01008148bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008149 return isStateInCall(mEngine->getPhoneState());
8150}
8151
Eric Laurent96d1dda2022-03-14 17:14:19 +01008152bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008153 return is_state_in_call(state);
8154}
8155
Eric Laurentf9cccec2022-11-16 19:12:00 +01008156bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008157 audio_mode_t mode = mEngine->getPhoneState();
8158 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008159 || (mode == AUDIO_MODE_CALL_SCREEN)
8160 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008161}
8162
Eric Laurentf9cccec2022-11-16 19:12:00 +01008163bool AudioPolicyManager::isInCallOrScreening() const {
8164 audio_mode_t mode = mEngine->getPhoneState();
8165 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8166}
8167
Eric Laurentd60560a2015-04-10 11:31:20 -07008168void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8169{
8170 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008171 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008172 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008173 sourceDesc->sinkDevice()->equals(deviceDesc))
8174 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008175 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008176 }
8177 }
8178
8179 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8180 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8181 bool release = false;
8182 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8183 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8184 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8185 source->ext.device.type == deviceDesc->type()) {
8186 release = true;
8187 }
8188 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008189 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008190 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8191 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8192 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008193 sink->ext.device.type == deviceDesc->type() &&
8194 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8195 || strncmp(sink->ext.device.address, address,
8196 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008197 release = true;
8198 }
8199 }
8200 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008201 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8202 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008203 }
8204 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008205
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008206 mInputs.clearSessionRoutesForDevice(deviceDesc);
8207
Francois Gaffie716e1432019-01-14 16:58:59 +01008208 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008209}
8210
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008211void AudioPolicyManager::modifySurroundFormats(
8212 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008213 std::unordered_set<audio_format_t> enforcedSurround(
8214 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008215 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008216 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008217 allSurround.insert(pair.first);
8218 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8219 }
Phil Burk09bc4612016-02-24 15:58:15 -08008220
8221 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8222 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008223 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008224 // This is the resulting set of formats depending on the surround mode:
8225 // 'all surround' = allSurround
8226 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8227 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8228 // 'manual surround' = mManualSurroundFormats
8229 // AUTO: formats v 'enforced surround'
8230 // ALWAYS: formats v 'all surround' v 'enforced surround'
8231 // NEVER: formats ^ 'non-surround'
8232 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008233
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008234 std::unordered_set<audio_format_t> formatSet;
8235 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8236 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008237 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008238 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008239 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008240 formatSet.insert(*formatIter);
8241 }
8242 }
8243 } else {
8244 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8245 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008246 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008247
jiabin81772902018-04-02 17:52:27 -07008248 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008249 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008250 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8251 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8252 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008253 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008254 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8255 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8256 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008257 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008258 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008259 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008260 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008261 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008262 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008263}
8264
jiabin06e4bab2019-07-29 10:13:34 -07008265void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8266 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008267 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8268 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8269
8270 // If NEVER, then remove support for channelMasks > stereo.
8271 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008272 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8273 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008274 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008275 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008276 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008277 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008278 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008279 }
8280 }
jiabin81772902018-04-02 17:52:27 -07008281 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8282 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8283 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008284 bool supports5dot1 = false;
8285 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008286 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008287 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8288 supports5dot1 = true;
8289 break;
8290 }
8291 }
8292 // If not then add 5.1 support.
8293 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008294 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008295 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008296 }
Phil Burk09bc4612016-02-24 15:58:15 -08008297 }
8298}
8299
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008300void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008301 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008302 const sp<IOProfile>& profile) {
8303 if (!profile->hasDynamicAudioProfile()) {
8304 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008305 }
François Gaffie112b0af2015-11-19 16:13:25 +01008306
jiabin12537fc2023-10-12 17:56:08 +00008307 audio_port_v7 devicePort;
8308 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008309
jiabin12537fc2023-10-12 17:56:08 +00008310 audio_port_v7 mixPort;
8311 profile->toAudioPort(&mixPort);
8312 mixPort.ext.mix.handle = ioHandle;
8313
8314 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8315 if (status != NO_ERROR) {
8316 ALOGE("%s failed to query the attributes of the mix port", __func__);
8317 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008318 }
jiabin12537fc2023-10-12 17:56:08 +00008319
8320 std::set<audio_format_t> supportedFormats;
8321 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8322 supportedFormats.insert(mixPort.audio_profiles[i].format);
8323 }
8324 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8325 mReportedFormatsMap[devDesc] = formats;
8326
8327 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8328 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8329 modifySurroundFormats(devDesc, &formats);
8330 size_t modifiedNumProfiles = 0;
8331 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8332 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8333 formats.end()) {
8334 // Skip the format that is not present after modifying surround formats.
8335 continue;
8336 }
8337 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8338 sizeof(struct audio_profile));
8339 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8340 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8341 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8342 modifySurroundChannelMasks(&channels);
8343 std::copy(channels.begin(), channels.end(),
8344 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8345 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8346 }
8347 mixPort.num_audio_profiles = modifiedNumProfiles;
8348 }
8349 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008350}
Eric Laurentd60560a2015-04-10 11:31:20 -07008351
Mikhail Naganovdc769682018-05-04 15:34:08 -07008352status_t AudioPolicyManager::installPatch(const char *caller,
8353 audio_patch_handle_t *patchHandle,
8354 AudioIODescriptorInterface *ioDescriptor,
8355 const struct audio_patch *patch,
8356 int delayMs)
8357{
8358 ssize_t index = mAudioPatches.indexOfKey(
8359 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8360 *patchHandle : ioDescriptor->getPatchHandle());
8361 sp<AudioPatch> patchDesc;
8362 status_t status = installPatch(
8363 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8364 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008365 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008366 }
8367 return status;
8368}
8369
8370status_t AudioPolicyManager::installPatch(const char *caller,
8371 ssize_t index,
8372 audio_patch_handle_t *patchHandle,
8373 const struct audio_patch *patch,
8374 int delayMs,
8375 uid_t uid,
8376 sp<AudioPatch> *patchDescPtr)
8377{
8378 sp<AudioPatch> patchDesc;
8379 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8380 if (index >= 0) {
8381 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008382 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008383 }
8384
8385 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8386 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8387 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8388 if (status == NO_ERROR) {
8389 if (index < 0) {
8390 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008391 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008392 } else {
8393 patchDesc->mPatch = *patch;
8394 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008395 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008396 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008397 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008398 }
8399 nextAudioPortGeneration();
8400 mpClientInterface->onAudioPatchListUpdate();
8401 }
8402 if (patchDescPtr) *patchDescPtr = patchDesc;
8403 return status;
8404}
8405
jiabinbce0c1d2020-10-05 11:20:18 -07008406bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8407{
8408 const TrackClientVector activeClients = output->getActiveClients();
8409 if (activeClients.empty()) {
8410 return true;
8411 }
8412 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8413 if (index < 0) {
8414 ALOGE("%s, no audio patch found while there are active clients on output %d",
8415 __func__, output->getId());
8416 return false;
8417 }
8418 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8419 DeviceVector routedDevices;
8420 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8421 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8422 patchDesc->mPatch.sinks[i].id);
8423 if (device == nullptr) {
8424 ALOGE("%s, no audio device found with id(%d)",
8425 __func__, patchDesc->mPatch.sinks[i].id);
8426 return false;
8427 }
8428 routedDevices.add(device);
8429 }
8430 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008431 if (client->isInvalid()) {
8432 // No need to take care about invalidated clients.
8433 continue;
8434 }
jiabinbce0c1d2020-10-05 11:20:18 -07008435 sp<DeviceDescriptor> preferredDevice =
8436 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8437 if (mEngine->getOutputDevicesForAttributes(
8438 client->attributes(), preferredDevice, false) == routedDevices) {
8439 return false;
8440 }
8441 }
8442 return true;
8443}
8444
8445sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008446 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008447 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8448 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008449{
8450 for (const auto& device : devices) {
8451 // TODO: This should be checking if the profile supports the device combo.
8452 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008453 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8454 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008455 return nullptr;
8456 }
8457 }
8458 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8459 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008460 status_t status = desc->open(halConfig, mixerConfig, devices,
8461 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008462 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008463 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008464 return nullptr;
8465 }
jiabin14b50cc2023-12-13 19:01:52 +00008466 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8467 auto portConfig = desc->getConfig();
8468 for (const auto& device : devices) {
8469 device->setPreferredConfig(&portConfig);
8470 }
8471 }
jiabinbce0c1d2020-10-05 11:20:18 -07008472
8473 // Here is where the out_set_parameters() for card & device gets called
8474 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8475 const audio_devices_t deviceType = device->type();
8476 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008477 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008478 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8479 mpClientInterface->setParameters(output, String8(param));
8480 free(param);
8481 }
jiabin12537fc2023-10-12 17:56:08 +00008482 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008483 if (!profile->hasValidAudioProfile()) {
8484 ALOGW("%s() missing param", __func__);
8485 desc->close();
8486 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008487 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8488 // Reopen the output with the best audio profile picked by APM when the profile supports
8489 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008490 desc->close();
8491 output = AUDIO_IO_HANDLE_NONE;
8492 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8493 profile->pickAudioProfile(
8494 config.sample_rate, config.channel_mask, config.format);
8495 config.offload_info.sample_rate = config.sample_rate;
8496 config.offload_info.channel_mask = config.channel_mask;
8497 config.offload_info.format = config.format;
8498
jiabina84c3d32022-12-02 18:59:55 +00008499 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008500 if (status != NO_ERROR) {
8501 return nullptr;
8502 }
8503 }
8504
8505 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008506
baek.kim -61c20122022-07-27 10:05:32 +00008507 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8508 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8509
jiabinbce0c1d2020-10-05 11:20:18 -07008510 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8511 sp<AudioPolicyMix> policyMix;
8512 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8513 policyMix->setOutput(desc);
8514 desc->mPolicyMix = policyMix;
8515 } else {
8516 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008517 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008518 }
8519
baek.kim -61c20122022-07-27 10:05:32 +00008520 } else if (hasPrimaryOutput() && speaker != nullptr
8521 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008522 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8523 // no duplicated output for:
8524 // - direct outputs
8525 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008526 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008527 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8528
8529 //TODO: configure audio effect output stage here
8530
8531 // open a duplicating output thread for the new output and the primary output
8532 sp<SwAudioOutputDescriptor> dupOutputDesc =
8533 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8534 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8535 if (status == NO_ERROR) {
8536 // add duplicated output descriptor
8537 addOutput(duplicatedOutput, dupOutputDesc);
8538 } else {
8539 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8540 mPrimaryOutput->mIoHandle, output);
8541 desc->close();
8542 removeOutput(output);
8543 nextAudioPortGeneration();
8544 return nullptr;
8545 }
8546 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008547 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8548 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8549 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008550 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008551 }
jiabinbce0c1d2020-10-05 11:20:18 -07008552 return desc;
8553}
8554
jiabinf1c73972022-04-14 16:28:52 -07008555status_t AudioPolicyManager::getDevicesForAttributes(
8556 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8557 // Devices are determined in the following precedence:
8558 //
8559 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8560 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8561 //
8562 // If no such dynamic policy then
8563 // 2) Devices containing an active client using setPreferredDevice
8564 // with same strategy as the attributes.
8565 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8566 //
8567 // If no corresponding active client with setPreferredDevice then
8568 // 3) Devices associated with the strategy determined by the attributes
8569 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8570 //
8571 // See related getOutputForAttrInt().
8572
8573 // check dynamic policies but only for primary descriptors (secondary not used for audible
8574 // audio routing, only used for duplication for playback capture)
8575 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008576 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008577 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008578 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8579 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8580 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008581 if (status != OK) {
8582 return status;
8583 }
8584
8585 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8586 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8587 // as they are unaffected by device/stream volume
8588 // (per SwAudioOutputDescriptor::isFixedVolume()).
8589 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8590 ) {
8591 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8592 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8593 devices.add(deviceDesc);
8594 } else {
8595 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8596 // which selects setPreferredDevice if active. This means forVolume call
8597 // will take an active setPreferredDevice, if such exists.
8598
8599 devices = mEngine->getOutputDevicesForAttributes(
8600 attr, nullptr /* preferredDevice */, false /* fromCache */);
8601 }
8602
8603 if (forVolume) {
8604 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8605 // for single volume control in AudioService (such relationship should exist if
8606 // SPEAKER_SAFE is present).
8607 //
8608 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8609 DeviceVector speakerSafeDevices =
8610 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8611 if (!speakerSafeDevices.isEmpty()) {
8612 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8613 devices.remove(speakerSafeDevices);
8614 }
8615 }
8616
8617 return NO_ERROR;
8618}
8619
8620status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8621 AudioProfileVector& audioProfiles,
8622 uint32_t flags,
8623 bool isInput) {
8624 for (const auto& hwModule : mHwModules) {
8625 // the MSD module checks for different conditions
8626 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8627 continue;
8628 }
8629 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8630 : hwModule->getOutputProfiles();
8631 for (const auto& profile : ioProfiles) {
8632 if (!profile->areAllDevicesSupported(devices) ||
8633 !profile->isCompatibleProfileForFlags(
8634 flags, false /*exactMatchRequiredForInputFlags*/)) {
8635 continue;
8636 }
8637 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8638 }
8639 }
8640
8641 if (!isInput) {
8642 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8643 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8644 if (msdModule != nullptr) {
8645 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8646 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8647 for (const auto &profile: msdModule->getOutputProfiles()) {
8648 if (!profile->asAudioPort()->isDirectOutput()) {
8649 continue;
8650 }
8651 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8652 }
8653 } else {
8654 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8655 }
8656 }
8657 }
8658
8659 return NO_ERROR;
8660}
8661
jiabin3ff8d7d2022-12-13 06:27:44 +00008662sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8663 const audio_config_t *config,
8664 audio_output_flags_t flags,
8665 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008666 closeOutput(outputDesc->mIoHandle);
8667 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8668 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8669 if (preferredOutput == nullptr) {
8670 ALOGE("%s failed to reopen output device=%d, caller=%s",
8671 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008672 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008673 return preferredOutput;
8674}
8675
8676void AudioPolicyManager::reopenOutputsWithDevices(
8677 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8678 for (const auto& [output, devices] : outputsToReopen) {
8679 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8680 closeOutput(output);
8681 openOutputWithProfileAndDevice(desc->mProfile, devices);
8682 }
jiabina84c3d32022-12-02 18:59:55 +00008683}
8684
jiabinc44b3462022-12-08 12:52:31 -08008685PortHandleVector AudioPolicyManager::getClientsForStream(
8686 audio_stream_type_t streamType) const {
8687 PortHandleVector clients;
8688 for (size_t i = 0; i < mOutputs.size(); ++i) {
8689 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8690 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8691 }
8692 return clients;
8693}
8694
8695void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8696 PortHandleVector clients;
8697 for (auto stream : streams) {
8698 PortHandleVector clientsForStream = getClientsForStream(stream);
8699 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8700 }
8701 mpClientInterface->invalidateTracks(clients);
8702}
8703
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008704} // namespace android