blob: 6a104691a40bbda7e4eb198b9cca909c87b5e27a [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070044#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070045#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070047#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070049#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070050#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070051#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070052#include <utils/Log.h>
53
Eric Laurentd4692962014-05-05 18:13:44 -070054#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010055#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010059using android::media::audio::common::AudioDevice;
60using android::media::audio::common::AudioDeviceAddress;
61using android::media::audio::common::AudioPortDeviceExt;
62using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000063using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070064
Eric Laurentdc462862016-07-19 12:29:53 -070065//FIXME: workaround for truncated touch sounds
66// to be removed when the problem is handled by system UI
67#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070068
69// Largest difference in dB on earpiece in call between the voice volume and another
70// media / notification / system volume.
71constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
72
jiabin06e4bab2019-07-29 10:13:34 -070073template <typename T>
74bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
75{
76 if (left.size() != right.size()) {
77 return false;
78 }
79 for (size_t index = 0; index < right.size(); index++) {
80 if (left[index] != right[index]) {
81 return false;
82 }
83 }
84 return true;
85}
86
87template <typename T>
88bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
89{
90 return !(left == right);
91}
92
Eric Laurente552edb2014-03-10 17:42:56 -070093// ----------------------------------------------------------------------------
94// AudioPolicyInterface implementation
95// ----------------------------------------------------------------------------
96
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010097status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
98 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
99 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800100 nextAudioPortGeneration();
101 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800102}
103
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100104status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
105 audio_policy_dev_state_t state,
106 const char* device_address,
107 const char* device_name,
108 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800109 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
111 status == OK) {
112 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
113 } else {
114 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
115 return status;
116 }
117}
118
François Gaffie11d30102018-11-02 16:09:09 +0100119void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000120 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200121{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000122 audio_port_v7 devicePort;
123 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000124 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000125 status != OK) {
Mikhail Naganov3754b642024-04-17 18:31:04 +0000126 ALOGE("Error %d while setting connected state %d for device %s",
127 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 device->getDeviceTypeAddr().toString(false).c_str());
129 }
François Gaffie44481e72016-04-20 07:49:57 +0200130}
131
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100132status_t AudioPolicyManager::setDeviceConnectionStateInt(
133 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
134 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100135 if (port.ext.getTag() != AudioPortExt::device) {
136 return BAD_VALUE;
137 }
138 audio_devices_t device_type;
139 std::string device_address;
140 if (status_t status = aidl2legacy_AudioDevice_audio_device(
141 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
142 status != OK) {
143 return status;
144 };
145 const char* device_name = port.name.c_str();
146 // connect/disconnect only 1 device at a time
147 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
148 return BAD_VALUE;
149
150 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
151 device_type, device_address.c_str(), device_name, encodedFormat,
152 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000153 if (device == nullptr) {
154 return INVALID_OPERATION;
155 }
156 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
157 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
158 }
159 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100160}
161
François Gaffie11d30102018-11-02 16:09:09 +0100162status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800163 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100164 const char* device_address,
165 const char* device_name,
166 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800167 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100168 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
169 status == OK) {
170 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
171 } else {
172 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
173 return status;
174 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700175}
Paul McLeane743a472015-01-28 11:07:31 -0800176
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700177status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
178 audio_policy_dev_state_t state)
179{
Eric Laurente552edb2014-03-10 17:42:56 -0700180 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700182 SortedVector <audio_io_handle_t> outputs;
183
François Gaffie11d30102018-11-02 16:09:09 +0100184 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700185
Eric Laurente552edb2014-03-10 17:42:56 -0700186 // save a copy of the opened output descriptors before any output is opened or closed
187 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
188 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100189
190 bool wasLeUnicastActive = isLeUnicastActive();
191
Eric Laurente552edb2014-03-10 17:42:56 -0700192 switch (state)
193 {
194 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800195 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700196 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100197 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700198 return INVALID_OPERATION;
199 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800200 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700201 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700202
Eric Laurente552edb2014-03-10 17:42:56 -0700203 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200204 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700205 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700206 }
207
François Gaffie44481e72016-04-20 07:49:57 +0200208 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
209 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000210 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200211
François Gaffie11d30102018-11-02 16:09:09 +0100212 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
213 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200214
jiabinc0048632023-04-27 22:04:31 +0000215 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganov3754b642024-04-17 18:31:04 +0000216
217 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700218 return INVALID_OPERATION;
219 }
François Gaffie2110e042015-03-24 08:41:51 +0100220
jiabin1c4794b2020-05-05 10:08:05 -0700221 // Populate encapsulation information when a output device is connected.
222 device->setEncapsulationInfoFromHal(mpClientInterface);
223
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700224 // outputs should never be empty here
225 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
226 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100227 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800228
Eric Laurent3ae5f312015-02-03 17:12:08 -0800229 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700230 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700231 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700232 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100233 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700234 return INVALID_OPERATION;
235 }
236
François Gaffie11d30102018-11-02 16:09:09 +0100237 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700238
jiabinc0048632023-04-27 22:04:31 +0000239 // Notify the HAL to prepare to disconnect device
240 broadcastDeviceConnectionState(
241 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700242
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100244 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700245
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100246 mOutputs.clearSessionRoutesForDevice(device);
247
François Gaffie11d30102018-11-02 16:09:09 +0100248 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100249
jiabinc0048632023-04-27 22:04:31 +0000250 // Send Disconnect to HALs
251 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
252
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800253 // Reset active device codec
254 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
255
Kriti Dangef6be8f2020-11-05 11:58:19 +0100256 // remove device from mReportedFormatsMap cache
257 mReportedFormatsMap.erase(device);
258
jiabina84c3d32022-12-02 18:59:55 +0000259 // remove preferred mixer configurations
260 mPreferredMixerAttrInfos.erase(device->getId());
261
Eric Laurente552edb2014-03-10 17:42:56 -0700262 } break;
263
264 default:
François Gaffie11d30102018-11-02 16:09:09 +0100265 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700266 return BAD_VALUE;
267 }
268
Eric Laurent736a1022019-03-27 18:28:46 -0700269 // Propagate device availability to Engine
270 setEngineDeviceConnectionState(device, state);
271
Eric Laurentae970022019-01-29 14:25:04 -0800272 // No need to evaluate playback routing when connecting a remote submix
273 // output device used by a dynamic policy of type recorder as no
274 // playback use case is affected.
275 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700276 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800277 for (audio_io_handle_t output : outputs) {
278 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800279 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
280 if (policyMix != nullptr
281 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000282 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800283 doCheckForDeviceAndOutputChanges = false;
284 break;
285 }
286 }
287 }
288
289 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700290 // outputs must be closed after checkOutputForAllStrategies() is executed
291 if (!outputs.isEmpty()) {
292 for (audio_io_handle_t output : outputs) {
293 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100294 // close unused outputs after device disconnection or direct outputs that have
295 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200296 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200297 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
298 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200299 (desc->mDirectOpenCount == 0))
300 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
301 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200302 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700303 closeOutput(output);
304 }
Eric Laurente552edb2014-03-10 17:42:56 -0700305 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700306 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
307 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700308 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700309 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800310 };
311
312 if (doCheckForDeviceAndOutputChanges) {
313 checkForDeviceAndOutputChanges(checkCloseOutputs);
314 } else {
315 checkCloseOutputs();
316 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100317 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100318 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700319 const DeviceVector activeMediaDevices =
320 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000321 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700322 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700323 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530324 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
325 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100326 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 // do not force device change on duplicated output because if device is 0, it will
328 // also force a device 0 for the two outputs it is duplicated to which may override
329 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100330 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100331 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700332 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 // always force when disconnecting (a non-duplicated device)
334 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000335 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
336 // If the device is using preferred mixer attributes, the output need to reopen
337 // with default configuration when the new selected devices are different from
338 // current routing devices
339 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
340 continue;
341 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530342 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700343 }
jiabinbce0c1d2020-10-05 11:20:18 -0700344 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000345 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700346 desc->supportsDevicesForPlayback(activeMediaDevices)) {
347 // Reopen the output to query the dynamic profiles when there is not active
348 // clients or all active clients will be rerouted. Otherwise, set the flag
349 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
350 // can be reopened to query dynamic profiles when all clients are inactive.
351 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000352 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700353 } else {
354 desc->mPendingReopenToQueryProfiles = true;
355 }
356 }
357 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
358 // Clear the flag that previously set for re-querying profiles.
359 desc->mPendingReopenToQueryProfiles = false;
360 }
361 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000362 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700363
Eric Laurentd60560a2015-04-10 11:31:20 -0700364 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100365 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700366 }
367
Eric Laurent96d1dda2022-03-14 17:14:19 +0100368 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
369
Eric Laurent72aa32f2014-05-30 18:51:48 -0700370 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700371 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700372 } // end if is output device
373
Eric Laurente552edb2014-03-10 17:42:56 -0700374 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700375 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100376 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700377 switch (state)
378 {
379 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700380 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700381 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100382 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700383 return INVALID_OPERATION;
384 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700385
386 if (mAvailableInputDevices.add(device) < 0) {
387 return NO_MEMORY;
388 }
389
François Gaffie44481e72016-04-20 07:49:57 +0200390 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
391 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000392 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700393 // Propagate device availability to Engine
394 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200395
Eric Laurent0dd51852019-04-19 18:18:58 -0700396 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700397 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
398
Eric Laurent0dd51852019-04-19 18:18:58 -0700399 mAvailableInputDevices.remove(device);
400
jiabinc0048632023-04-27 22:04:31 +0000401 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100402
403 mHwModules.cleanUpForDevice(device);
404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 return INVALID_OPERATION;
406 }
407
Eric Laurentd4692962014-05-05 18:13:44 -0700408 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700409
410 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700411 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700412 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100413 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700414 return INVALID_OPERATION;
415 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700416
François Gaffie11d30102018-11-02 16:09:09 +0100417 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700418
jiabinc0048632023-04-27 22:04:31 +0000419 // Notify the HAL to prepare to disconnect device
420 broadcastDeviceConnectionState(
421 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700422
François Gaffie11d30102018-11-02 16:09:09 +0100423 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700424
425 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100426
jiabinc0048632023-04-27 22:04:31 +0000427 // Set Disconnect to HALs
428 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
429
Kriti Dangef6be8f2020-11-05 11:58:19 +0100430 // remove device from mReportedFormatsMap cache
431 mReportedFormatsMap.erase(device);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700432
433 // Propagate device availability to Engine
434 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700435 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700436
437 default:
François Gaffie11d30102018-11-02 16:09:09 +0100438 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700439 return BAD_VALUE;
440 }
441
Eric Laurent0dd51852019-04-19 18:18:58 -0700442 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700443 // As the input device list can impact the output device selection, update
444 // getDeviceForStrategy() cache
445 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700446
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100447 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200448 // Reconnect Audio Source
449 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
450 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
451 checkAudioSourceForAttributes(attributes);
452 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700453 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100454 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700455 }
456
Eric Laurentb52c1522014-05-20 11:27:36 -0700457 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700458 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700459 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700460
François Gaffie11d30102018-11-02 16:09:09 +0100461 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700462 return BAD_VALUE;
463}
464
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100465status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
466 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800467 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000468 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
469 devDescr->setName(device_name);
470 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100471}
472
Eric Laurent736a1022019-03-27 18:28:46 -0700473void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
474 audio_policy_dev_state_t state) {
475
476 // the Engine does not have to know about remote submix devices used by dynamic audio policies
477 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
478 return;
479 }
480 mEngine->setDeviceConnectionState(device, state);
481}
482
483
Eric Laurente0720872014-03-11 09:30:41 -0700484audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100485 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700486{
Eric Laurent634b7142016-04-20 13:48:02 -0700487 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800488 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
489 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700490 (strlen(device_address) != 0)/*matchAddress*/);
491
492 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100493 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700494 device, device_address);
495 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
496 }
François Gaffie53615e22015-03-19 09:24:12 +0100497
Eric Laurent3a4311c2014-03-17 12:00:47 -0700498 DeviceVector *deviceVector;
499
Eric Laurente552edb2014-03-10 17:42:56 -0700500 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700501 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700502 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700503 deviceVector = &mAvailableInputDevices;
504 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100505 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700506 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700507 }
Eric Laurent634b7142016-04-20 13:48:02 -0700508
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800509 return (deviceVector->getDevice(
510 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700511 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800512}
513
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800514status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
515 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800516 const char *device_name,
517 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800518{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
520 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800521
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800522 // connect/disconnect only 1 device at a time
523 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
524
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700526 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528 // Nothing to do: device is not connected
529 return NO_ERROR;
530 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800531 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700533 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 // configure codecs.
535 // Handle two specific cases by sending a set parameter to
536 // configure A2DP codecs. No need to toggle device state.
537 // Case 1: A2DP active device switches from primary to primary
538 // module
539 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100540 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700541 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
543 if (availablePrimaryOutputDevices().contains(devDesc) &&
544 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100545 bool isA2dp = audio_is_a2dp_out_device(device);
546 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
547 : String8(AudioParameter::keyReconfigLeSupported);
548 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800549 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100550 int isReconfigSupported;
551 repliedParameters.getInt(supportKey, isReconfigSupported);
552 if (isReconfigSupported) {
553 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
554 : String8(AudioParameter::keyReconfigLe);
555 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800556 param.add(key, String8("true"));
557 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
558 devDesc->setEncodedFormat(encodedFormat);
559 return NO_ERROR;
560 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700561 }
562 }
cnx421bd2dcc42020-07-11 14:58:44 +0800563 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
564 for (size_t i = 0; i < mOutputs.size(); i++) {
565 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
566 // mute media strategies and delay device switch by the largest
567 // This avoid sending the music tail into the earpiece or headset.
568 setStrategyMute(musicStrategy, true, desc);
569 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
570 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
571 nullptr, true /*fromCache*/).types());
572 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800573 // Toggle the device state: UNAVAILABLE -> AVAILABLE
574 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100575 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800576 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800577 device_address, device_name,
578 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800579 if (status != NO_ERROR) {
580 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
581 status);
582 return status;
583 }
584
585 status = setDeviceConnectionState(device,
586 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800587 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800588 if (status != NO_ERROR) {
589 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
590 status);
591 return status;
592 }
593
594 return NO_ERROR;
595}
596
Pattydd807582021-11-04 21:01:03 +0800597status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
598 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800599{
Pattydd807582021-11-04 21:01:03 +0800600 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800601 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800602 std::unordered_set<audio_format_t> formatSet;
603 sp<HwModule> primaryModule =
604 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700605 if (primaryModule == nullptr) {
606 ALOGE("%s() unable to get primary module", __func__);
607 return NO_INIT;
608 }
Pattydd807582021-11-04 21:01:03 +0800609
610 DeviceTypeSet audioDeviceSet;
611
612 switch(device) {
613 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
614 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
615 break;
616 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800617 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
618 break;
619 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
620 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800621 break;
622 default:
623 ALOGE("%s() device type 0x%08x not supported", __func__, device);
624 return BAD_VALUE;
625 }
626
jiabin9a3361e2019-10-01 09:38:30 -0700627 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800628 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800629 for (const auto& device : declaredDevices) {
630 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800631 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800632 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800633 return status;
634}
635
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100636DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
637{
638 DeviceVector rxSinkdevices{};
639 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
640 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
641 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
642 auto rxSinkDevice = rxSinkdevices.itemAt(0);
643 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
644 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
645 // retrieve Rx Source device descriptor
646 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
647 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
648
649 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
650 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
651 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
652 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
653 return DeviceVector(rxSinkDevice);
654 }
655 }
656 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
657 // the device returned is not necessarily reachable via this output
658 // (filter later by setOutputDevices())
659 return getNewOutputDevices(mPrimaryOutput, fromCache);
660}
661
662status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
663{
François Gaffiedb1755b2023-09-01 11:50:35 +0200664 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100665 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
666 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
667 }
668 return INVALID_OPERATION;
669}
670
671status_t AudioPolicyManager::updateCallRoutingInternal(
672 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700673{
674 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100675 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700676 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200677 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700678 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100679 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700680 }
François Gaffie11d30102018-11-02 16:09:09 +0100681
Francois Gaffie716e1432019-01-14 16:58:59 +0100682 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100683 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200684
685 disconnectTelephonyAudioSource(mCallRxSourceClient);
686 disconnectTelephonyAudioSource(mCallTxSourceClient);
687
688 if (rxDevices.isEmpty()) {
689 ALOGW("%s() no selected output device", __func__);
690 return INVALID_OPERATION;
691 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000692 if (txSourceDevice == nullptr) {
693 ALOGE("%s() selected input device not available", __func__);
694 return INVALID_OPERATION;
695 }
François Gaffiec005e562018-11-06 15:04:49 +0100696
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100697 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100698 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700699
François Gaffie9eb18552018-11-05 10:33:26 +0100700 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700701 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100702 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700703 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100704 // retrieve Rx Source and Tx Sink device descriptors
705 sp<DeviceDescriptor> rxSourceDevice =
706 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
707 String8(),
708 AUDIO_FORMAT_DEFAULT);
709 sp<DeviceDescriptor> txSinkDevice =
710 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
711 String8(),
712 AUDIO_FORMAT_DEFAULT);
713
714 // RX and TX Telephony device are declared by Primary Audio HAL
715 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
716 (telephonyRxModule->getHalVersionMajor() >= 3)) {
717 if (rxSourceDevice == 0 || txSinkDevice == 0) {
718 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100719 ALOGE("%s() no telephony Tx and/or RX device", __func__);
720 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100721 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100722 // createAudioPatchInternal now supports both HW / SW bridging
723 createRxPatch = true;
724 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100725 } else {
726 // If the RX device is on the primary HW module, then use legacy routing method for
727 // voice calls via setOutputDevice() on primary output.
728 // Otherwise, create two audio patches for TX and RX path.
729 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
730 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700731 // If the TX device is also on the primary HW module, setOutputDevice() will take care
732 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100733 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
734 (txSinkDevice != 0);
735 }
736 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
737 // Otherwise, create two audio patches for TX and RX path.
738 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200739 if (!hasPrimaryOutput()) {
740 ALOGW("%s() no primary output available", __func__);
741 return INVALID_OPERATION;
742 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530743 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700744 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200745 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800746 // If the TX device is on the primary HW module but RX device is
747 // on other HW module, SinkMetaData of telephony input should handle it
748 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700749 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700750 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100751 // terminate active capture if on the same HW module as the call TX source device
752 // FIXME: would be better to refine to only inputs whose profile connects to the
753 // call TX device but this information is not in the audio patch and logic here must be
754 // symmetric to the one in startInput()
755 for (const auto& activeDesc : mInputs.getActiveInputs()) {
756 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
757 closeActiveClients(activeDesc);
758 }
759 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200760 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800761 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100762 if (waitMs != nullptr) {
763 *waitMs = muteWaitMs;
764 }
765 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800766}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700767
Mikhail Naganov100f0122018-11-29 11:22:16 -0800768bool AudioPolicyManager::isDeviceOfModule(
769 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
770 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
771 if (module != 0) {
772 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
773 .indexOf(devDesc) != NAME_NOT_FOUND
774 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
775 .indexOf(devDesc) != NAME_NOT_FOUND;
776 }
777 return false;
778}
779
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200780void AudioPolicyManager::connectTelephonyRxAudioSource()
781{
Francois Gaffie601801d2021-06-22 13:27:39 +0200782 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200783 const struct audio_port_config source = {
784 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
785 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
786 };
787 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200788 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
789 ALOGE_IF(mCallRxSourceClient == nullptr,
790 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200791}
792
Francois Gaffie601801d2021-06-22 13:27:39 +0200793void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200794{
Francois Gaffie601801d2021-06-22 13:27:39 +0200795 if (clientDesc == nullptr) {
796 return;
797 }
798 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
799 "%s error stopping audio source", __func__);
800 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200801}
802
803void AudioPolicyManager::connectTelephonyTxAudioSource(
804 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
805 uint32_t delayMs)
806{
Francois Gaffie601801d2021-06-22 13:27:39 +0200807 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200808 if (srcDevice == nullptr || sinkDevice == nullptr) {
809 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
810 return;
811 }
812 PatchBuilder patchBuilder;
813 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
814 ALOGV("%s between source %s and sink %s", __func__,
815 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200816 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200817 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
818
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200819 struct audio_port_config source = {};
820 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 mCallTxSourceClient = new InternalSourceClientDescriptor(
822 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200823 mCommunnicationStrategy, toVolumeSource(aa));
824 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
825 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200826 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
827 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200828 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
829 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200830 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200831 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200832}
833
Eric Laurente0720872014-03-11 09:30:41 -0700834void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700835{
836 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100837 // store previous phone state for management of sonification strategy below
838 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100839 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100840
841 if (mEngine->setPhoneState(state) != NO_ERROR) {
842 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700843 return;
844 }
François Gaffie2110e042015-03-24 08:41:51 +0100845 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700846 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700847 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700848 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800849 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700850 }
851
François Gaffie2110e042015-03-24 08:41:51 +0100852 /**
853 * Switching to or from incall state or switching between telephony and VoIP lead to force
854 * routing command.
855 */
Eric Laurent74b71512019-11-06 17:21:57 -0800856 bool force = ((isStateInCall(oldState) != isStateInCall(state))
857 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700858
859 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700860 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700861
Eric Laurente552edb2014-03-10 17:42:56 -0700862 int delayMs = 0;
863 if (isStateInCall(state)) {
864 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100865 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
866 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700867 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700868 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700869 // mute media and sonification strategies and delay device switch by the largest
870 // latency of any output where either strategy is active.
871 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100872 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
873 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
874 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700875 (delayMs < (int)desc->latency()*2)) {
876 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700877 }
François Gaffiec005e562018-11-06 15:04:49 +0100878 setStrategyMute(musicStrategy, true, desc);
879 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
880 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
881 nullptr, true /*fromCache*/).types());
882 setStrategyMute(sonificationStrategy, true, desc);
883 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
884 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
885 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700886 }
887 }
888
François Gaffiedb1755b2023-09-01 11:50:35 +0200889 if (state == AUDIO_MODE_IN_CALL) {
890 (void)updateCallRouting(false /*fromCache*/, delayMs);
891 } else {
892 if (oldState == AUDIO_MODE_IN_CALL) {
893 disconnectTelephonyAudioSource(mCallRxSourceClient);
894 disconnectTelephonyAudioSource(mCallTxSourceClient);
895 }
896 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100897 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
898 // force routing command to audio hardware when ending call
899 // even if no device change is needed
900 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
901 rxDevices = mPrimaryOutput->devices();
902 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530903 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700904 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700905 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700906
jiabin3ff8d7d2022-12-13 06:27:44 +0000907 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700908 // reevaluate routing on all outputs in case tracks have been started during the call
909 for (size_t i = 0; i < mOutputs.size(); i++) {
910 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100911 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200912 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
913 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000914 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
915 // If the device is using preferred mixer attributes, the output need to reopen
916 // with default configuration when the new selected devices are different from
917 // current routing devices.
918 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
919 continue;
920 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530921 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200922 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700923 }
924 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000925 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700926
Eric Laurent96d1dda2022-03-14 17:14:19 +0100927 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
928
Eric Laurente552edb2014-03-10 17:42:56 -0700929 if (isStateInCall(state)) {
930 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700931 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800932 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700933 }
934
935 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100936 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
937 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700938}
939
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700940audio_mode_t AudioPolicyManager::getPhoneState() {
941 return mEngine->getPhoneState();
942}
943
Eric Laurente0720872014-03-11 09:30:41 -0700944void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100945 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700946{
François Gaffie2110e042015-03-24 08:41:51 +0100947 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700948 if (config == mEngine->getForceUse(usage)) {
949 return;
950 }
Eric Laurente552edb2014-03-10 17:42:56 -0700951
François Gaffie2110e042015-03-24 08:41:51 +0100952 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
953 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
954 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700955 }
François Gaffie2110e042015-03-24 08:41:51 +0100956 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
957 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
958 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700959
960 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700961 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800962
Eric Laurent22fcda22019-05-17 16:28:47 -0700963 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
964 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800965 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700966 }
967
Eric Laurentdc462862016-07-19 12:29:53 -0700968 //FIXME: workaround for truncated touch sounds
969 // to be removed when the problem is handled by system UI
970 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700971 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
972 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
973 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700974
975 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100976 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700977}
978
Eric Laurente0720872014-03-11 09:30:41 -0700979void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700980{
981 ALOGV("setSystemProperty() property %s, value %s", property, value);
982}
983
Dorin Drimusecc9f422022-03-09 17:57:40 +0100984// Find an MSD output profile compatible with the parameters passed.
985// When "directOnly" is set, restrict search to profiles for direct outputs.
986sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
987 const DeviceVector& devices,
988 uint32_t samplingRate,
989 audio_format_t format,
990 audio_channel_mask_t channelMask,
991 audio_output_flags_t flags,
992 bool directOnly)
993{
994 flags = getRelevantFlags(flags, directOnly);
995
996 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
997 if (msdModule != nullptr) {
998 // for the msd module check if there are patches to the output devices
999 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1000 HwModuleCollection modules;
1001 modules.add(msdModule);
1002 return searchCompatibleProfileHwModules(
1003 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1004 flags, directOnly);
1005 }
1006 }
1007 return nullptr;
1008}
1009
Michael Chana94fbb22018-04-24 14:31:19 +10001010// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1011// search to profiles for direct outputs.
1012sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001013 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001014 uint32_t samplingRate,
1015 audio_format_t format,
1016 audio_channel_mask_t channelMask,
1017 audio_output_flags_t flags,
1018 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001019{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001020 flags = getRelevantFlags(flags, directOnly);
1021
1022 return searchCompatibleProfileHwModules(
1023 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1024}
1025
1026audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1027 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001028 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001029 // only retain flags that will drive the direct output profile selection
1030 // if explicitly requested
1031 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001032 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001033 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1034 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001035 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 return flags;
1037}
Eric Laurent861a6282015-05-18 15:40:16 -07001038
Dorin Drimusecc9f422022-03-09 17:57:40 +01001039sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1040 const HwModuleCollection& hwModules,
1041 const DeviceVector& devices,
1042 uint32_t samplingRate,
1043 audio_format_t format,
1044 audio_channel_mask_t channelMask,
1045 audio_output_flags_t flags,
1046 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001047 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001048 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001049 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinde7ae442024-02-06 00:57:36 +00001050 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001051 samplingRate, NULL /*updatedSamplingRate*/,
1052 format, NULL /*updatedFormat*/,
1053 channelMask, NULL /*updatedChannelMask*/,
jiabinde7ae442024-02-06 00:57:36 +00001054 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001055 continue;
1056 }
1057 // reject profiles not corresponding to a device currently available
1058 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1059 continue;
1060 }
1061 // reject profiles if connected device does not support codec
1062 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1063 continue;
1064 }
1065 if (!directOnly) {
1066 return curProfile;
1067 }
1068
1069 // when searching for direct outputs, if several profiles are compatible, give priority
1070 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001071 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001072 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001073 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001074 }
1075 profile = curProfile;
1076 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1077 break;
1078 }
Eric Laurente552edb2014-03-10 17:42:56 -07001079 }
1080 }
Eric Laurent861a6282015-05-18 15:40:16 -07001081 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001082}
1083
Eric Laurentfa0f6742021-08-17 18:39:44 +02001084sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001085 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001086{
1087 for (const auto& hwModule : mHwModules) {
1088 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001089 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001090 continue;
1091 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001092 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001093 // reject profiles not corresponding to a device currently available
1094 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1095 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1096 continue;
1097 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001098 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1099 != devices.size()) {
1100 continue;
1101 }
1102 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001103 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1104 return curProfile;
1105 }
1106 }
1107 return nullptr;
1108}
1109
Eric Laurentf4e63452017-11-06 19:31:46 +00001110audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001111{
François Gaffiec005e562018-11-06 15:04:49 +01001112 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001113
1114 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1115 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1116 // format, flags, etc. This may result in some discrepancy for functions that utilize
1117 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1118 // and AudioSystem::getOutputSamplingRate().
1119
François Gaffie11d30102018-11-02 16:09:09 +01001120 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001121 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1122 if (stream == AUDIO_STREAM_MUSIC &&
1123 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1124 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1125 }
1126 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001127
François Gaffie11d30102018-11-02 16:09:09 +01001128 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1129 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001130 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001131}
1132
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001133status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1134 const audio_attributes_t *srcAttr,
1135 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001136{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001137 if (srcAttr != NULL) {
1138 if (!isValidAttributes(srcAttr)) {
1139 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1140 __func__,
1141 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1142 srcAttr->tags);
1143 return BAD_VALUE;
1144 }
1145 *dstAttr = *srcAttr;
1146 } else {
1147 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1148 ALOGE("%s: invalid stream type", __func__);
1149 return BAD_VALUE;
1150 }
François Gaffiec005e562018-11-06 15:04:49 +01001151 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001152 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001153
1154 // Only honor audibility enforced when required. The client will be
1155 // forced to reconnect if the forced usage changes.
1156 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001157 dstAttr->flags = static_cast<audio_flags_mask_t>(
1158 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001159 }
1160
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001161 return NO_ERROR;
1162}
1163
Kevin Rocard153f92d2018-12-18 18:33:28 -08001164status_t AudioPolicyManager::getOutputForAttrInt(
1165 audio_attributes_t *resultAttr,
1166 audio_io_handle_t *output,
1167 audio_session_t session,
1168 const audio_attributes_t *attr,
1169 audio_stream_type_t *stream,
1170 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001171 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001172 audio_output_flags_t *flags,
1173 audio_port_handle_t *selectedDeviceId,
1174 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001175 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001176 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001177 bool *isSpatialized,
1178 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001179{
François Gaffiec005e562018-11-06 15:04:49 +01001180 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001181 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001182 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001183 const sp<DeviceDescriptor> requestedDevice =
1184 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1185
Eric Laurent8a1095a2019-11-08 14:44:16 -08001186 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001187 *isSpatialized = false;
1188
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001189 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1190 if (status != NO_ERROR) {
1191 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001192 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001193 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001194 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001195 }
François Gaffiec005e562018-11-06 15:04:49 +01001196 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001197
François Gaffiec005e562018-11-06 15:04:49 +01001198 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1199 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001200
Oscar Azucena873d10f2023-01-12 18:34:42 -08001201 bool usePrimaryOutputFromPolicyMixes = false;
1202
Kevin Rocard153f92d2018-12-18 18:33:28 -08001203 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1204 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1205 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001206 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001207 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1208 .channel_mask = config->channel_mask,
1209 .format = config->format,
1210 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001211 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001212 mAvailableOutputDevices, requestedDevice, primaryMix,
1213 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001214 if (status != OK) {
1215 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001216 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001217
Kevin Rocard153f92d2018-12-18 18:33:28 -08001218 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001219 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1220 && !audio_is_linear_pcm(config->format)) {
1221 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001222 return BAD_VALUE;
1223 }
1224 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001225 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001226 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1227 primaryMix->mDeviceAddress,
1228 AUDIO_FORMAT_DEFAULT);
1229 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001230 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001231 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1232 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001233 // if a direct output can be opened to deliver the track's multi-channel content to the
1234 // output rather than being downmixed by the primary output, then use this direct
1235 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1236 // mix.
1237 bool tryDirectForChannelMask = policyDesc != nullptr
1238 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1239 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001240 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001241 audio_io_handle_t newOutput;
1242 status = openDirectOutput(
1243 *stream, session, config,
1244 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001245 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001246 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001247 policyDesc = mOutputs.valueFor(newOutput);
1248 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001249 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001250 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001251 policyDesc = nullptr;
1252 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001253 }
1254 if (policyDesc != nullptr) {
1255 policyDesc->mPolicyMix = primaryMix;
1256 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001257 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1258 : AUDIO_PORT_HANDLE_NONE;
1259 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1260 // Remove direct flag as it is not on a direct output.
1261 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1262 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001263
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001264 ALOGV("getOutputForAttr() returns output %d", *output);
1265 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1266 *outputType = API_OUT_MIX_PLAYBACK;
1267 } else {
1268 *outputType = API_OUTPUT_LEGACY;
1269 }
1270 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001271 } else {
1272 if (policyMixDevice != nullptr) {
1273 ALOGE("%s, try to use primary mix but no output found", __func__);
1274 return INVALID_OPERATION;
1275 }
1276 // Fallback to default engine selection as the selected primary mix device is not
1277 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001278 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001279 }
François Gaffiec005e562018-11-06 15:04:49 +01001280 // Virtual sources must always be dynamicaly or explicitly routed
1281 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1282 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1283 return BAD_VALUE;
1284 }
1285 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1286 // in order to let the choice of the order to future vendor engine
1287 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001288
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001289 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001290 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001291 }
1292
Nadav Barb2f18162018-07-18 13:01:53 +03001293 // Set incall music only if device was explicitly set, and fallback to the device which is
1294 // chosen by the engine if not.
1295 // FIXME: provide a more generic approach which is not device specific and move this back
1296 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001297 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001298 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001299 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001300 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001301 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001302 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001303 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001304 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001305 }
1306 }
1307
François Gaffiec005e562018-11-06 15:04:49 +01001308 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1309 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1310 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001311
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001312 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001313 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001314 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001315 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001316 ALOGV("%s() Using MSD devices %s instead of devices %s",
1317 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001318 } else {
1319 *output = AUDIO_IO_HANDLE_NONE;
1320 }
1321 }
1322 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001323 sp<PreferredMixerAttributesInfo> info = nullptr;
1324 if (outputDevices.size() == 1) {
1325 info = getPreferredMixerAttributesInfo(
1326 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001327 mEngine->getProductStrategyForAttributes(*resultAttr),
1328 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001329 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1330 // and it is currently active.
1331 if (info != nullptr && info->getUid() != uid &&
1332 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1333 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001334 info = nullptr;
1335 }
1336 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001337 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001338 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001339 // The client will be active if the client is currently preferred mixer owner and the
1340 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001341 *isBitPerfect = (info != nullptr
1342 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001343 && info->getUid() == uid
1344 && *output != AUDIO_IO_HANDLE_NONE
1345 // When bit-perfect output is selected for the preferred mixer attributes owner,
1346 // only need to consider the config matches.
1347 && mOutputs.valueFor(*output)->isConfigurationMatched(
1348 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001349 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001350 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001351 AudioProfileVector profiles;
1352 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1353 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001354 const auto channels = profiles[0]->getChannels();
1355 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1356 config->channel_mask = *channels.begin();
1357 }
1358 const auto sampleRates = profiles[0]->getSampleRates();
1359 if (!sampleRates.empty() &&
1360 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1361 config->sample_rate = *sampleRates.begin();
1362 }
jiabinf1c73972022-04-14 16:28:52 -07001363 config->format = profiles[0]->getFormat();
1364 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001365 return INVALID_OPERATION;
1366 }
Paul McLeanaa981192015-03-21 09:55:15 -07001367
François Gaffiec005e562018-11-06 15:04:49 +01001368 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001369 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001370 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001371 *selectedDeviceId = outputDevice->getId();
1372 break;
1373 }
1374 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001375
Eric Laurent8a1095a2019-11-08 14:44:16 -08001376 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1377 *outputType = API_OUTPUT_TELEPHONY_TX;
1378 } else {
1379 *outputType = API_OUTPUT_LEGACY;
1380 }
1381
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001382 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1383
1384 return NO_ERROR;
1385}
1386
1387status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1388 audio_io_handle_t *output,
1389 audio_session_t session,
1390 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001391 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001392 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001393 audio_output_flags_t *flags,
1394 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001395 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001396 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001397 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001398 bool *isSpatialized,
1399 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001400{
1401 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1402 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1403 return INVALID_OPERATION;
1404 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001405 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001406 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001407 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001408 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001409 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001410 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001411 const sp<DeviceDescriptor> requestedDevice =
1412 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1413
1414 // Prevent from storing invalid requested device id in clients
1415 const audio_port_handle_t sanitizedRequestedPortId =
1416 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1417 *selectedDeviceId = sanitizedRequestedPortId;
1418
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001419 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001420 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001421 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1422 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001423 if (status != NO_ERROR) {
1424 return status;
1425 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001426 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001427 if (secondaryOutputs != nullptr) {
1428 for (auto &secondaryMix : secondaryMixes) {
1429 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1430 if (outputDesc != nullptr &&
1431 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1432 secondaryOutputs->push_back(outputDesc->mIoHandle);
1433 weakSecondaryOutputDescs.push_back(outputDesc);
1434 }
1435 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001436 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001437
Eric Laurent8fc147b2018-07-22 19:13:55 -07001438 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001439 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001440 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001441 };
jiabin4ef93452019-09-10 14:29:54 -07001442 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001443
Eric Laurentc209fe42020-06-05 18:11:23 -07001444 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001445 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001446 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001447 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001448 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001449 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001450 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001451 std::move(weakSecondaryOutputDescs),
1452 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001453 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001454
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001455 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1456 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001457
Eric Laurente83b55d2014-11-14 10:06:21 -08001458 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001459}
1460
Eric Laurentc529cf62020-04-17 18:19:10 -07001461status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1462 audio_session_t session,
1463 const audio_config_t *config,
1464 audio_output_flags_t flags,
1465 const DeviceVector &devices,
1466 audio_io_handle_t *output) {
1467
1468 *output = AUDIO_IO_HANDLE_NONE;
1469
1470 // skip direct output selection if the request can obviously be attached to a mixed output
1471 // and not explicitly requested
1472 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1473 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1474 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1475 return NAME_NOT_FOUND;
1476 }
1477
1478 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1479 // This prevents creating an offloaded track and tearing it down immediately after start
1480 // when audioflinger detects there is an active non offloadable effect.
1481 // FIXME: We should check the audio session here but we do not have it in this context.
1482 // This may prevent offloading in rare situations where effects are left active by apps
1483 // in the background.
1484 sp<IOProfile> profile;
1485 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1486 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1487 profile = getProfileForOutput(
1488 devices, config->sample_rate, config->format, config->channel_mask,
1489 flags, true /* directOnly */);
1490 }
1491
1492 if (profile == nullptr) {
1493 return NAME_NOT_FOUND;
1494 }
1495
1496 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1497 for (size_t i = 0; i < mOutputs.size(); i++) {
1498 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1499 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1500 // reuse direct output if currently open by the same client
1501 // and configured with same parameters
1502 if ((config->sample_rate == desc->getSamplingRate()) &&
1503 (config->format == desc->getFormat()) &&
1504 (config->channel_mask == desc->getChannelMask()) &&
1505 (session == desc->mDirectClientSession)) {
1506 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001507 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001508 mOutputs.keyAt(i), session);
1509 *output = mOutputs.keyAt(i);
1510 return NO_ERROR;
1511 }
1512 }
1513 }
1514
1515 if (!profile->canOpenNewIo()) {
1516 return NAME_NOT_FOUND;
1517 }
1518
1519 sp<SwAudioOutputDescriptor> outputDesc =
1520 new SwAudioOutputDescriptor(profile, mpClientInterface);
1521
Michael Chan6fb34492020-12-08 15:44:49 +11001522 // An MSD patch may be using the only output stream that can service this request. Release
1523 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001524 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001525
Eric Laurentf1f22e72021-07-13 14:04:14 +02001526 status_t status =
1527 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001528
1529 // only accept an output with the requested parameters
1530 if (status != NO_ERROR ||
1531 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1532 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1533 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1534 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1535 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1536 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1537 config->channel_mask, outputDesc->getChannelMask());
1538 if (*output != AUDIO_IO_HANDLE_NONE) {
1539 outputDesc->close();
1540 }
1541 // fall back to mixer output if possible when the direct output could not be open
1542 if (audio_is_linear_pcm(config->format) &&
1543 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1544 return NAME_NOT_FOUND;
1545 }
1546 *output = AUDIO_IO_HANDLE_NONE;
1547 return BAD_VALUE;
1548 }
1549 outputDesc->mDirectOpenCount = 1;
1550 outputDesc->mDirectClientSession = session;
1551
1552 addOutput(*output, outputDesc);
1553 mPreviousOutputs = mOutputs;
1554 ALOGV("%s returns new direct output %d", __func__, *output);
1555 mpClientInterface->onAudioPortListUpdate();
1556 return NO_ERROR;
1557}
1558
François Gaffie11d30102018-11-02 16:09:09 +01001559audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1560 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001561 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001562 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001563 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001564 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001565 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001566 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001567 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001568{
Andy Hungc88b0642018-04-27 15:42:35 -07001569 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001570
jiabine375d412019-02-26 12:54:53 -08001571 // Discard haptic channel mask when forcing muting haptic channels.
1572 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001573 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1574 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001575
Eric Laurente552edb2014-03-10 17:42:56 -07001576 // open a direct output if required by specified parameters
1577 //force direct flag if offload flag is set: offloading implies a direct output stream
1578 // and all common behaviors are driven by checking only the direct flag
1579 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001580 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1581 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001582 }
Nadav Bar766fb022018-01-07 12:18:03 +02001583 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1584 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001585 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001586
1587 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1588
Eric Laurente83b55d2014-11-14 10:06:21 -08001589 // only allow deep buffering for music stream type
1590 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001591 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001592 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001593 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001594 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1595 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001596 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001597 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001598 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001599 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001600 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001601 audio_is_linear_pcm(config->format) &&
1602 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001603 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001604 AUDIO_OUTPUT_FLAG_DIRECT);
1605 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001606 }
Eric Laurente552edb2014-03-10 17:42:56 -07001607
Carter Hsua3abb402021-10-26 11:11:20 +08001608 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1609 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1610 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1611 }
1612
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001613 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001614 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001615 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001616 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001617 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001618 }
1619
Eric Laurentc529cf62020-04-17 18:19:10 -07001620 audio_config_t directConfig = *config;
1621 directConfig.channel_mask = channelMask;
1622 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1623 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001624 return output;
1625 }
1626
Eric Laurent14cbfca2016-03-17 09:42:16 -07001627 // A request for HW A/V sync cannot fallback to a mixed output because time
1628 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001629 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001630 return AUDIO_IO_HANDLE_NONE;
1631 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001632 // A request for Tuner cannot fallback to a mixed output
1633 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1634 return AUDIO_IO_HANDLE_NONE;
1635 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001636
Eric Laurente552edb2014-03-10 17:42:56 -07001637 // ignoring channel mask due to downmix capability in mixer
1638
1639 // open a non direct output
1640
1641 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001642 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001643 // get which output is suitable for the specified stream. The actual
1644 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001645 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001646 if (prefMixerConfigInfo != nullptr) {
1647 for (audio_io_handle_t outputHandle : outputs) {
1648 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1649 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1650 output = outputHandle;
1651 break;
1652 }
1653 }
1654 if (output == AUDIO_IO_HANDLE_NONE) {
1655 // No output open with the preferred profile. Open a new one.
1656 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1657 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1658 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1659 config.format = prefMixerConfigInfo->getConfigBase().format;
1660 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1661 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1662 &config, prefMixerConfigInfo->getFlags());
1663 if (preferredOutput == nullptr) {
1664 ALOGE("%s failed to open output with preferred mixer config", __func__);
1665 } else {
1666 output = preferredOutput->mIoHandle;
1667 }
1668 }
1669 } else {
1670 // at this stage we should ignore the DIRECT flag as no direct output could be
1671 // found earlier
1672 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1673 output = selectOutput(
1674 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1675 }
Eric Laurente552edb2014-03-10 17:42:56 -07001676 }
François Gaffie11d30102018-11-02 16:09:09 +01001677 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001678 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001679 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001680
Eric Laurente552edb2014-03-10 17:42:56 -07001681 return output;
1682}
1683
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001684sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001685 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1686 mAvailableInputDevices);
1687 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1688}
1689
1690DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1691 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1692 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001693}
1694
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001695const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001696 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001697 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1698 if (msdModule != 0) {
1699 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1700 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1701 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1702 const struct audio_port_config *source = &patch->mPatch.sources[j];
1703 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1704 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001705 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001706 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001707 }
1708 }
1709 }
1710 return msdPatches;
1711}
1712
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001713bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1714 ssize_t index = mAudioPatches.indexOfKey(handle);
1715 if (index < 0) {
1716 return false;
1717 }
1718 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1719 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1720 if (msdModule == nullptr) {
1721 return false;
1722 }
1723 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1724 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1725 return true;
1726 }
1727 index = getMsdOutputPatches().indexOfKey(handle);
1728 if (index < 0) {
1729 return false;
1730 }
1731 return true;
1732}
1733
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001734status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1735 const InputProfileCollection &inputProfiles,
1736 const OutputProfileCollection &outputProfiles,
1737 const sp<DeviceDescriptor> &sourceDevice,
1738 const sp<DeviceDescriptor> &sinkDevice,
1739 AudioProfileVector& sourceProfiles,
1740 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001741 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001742 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001743 return NO_INIT;
1744 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001745 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001746 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001747 return NO_INIT;
1748 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001749 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001750 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1751 inProfile->supportsDevice(sourceDevice)) {
1752 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001753 }
1754 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001755 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001756 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001757 outProfile->supportsDevice(sinkDevice)) {
1758 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001759 }
1760 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001761 return NO_ERROR;
1762}
1763
1764status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1765 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1766 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1767{
Dean Wheatley16809da2022-12-09 14:55:46 +11001768 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1769 static const std::vector<audio_format_t> formatsOrder = {{
1770 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001771 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1772 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001773 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1774 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1775 // preferred).
1776 std::vector<audio_channel_mask_t> masks = {{
1777 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1778 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1779 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1780 // insert index masks (higher counts most preferred) as preferred over position masks
1781 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1782 masks.insert(
1783 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1784 }
1785 return masks;
1786 }();
1787
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001788 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001789 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1790 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001791 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001792 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1793 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001794 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001795 }
1796 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1797 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1798 sinkConfig->format = bestSinkConfig.format;
1799 // For encoded streams force direct flag to prevent downstream mixing.
1800 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1801 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001802 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1803 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001804 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001805 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1806 // raw and IEC61937 framed streams.
1807 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1808 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1809 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001810 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1811 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001812 sourceConfig->channel_mask =
1813 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1814 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1815 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001816 sourceConfig->format = bestSinkConfig.format;
1817 // Copy input stream directly without any processing (e.g. resampling).
1818 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1819 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1820 if (hwAvSync) {
1821 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1822 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1823 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1824 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1825 }
1826 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1827 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1828 sinkConfig->config_mask |= config_mask;
1829 sourceConfig->config_mask |= config_mask;
1830 return NO_ERROR;
1831}
1832
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001833PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1834 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001835{
1836 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001837 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1838 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1839 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1840 if (deviceModule == nullptr) {
1841 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1842 return patchBuilder;
1843 }
1844 const InputProfileCollection inputProfiles = msdIsSource ?
1845 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1846 const OutputProfileCollection outputProfiles = msdIsSource ?
1847 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1848
1849 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1850 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1851 device : getMsdAudioOutDevices().itemAt(0);
1852 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1853
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001854 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1855 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001856 AudioProfileVector sourceProfiles;
1857 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001858 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1859 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001860 for (auto hwAvSync : { true, false }) {
1861 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1862 sourceProfiles, sinkProfiles) != NO_ERROR) {
1863 continue;
1864 }
1865 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1866 &sinkConfig) == NO_ERROR) {
1867 // Found a matching config. Re-create PatchBuilder with this config.
1868 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1869 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001870 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001871 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001872 " supporting PCM format conversion.", __func__);
1873 return patchBuilder;
1874}
1875
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001876status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001877 DeviceVector devices;
1878 if (outputDevices != nullptr && outputDevices->size() > 0) {
1879 devices.add(*outputDevices);
1880 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 // Use media strategy for unspecified output device. This should only
1882 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1883 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001884 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001885 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001886 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001887 }
Michael Chan6fb34492020-12-08 15:44:49 +11001888 std::vector<PatchBuilder> patchesToCreate;
1889 for (auto i = 0u; i < devices.size(); ++i) {
1890 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001891 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001892 }
1893 // Retain only the MSD patches associated with outputDevices request.
1894 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001895 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001896 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1897 auto retainedPatch = false;
1898 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1899 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1900 patchesToRemove.removeItemsAt(i);
1901 retainedPatch = true;
1902 break;
1903 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001904 }
Michael Chan6fb34492020-12-08 15:44:49 +11001905 if (retainedPatch) {
1906 it = patchesToCreate.erase(it);
1907 continue;
1908 }
1909 ++it;
1910 }
1911 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1912 return NO_ERROR;
1913 }
1914 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1915 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001916 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001917 }
Michael Chan6fb34492020-12-08 15:44:49 +11001918 status_t status = NO_ERROR;
1919 for (const auto &p : patchesToCreate) {
1920 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1921 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1922 char message[256];
1923 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1924 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1925 currStatus == NO_ERROR ? "Success" : "Error",
1926 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1927 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1928 if (currStatus == NO_ERROR) {
1929 ALOGD("%s", message);
1930 } else {
1931 ALOGE("%s", message);
1932 if (status == NO_ERROR) {
1933 status = currStatus;
1934 }
1935 }
1936 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001937 return status;
1938}
1939
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001940void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1941 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001942 for (size_t i = 0; i < msdPatches.size(); i++) {
1943 const auto& patch = msdPatches[i];
1944 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1945 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1946 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1947 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1948 releaseAudioPatch(patch->getHandle(), mUidCached);
1949 break;
1950 }
1951 }
1952 }
1953}
1954
Dorin Drimus94d94412022-02-02 09:05:02 +01001955bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001956 DeviceVector devicesToCheck =
1957 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001958 AudioPatchCollection msdPatches = getMsdOutputPatches();
1959 for (size_t i = 0; i < msdPatches.size(); i++) {
1960 const auto& patch = msdPatches[i];
1961 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1962 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1963 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1964 const auto& foundDevice = devicesToCheck.getDevice(
1965 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1966 if (foundDevice != nullptr) {
1967 devicesToCheck.remove(foundDevice);
1968 if (devicesToCheck.isEmpty()) {
1969 return true;
1970 }
1971 }
1972 }
1973 }
1974 }
1975 return false;
1976}
1977
Eric Laurente0720872014-03-11 09:30:41 -07001978audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001979 audio_output_flags_t flags,
1980 audio_format_t format,
1981 audio_channel_mask_t channelMask,
1982 uint32_t samplingRate,
1983 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001984{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001985 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1986 "%s called with format %#x", __func__, format);
1987
jiabinebb6af42020-06-09 17:31:17 -07001988 // Return the output that haptic-generating attached to when 1) session id is specified,
1989 // 2) haptic-generating effect exists for given session id and 3) the output that
1990 // haptic-generating effect attached to is in given outputs.
1991 if (sessionId != AUDIO_SESSION_NONE) {
1992 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1993 sessionId, FX_IID_HAPTICGENERATOR);
1994 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1995 return hapticGeneratingOutput;
1996 }
1997 }
1998
Eric Laurent16c66dd2019-05-01 17:54:10 -07001999 // Flags disqualifying an output: the match must happen before calling selectOutput()
2000 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2001 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2002
2003 // Flags expressing a functional request: must be honored in priority over
2004 // other criteria
2005 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2006 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002007 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2008 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002009 // Flags expressing a performance request: have lower priority than serving
2010 // requested sampling rate or channel mask
2011 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2012 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2013 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2014
2015 const audio_output_flags_t functionalFlags =
2016 (audio_output_flags_t)(flags & kFunctionalFlags);
2017 const audio_output_flags_t performanceFlags =
2018 (audio_output_flags_t)(flags & kPerformanceFlags);
2019
2020 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2021
Eric Laurente552edb2014-03-10 17:42:56 -07002022 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002023 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002024 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002025 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002026 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002027 // with tiebreak preferring the minimum number of extra functional flags
2028 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002029 // 3: the output supporting the exact channel mask
2030 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002031 // 5: the output with the highest sampling rate if the requested sample rate is
2032 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002033 // 6: the output with the highest number of requested performance flags
2034 // 7: the output with the bit depth the closest to the requested one
2035 // 8: the primary output
2036 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002037
Eric Laurent16c66dd2019-05-01 17:54:10 -07002038 // matching criteria values in priority order for best matching output so far
2039 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002040
Eric Laurent16c66dd2019-05-01 17:54:10 -07002041 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2042 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2043 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002044
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002045 for (audio_io_handle_t output : outputs) {
2046 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002047 // matching criteria values in priority order for current output
2048 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002049
Eric Laurent16c66dd2019-05-01 17:54:10 -07002050 if (outputDesc->isDuplicated()) {
2051 continue;
2052 }
2053 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2054 continue;
2055 }
Eric Laurent8838a382014-09-08 16:44:28 -07002056
Eric Laurent16c66dd2019-05-01 17:54:10 -07002057 // If haptic channel is specified, use the haptic output if present.
2058 // When using haptic output, same audio format and sample rate are required.
2059 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002060 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002061 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2062 continue;
2063 }
2064 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002065 && format == outputDesc->getFormat()
2066 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002067 currentMatchCriteria[0] = outputHapticChannelCount;
2068 }
2069
2070 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002071 const int matchingFunctionalFlags =
2072 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2073 const int totalFunctionalFlags =
2074 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2075 // Prefer matching functional flags, but subtract unnecessary functional flags.
2076 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002077
2078 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002079 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2080 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002081 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2082 channelCount <= outputChannelCount) {
2083 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002084 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2085 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002086 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002087 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002088 currentMatchCriteria[3] = outputChannelCount;
2089 }
2090
2091 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002092 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002093 int diff; // avoid unsigned integer overflow.
2094 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2095
2096 // prefer the closest output sampling rate greater than or equal to target
2097 // if none exists, prefer the closest output sampling rate less than target.
2098 //
2099 // criteria is offset to make non-negative.
2100 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002101 }
2102
2103 // performance flags match
2104 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2105
2106 // format match
2107 if (format != AUDIO_FORMAT_INVALID) {
2108 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002109 PolicyAudioPort::kFormatDistanceMax -
2110 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002111 }
2112
2113 // primary output match
2114 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2115
2116 // compare match criteria by priority then value
2117 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2118 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2119 bestMatchCriteria = currentMatchCriteria;
2120 bestOutput = output;
2121
2122 std::stringstream result;
2123 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2124 std::ostream_iterator<int>(result, " "));
2125 ALOGV("%s new bestOutput %d criteria %s",
2126 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002127 }
2128 }
2129
Eric Laurent16c66dd2019-05-01 17:54:10 -07002130 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002131}
2132
Eric Laurent8fc147b2018-07-22 19:13:55 -07002133status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002134{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002135 ALOGV("%s portId %d", __FUNCTION__, portId);
2136
2137 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2138 if (outputDesc == 0) {
2139 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002140 return BAD_VALUE;
2141 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002142 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002143
Eric Laurent8fc147b2018-07-22 19:13:55 -07002144 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002145 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002146
Eric Laurent733ce942017-12-07 12:18:25 -08002147 status_t status = outputDesc->start();
2148 if (status != NO_ERROR) {
2149 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002150 }
2151
Eric Laurent97ac8712018-07-27 18:59:02 -07002152 uint32_t delayMs;
2153 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002154
2155 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002156 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002157 if (status == DEAD_OBJECT) {
2158 sp<SwAudioOutputDescriptor> desc =
2159 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2160 if (desc == nullptr) {
2161 // This is not common, it may indicate something wrong with the HAL.
2162 ALOGE("%s unable to open output with default config", __func__);
2163 return status;
2164 }
2165 desc->mUsePreferredMixerAttributes = true;
2166 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002167 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002168 }
jiabina84c3d32022-12-02 18:59:55 +00002169
2170 // If the client is the first one active on preferred mixer parameters, reopen the output
2171 // if the current mixer parameters doesn't match the preferred one.
2172 if (outputDesc->devices().size() == 1) {
2173 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2174 outputDesc->devices()[0]->getId(), client->strategy());
2175 if (info != nullptr && info->getUid() == client->uid()) {
2176 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2177 info->getConfigBase(), info->getFlags())) {
2178 stopSource(outputDesc, client);
2179 outputDesc->stop();
2180 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2181 config.channel_mask = info->getConfigBase().channel_mask;
2182 config.sample_rate = info->getConfigBase().sample_rate;
2183 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002184 sp<SwAudioOutputDescriptor> desc =
2185 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2186 if (desc == nullptr) {
2187 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002188 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002189 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002190 // Intentionally return error to let the client side resending request for
2191 // creating and starting.
2192 return DEAD_OBJECT;
2193 }
2194 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002195 if (info->getActiveClientCount() == 1 &&
2196 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2197 // If it is first bit-perfect client, reroute all clients that will be routed to
2198 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2199 PortHandleVector clientsToInvalidate;
2200 for (size_t i = 0; i < mOutputs.size(); i++) {
2201 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002202 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002203 continue;
2204 }
2205 for (const auto& c : mOutputs[i]->getClientIterable()) {
2206 clientsToInvalidate.push_back(c->portId());
2207 }
2208 }
2209 if (!clientsToInvalidate.empty()) {
2210 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2211 __func__);
2212 mpClientInterface->invalidateTracks(clientsToInvalidate);
2213 }
2214 }
jiabina84c3d32022-12-02 18:59:55 +00002215 }
2216 }
2217
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002218 if (client->hasPreferredDevice()) {
2219 // playback activity with preferred device impacts routing occurred, inform upper layers
2220 mpClientInterface->onRoutingUpdated();
2221 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002222 if (delayMs != 0) {
2223 usleep(delayMs * 1000);
2224 }
2225
2226 return status;
2227}
2228
Eric Laurent96d1dda2022-03-14 17:14:19 +01002229bool AudioPolicyManager::isLeUnicastActive() const {
2230 if (isInCall()) {
2231 return true;
2232 }
2233 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2234}
2235
2236bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2237 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2238 return false;
2239 }
2240 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2241 ALOGV("%s active %d", __func__, active);
2242 return active;
2243}
2244
Eric Laurent97ac8712018-07-27 18:59:02 -07002245status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2246 const sp<TrackClientDescriptor>& client,
2247 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002248{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002249 // cannot start playback of STREAM_TTS if any other output is being used
2250 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002251
2252 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002253 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002254 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002255 auto clientStrategy = client->strategy();
2256 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002257 if (stream == AUDIO_STREAM_TTS) {
2258 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002259 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002260 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002261 return INVALID_OPERATION;
2262 } else {
2263 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2264 }
2265 } else {
2266 // some playback other than beacon starts
2267 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2268 }
2269
Eric Laurent77305a62016-07-25 16:39:22 -07002270 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002271 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002272 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002273
François Gaffie11d30102018-11-02 16:09:09 +01002274 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002275 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002276 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002277 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002278 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002279 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002280 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002281 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002282 } else {
2283 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002284 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002285 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2286 AUDIO_FORMAT_DEFAULT);
2287 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2288 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002289 }
2290
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002291 // requiresMuteCheck is false when we can bypass mute strategy.
2292 // It covers a common case when there is no materially active audio
2293 // and muting would result in unnecessary delay and dropped audio.
2294 const uint32_t outputLatencyMs = outputDesc->latency();
2295 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002296 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002297
Eric Laurente552edb2014-03-10 17:42:56 -07002298 // increment usage count for this stream on the requested output:
2299 // NOTE that the usage count is the same for duplicated output and hardware output which is
2300 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002301 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002302
2303 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002304 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002305 // Preferred device may be exclusive, use only if no other active clients on this output
2306 devices = DeviceVector(
2307 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2308 } else {
2309 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2310 }
François Gaffie11d30102018-11-02 16:09:09 +01002311 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002312 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002313 }
2314 }
Eric Laurente552edb2014-03-10 17:42:56 -07002315
François Gaffiec005e562018-11-06 15:04:49 +01002316 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002317 selectOutputForMusicEffects();
2318 }
2319
François Gaffie1c878552018-11-22 16:53:21 +01002320 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002321 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002322 if (devices.isEmpty()) {
2323 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002324 }
François Gaffiec005e562018-11-06 15:04:49 +01002325 bool shouldWait =
2326 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2327 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2328 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002329 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002330 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002331 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002332 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002333 // An output has a shared device if
2334 // - managed by the same hw module
2335 // - supports the currently selected device
2336 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002337 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002338
Eric Laurent77305a62016-07-25 16:39:22 -07002339 // force a device change if any other output is:
2340 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002341 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002342 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002343 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002344 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002345 // change the device currently selected by the other output.
2346 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002347 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002348 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002349 force = true;
2350 }
2351 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002352 // a notification so that audio focus effect can propagate, or that a mute/unmute
2353 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002354 const uint32_t latencyMs = desc->latency();
2355 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2356
2357 if (shouldWait && isActive && (waitMs < latencyMs)) {
2358 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002359 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002360
2361 // Require mute check if another output is on a shared device
2362 // and currently active to have proper drain and avoid pops.
2363 // Note restoring AudioTracks onto this output needs to invoke
2364 // a volume ramp if there is no mute.
2365 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002366 }
2367 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002368
jiabin3ff8d7d2022-12-13 06:27:44 +00002369 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2370 // If the output is open with preferred mixer attributes, but the routed device is
2371 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2372 // changed.
2373 return DEAD_OBJECT;
2374 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002375 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302376 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2377 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002378
Eric Laurente552edb2014-03-10 17:42:56 -07002379 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002380 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002381 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002382 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002383 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002384 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002385 outputDesc->useHwGain() /*force*/)) {
2386 // request AudioService to reinitialize the volume curves asynchronously
2387 ALOGE("checkAndSetVolume failed, requesting volume range init");
2388 mpClientInterface->onVolumeRangeInitRequest();
2389 };
Eric Laurente552edb2014-03-10 17:42:56 -07002390
2391 // update the outputs if starting an output with a stream that can affect notification
2392 // routing
2393 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002394
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002395 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002396 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002397 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002398 }
Eric Laurentdc462862016-07-19 12:29:53 -07002399
2400 if (waitMs > muteWaitMs) {
2401 *delayMs = waitMs - muteWaitMs;
2402 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002403
2404 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2405 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2406 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2407 // change occurs after the MixerThread starts and causes a stream volume
2408 // glitch.
2409 //
2410 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002411 }
Eric Laurentdc462862016-07-19 12:29:53 -07002412
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002413 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002414 mEngine->getForceUse(
2415 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002416 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002417 }
2418
Eric Laurent97ac8712018-07-27 18:59:02 -07002419 // Automatically enable the remote submix input when output is started on a re routing mix
2420 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002421 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2422 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002423 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2424 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2425 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002426 "remote-submix",
2427 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002428 }
2429
Eric Laurent96d1dda2022-03-14 17:14:19 +01002430 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2431
Eric Laurente552edb2014-03-10 17:42:56 -07002432 return NO_ERROR;
2433}
2434
Eric Laurent96d1dda2022-03-14 17:14:19 +01002435void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2436 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2437 bool isUnicastActive = isLeUnicastActive();
2438
2439 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002440 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002441 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2442 for (size_t i = 0; i < mOutputs.size(); i++) {
2443 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2444 if (desc != ignoredOutput && desc->isActive()
2445 && ((isUnicastActive &&
2446 !desc->devices().
2447 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2448 || (wasUnicastActive &&
2449 !desc->devices().getDevicesFromTypes(
2450 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2451 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2452 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002453 if (desc->mUsePreferredMixerAttributes && force) {
2454 // If the device is using preferred mixer attributes, the output need to reopen
2455 // with default configuration when the new selected devices are different from
2456 // current routing devices.
2457 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2458 continue;
2459 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302460 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002461 // re-apply device specific volume if not done by setOutputDevice()
2462 if (!force) {
2463 applyStreamVolumes(desc, newDevices.types(), delayMs);
2464 }
2465 }
2466 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002467 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002468 }
2469}
2470
Eric Laurent8fc147b2018-07-22 19:13:55 -07002471status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002472{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002473 ALOGV("%s portId %d", __FUNCTION__, portId);
2474
2475 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2476 if (outputDesc == 0) {
2477 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002478 return BAD_VALUE;
2479 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002480 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002481
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002482 if (client->hasPreferredDevice(true)) {
2483 // playback activity with preferred device impacts routing occurred, inform upper layers
2484 mpClientInterface->onRoutingUpdated();
2485 }
2486
Eric Laurent97ac8712018-07-27 18:59:02 -07002487 ALOGV("stopOutput() output %d, stream %d, session %d",
2488 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002489
Eric Laurent97ac8712018-07-27 18:59:02 -07002490 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002491
Eric Laurent733ce942017-12-07 12:18:25 -08002492 if (status == NO_ERROR ) {
2493 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002494 } else {
2495 return status;
2496 }
2497
2498 if (outputDesc->devices().size() == 1) {
2499 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2500 outputDesc->devices()[0]->getId(), client->strategy());
2501 if (info != nullptr && info->getUid() == client->uid()) {
2502 info->decreaseActiveClient();
2503 if (info->getActiveClientCount() == 0) {
2504 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2505 }
2506 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002507 }
2508 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002509}
2510
Eric Laurent97ac8712018-07-27 18:59:02 -07002511status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2512 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002513{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002514 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002515 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002516 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002517 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002518
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002519 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2520
François Gaffie1c878552018-11-22 16:53:21 +01002521 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2522 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002523 // Automatically disable the remote submix input when output is stopped on a
2524 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002525 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002526 if (isSingleDeviceType(
2527 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002528 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002529 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002530 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2531 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002532 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002533 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002534 }
2535 }
2536 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002537 if (client->hasPreferredDevice(true) &&
2538 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002539 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002540 forceDeviceUpdate = true;
2541 }
2542
Eric Laurente552edb2014-03-10 17:42:56 -07002543 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002544 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002545
Eric Laurente552edb2014-03-10 17:42:56 -07002546 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002547 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002548 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002549 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002550
2551 // If the routing does not change, if an output is routed on a device using HwGain
2552 // (aka setAudioPortConfig) and there are still active clients following different
2553 // volume group(s), force reapply volume
2554 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2555 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2556
Eric Laurente552edb2014-03-10 17:42:56 -07002557 // delay the device switch by twice the latency because stopOutput() is executed when
2558 // the track stop() command is received and at that time the audio track buffer can
2559 // still contain data that needs to be drained. The latency only covers the audio HAL
2560 // and kernel buffers. Also the latency does not always include additional delay in the
2561 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302562 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002563 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002564
2565 // force restoring the device selection on other active outputs if it differs from the
2566 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002567 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002568 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002569 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002570 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002571 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002572 desc->isActive() &&
2573 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002574 (newDevices != desc->devices())) {
2575 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2576 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002577
jiabin3ff8d7d2022-12-13 06:27:44 +00002578 if (desc->mUsePreferredMixerAttributes && force) {
2579 // If the device is using preferred mixer attributes, the output need to
2580 // reopen with default configuration when the new selected devices are
2581 // different from current routing devices.
2582 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2583 continue;
2584 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302585 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002586
Eric Laurent57de36c2016-09-28 16:59:11 -07002587 // re-apply device specific volume if not done by setOutputDevice()
2588 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002589 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002590 }
Eric Laurente552edb2014-03-10 17:42:56 -07002591 }
2592 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002593 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002594 // update the outputs if stopping one with a stream that can affect notification routing
2595 handleNotificationRoutingForStream(stream);
2596 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002597
2598 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2599 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002600 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002601 }
2602
François Gaffiec005e562018-11-06 15:04:49 +01002603 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002604 selectOutputForMusicEffects();
2605 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002606
2607 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2608
Eric Laurente552edb2014-03-10 17:42:56 -07002609 return NO_ERROR;
2610 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002611 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002612 return INVALID_OPERATION;
2613 }
2614}
2615
jiabinbce0c1d2020-10-05 11:20:18 -07002616bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002617{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002618 ALOGV("%s portId %d", __FUNCTION__, portId);
2619
2620 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2621 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002622 // If an output descriptor is closed due to a device routing change,
2623 // then there are race conditions with releaseOutput from tracks
2624 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2625 // destroyed shortly thereafter.
2626 //
2627 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002628 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002629 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002630 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002631
2632 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002633
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302634 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2635 if (outputDesc->isClientActive(client)) {
2636 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2637 stopOutput(portId);
2638 }
2639
Eric Laurent8fc147b2018-07-22 19:13:55 -07002640 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2641 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002642 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002643 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002644 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002645 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002646 if (--outputDesc->mDirectOpenCount == 0) {
2647 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002648 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002649 }
2650 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302651
Andy Hung39efb7a2018-09-26 15:39:28 -07002652 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002653 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2654 // The output is pending reopened to query dynamic profiles and
2655 // there is no active clients
2656 closeOutput(outputDesc->mIoHandle);
2657 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2658 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2659 if (newOutputDesc == nullptr) {
2660 ALOGE("%s failed to open output", __func__);
2661 }
2662 return true;
2663 }
2664 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002665}
2666
Eric Laurentcaf7f482014-11-25 17:50:47 -08002667status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2668 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002669 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002670 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002671 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002672 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002673 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002674 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002675 input_type_t *inputType,
2676 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002677{
François Gaffiec005e562018-11-06 15:04:49 +01002678 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002679 "flags %#x attributes=%s requested device ID %d",
2680 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2681 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002682
Eric Laurentad2e7b92017-09-14 20:06:42 -07002683 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002684 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002685 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002686 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002687 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002688 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002689 sp<RecordClientDescriptor> clientDesc;
2690 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002691 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002692 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002693
2694 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2695 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2696 return INVALID_OPERATION;
2697 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002698
Francois Gaffie716e1432019-01-14 16:58:59 +01002699 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2700 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002701 }
2702
Paul McLean466dc8e2015-04-17 13:15:36 -06002703 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002704 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002705 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002706
Eric Laurentad2e7b92017-09-14 20:06:42 -07002707 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2708 // possible
2709 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2710 *input != AUDIO_IO_HANDLE_NONE) {
2711 ssize_t index = mInputs.indexOfKey(*input);
2712 if (index < 0) {
2713 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2714 status = BAD_VALUE;
2715 goto error;
2716 }
2717 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002718 RecordClientVector clients = inputDesc->getClientsForSession(session);
2719 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002720 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2721 status = BAD_VALUE;
2722 goto error;
2723 }
2724 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2725 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002726 // corresponds to a new client and is only permitted from the same UID.
2727 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002728 if (clients.size() > 1) {
2729 for (const auto& client : clients) {
2730 // The client map is ordered by key values (portId) and portIds are allocated
2731 // incrementaly. So the first client in this list is the one opened by audio flinger
2732 // when the mmap stream is created and should be ignored as it does not correspond
2733 // to an actual client
2734 if (client == *clients.cbegin()) {
2735 continue;
2736 }
2737 if (uid != client->uid() && !client->isSilenced()) {
2738 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2739 uid, client->portId(), client->uid());
2740 status = INVALID_OPERATION;
2741 goto error;
2742 }
Eric Laurent331679c2018-04-16 17:03:16 -07002743 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002744 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002745 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002746 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002747
Eric Laurentfecbceb2021-02-09 14:46:43 +01002748 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002749 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002750 }
2751
2752 *input = AUDIO_IO_HANDLE_NONE;
2753 *inputType = API_INPUT_INVALID;
2754
Francois Gaffie716e1432019-01-14 16:58:59 +01002755 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002756 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002757 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002758 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002759 ALOGW("%s could not find input mix for attr %s",
2760 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002761 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002762 }
jiabinc1de2df2019-05-07 14:26:40 -07002763 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2764 String8(attr->tags + strlen("addr=")),
2765 AUDIO_FORMAT_DEFAULT);
2766 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002767 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002768 __func__, attributes.source, attributes.tags);
2769 status = BAD_VALUE;
2770 goto error;
2771 }
2772
Kevin Rocard25f9b052019-02-27 15:08:54 -08002773 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2774 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2775 } else {
2776 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2777 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002778 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002779 if (explicitRoutingDevice != nullptr) {
2780 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002781 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002782 // Prevent from storing invalid requested device id in clients
2783 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002784 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002785 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2786 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002787 }
François Gaffie11d30102018-11-02 16:09:09 +01002788 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002789 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002790 status = BAD_VALUE;
2791 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002792 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002793 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2794 *inputType = API_INPUT_MIX_CAPTURE;
2795 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002796 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2797 // there is an external policy, but this input is attached to a mix of recorders,
2798 // meaning it receives audio injected into the framework, so the recorder doesn't
2799 // know about it and is therefore considered "legacy"
2800 *inputType = API_INPUT_LEGACY;
2801 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002802 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002803 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002804 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002805 } else {
2806 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002807 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002808
Eric Laurent599c7582015-12-07 18:05:55 -08002809 }
2810
François Gaffiec005e562018-11-06 15:04:49 +01002811 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002812 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002813 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002814 AudioProfileVector profiles;
2815 status_t ret = getProfilesForDevices(
2816 DeviceVector(device), profiles, flags, true /*isInput*/);
2817 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002818 const auto channels = profiles[0]->getChannels();
2819 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2820 config->channel_mask = *channels.begin();
2821 }
2822 const auto sampleRates = profiles[0]->getSampleRates();
2823 if (!sampleRates.empty() &&
2824 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2825 config->sample_rate = *sampleRates.begin();
2826 }
jiabinf1c73972022-04-14 16:28:52 -07002827 config->format = profiles[0]->getFormat();
2828 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002829 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002830 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002831
Eric Laurent8f42ea12018-08-08 09:08:25 -07002832exit:
2833
François Gaffiec005e562018-11-06 15:04:49 +01002834 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2835 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002836
Francois Gaffie716e1432019-01-14 16:58:59 +01002837 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002838 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002839 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002840
Mikhail Naganov2996f672019-04-18 12:29:59 -07002841 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002842 requestedDeviceId, attributes.source, flags,
2843 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002844 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002845 // Move (if found) effect for the client session to its input
2846 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002847 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002848
2849 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2850 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002851
Eric Laurent599c7582015-12-07 18:05:55 -08002852 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002853
2854error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002855 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002856}
2857
2858
François Gaffie11d30102018-11-02 16:09:09 +01002859audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002860 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002861 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002862 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002863 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002864 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002865{
2866 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002867 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002868 bool isSoundTrigger = false;
2869
François Gaffiec005e562018-11-06 15:04:49 +01002870 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002871 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2872 if (index >= 0) {
2873 input = mSoundTriggerSessions.valueFor(session);
2874 isSoundTrigger = true;
2875 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2876 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2877 } else {
2878 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002879 }
François Gaffiec005e562018-11-06 15:04:49 +01002880 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002881 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002882 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002883 }
2884
Carter Hsua3abb402021-10-26 11:11:20 +08002885 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2886 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2887 }
2888
Eric Laurentfe231122017-11-17 17:48:06 -08002889 // sampling rate and flags may be updated by getInputProfile
2890 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2891 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002892 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002893 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002894 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002895 // find a compatible input profile (not necessarily identical in parameters)
2896 sp<IOProfile> profile = getInputProfile(
2897 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2898 if (profile == nullptr) {
2899 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002900 }
jiabin2fd710d2022-05-02 23:20:22 +00002901
Glenn Kasten05ddca52016-02-11 08:17:12 -08002902 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002903 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002904 if (samplingRate == 0) {
2905 samplingRate = profileSamplingRate;
2906 }
Eric Laurente552edb2014-03-10 17:42:56 -07002907
Eric Laurent322b4d22015-04-03 15:57:54 -07002908 if (profile->getModuleHandle() == 0) {
2909 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002910 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002911 }
2912
Eric Laurentec376dc2021-04-08 20:41:22 +02002913 // Reuse an already opened input if a client with the same session ID already exists
2914 // on that input
2915 for (size_t i = 0; i < mInputs.size(); i++) {
2916 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2917 if (desc->mProfile != profile) {
2918 continue;
2919 }
2920 RecordClientVector clients = desc->clientsList();
2921 for (const auto &client : clients) {
2922 if (session == client->session()) {
2923 return desc->mIoHandle;
2924 }
2925 }
2926 }
2927
Eric Laurent3974e3b2017-12-07 17:58:43 -08002928 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002929 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002930 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002931 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002932 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002933 continue;
2934 }
2935 // if sound trigger, reuse input if used by other sound trigger on same session
2936 // else
2937 // reuse input if active client app is not in IDLE state
2938 //
2939 RecordClientVector clients = desc->clientsList();
2940 bool doClose = false;
2941 for (const auto& client : clients) {
2942 if (isSoundTrigger != client->isSoundTrigger()) {
2943 continue;
2944 }
2945 if (client->isSoundTrigger()) {
2946 if (session == client->session()) {
2947 return desc->mIoHandle;
2948 }
2949 continue;
2950 }
2951 if (client->active() && client->appState() != APP_STATE_IDLE) {
2952 return desc->mIoHandle;
2953 }
2954 doClose = true;
2955 }
2956 if (doClose) {
2957 closeInput(desc->mIoHandle);
2958 } else {
2959 i++;
2960 }
2961 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002962 }
2963
Eric Laurentfe231122017-11-17 17:48:06 -08002964 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002965
Eric Laurentfe231122017-11-17 17:48:06 -08002966 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2967 lConfig.sample_rate = profileSamplingRate;
2968 lConfig.channel_mask = profileChannelMask;
2969 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002970
François Gaffie11d30102018-11-02 16:09:09 +01002971 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002972
2973 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002974 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002975 (profileSamplingRate != lConfig.sample_rate) ||
2976 !audio_formats_match(profileFormat, lConfig.format) ||
2977 (profileChannelMask != lConfig.channel_mask)) {
2978 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002979 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002980 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002981 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002982 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002983 }
Eric Laurent599c7582015-12-07 18:05:55 -08002984 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002985 }
2986
Eric Laurentc722f302014-12-10 11:21:49 -08002987 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002988
Eric Laurent599c7582015-12-07 18:05:55 -08002989 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002990 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002991
Eric Laurent599c7582015-12-07 18:05:55 -08002992 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002993}
2994
Eric Laurent4eb58f12018-12-07 16:41:02 -08002995status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002996{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002997 ALOGV("%s portId %d", __FUNCTION__, portId);
2998
2999 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3000 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003001 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003002 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003003 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003004 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003005 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003006 if (client->active()) {
3007 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3008 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003009 }
3010
Eric Laurent8f42ea12018-08-08 09:08:25 -07003011 audio_session_t session = client->session();
3012
Eric Laurent4eb58f12018-12-07 16:41:02 -08003013 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003014
Eric Laurent4eb58f12018-12-07 16:41:02 -08003015 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003016
Eric Laurent4eb58f12018-12-07 16:41:02 -08003017 status_t status = inputDesc->start();
3018 if (status != NO_ERROR) {
3019 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003020 }
Eric Laurente552edb2014-03-10 17:42:56 -07003021
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003022 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003023 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003024 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003025
Eric Laurent8f42ea12018-08-08 09:08:25 -07003026 // indicate active capture to sound trigger service if starting capture from a mic on
3027 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003028 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003029 if (device != nullptr) {
3030 status = setInputDevice(input, device, true /* force */);
3031 } else {
3032 ALOGW("%s no new input device can be found for descriptor %d",
3033 __FUNCTION__, inputDesc->getId());
3034 status = BAD_VALUE;
3035 }
Eric Laurente552edb2014-03-10 17:42:56 -07003036
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003037 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003038 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003039 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003040 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003041 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3042 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003043 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003044 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003045
François Gaffie11d30102018-11-02 16:09:09 +01003046 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3047 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003048 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003049 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003050 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003051
Eric Laurent8f42ea12018-08-08 09:08:25 -07003052 // automatically enable the remote submix output when input is started if not
3053 // used by a policy mix of type MIX_TYPE_RECORDERS
3054 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003055 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003056 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003057 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003058 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003059 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3060 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003061 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 if (address != "") {
3063 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3064 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003065 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003066 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003067 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003068 } else if (status != NO_ERROR) {
3069 // Restore client activity state.
3070 inputDesc->setClientActive(client, false);
3071 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003072 }
3073
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003074 ALOGV("%s input %d source = %d status = %d exit",
3075 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003076
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003077 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003078}
3079
Eric Laurent8fc147b2018-07-22 19:13:55 -07003080status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003081{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003082 ALOGV("%s portId %d", __FUNCTION__, portId);
3083
3084 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3085 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003086 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003087 return BAD_VALUE;
3088 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003089 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003090 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003091 if (!client->active()) {
3092 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003093 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003094 }
Carter Hsue6139d52021-07-08 10:30:20 +08003095 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003096 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003097
Eric Laurent8f42ea12018-08-08 09:08:25 -07003098 inputDesc->stop();
3099 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003100 auto current_source = inputDesc->source();
3101 setInputDevice(input, getNewInputDevice(inputDesc),
3102 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003103 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003104 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003105 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003106 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003107 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3108 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003109 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003110 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003111
3112 // automatically disable the remote submix output when input is stopped if not
3113 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003114 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003115 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003116 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003117 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003118 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3119 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003120 }
3121 if (address != "") {
3122 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3123 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003124 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003125 }
3126 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003127 resetInputDevice(input);
3128
3129 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3130 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003131 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3132 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003133 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003134 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003135 }
3136 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003137 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003138 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003139}
3140
Eric Laurent8fc147b2018-07-22 19:13:55 -07003141void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003142{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003143 ALOGV("%s portId %d", __FUNCTION__, portId);
3144
3145 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3146 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003147 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003148 return;
3149 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003150 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003151 audio_io_handle_t input = inputDesc->mIoHandle;
3152
Eric Laurent8f42ea12018-08-08 09:08:25 -07003153 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003154
Andy Hung39efb7a2018-09-26 15:39:28 -07003155 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003156 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003157 if (inputDesc->getClientCount() > 0) {
3158 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003159 return;
3160 }
3161
Eric Laurent05b90f82014-08-27 15:32:29 -07003162 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003163 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003164 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003165}
3166
Eric Laurent8f42ea12018-08-08 09:08:25 -07003167void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003168{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003169 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003170
3171 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003172 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003173 }
3174}
3175
Eric Laurent8f42ea12018-08-08 09:08:25 -07003176void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3177{
3178 stopInput(portId);
3179 releaseInput(portId);
3180}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003181
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003182bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3183 if (input->clientsList().size() == 0
3184 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3185 return true;
3186 }
3187 for (const auto& client : input->clientsList()) {
3188 sp<DeviceDescriptor> device =
3189 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3190 client->session());
3191 if (!input->supportedDevices().contains(device)) {
3192 return true;
3193 }
3194 }
3195 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3196 return false;
3197}
3198
Eric Laurent0dd51852019-04-19 18:18:58 -07003199void AudioPolicyManager::checkCloseInputs() {
3200 // After connecting or disconnecting an input device, close input if:
3201 // - it has no client (was just opened to check profile) OR
3202 // - none of its supported devices are connected anymore OR
3203 // - one of its clients cannot be routed to one of its supported
3204 // devices anymore. Otherwise update device selection
3205 std::vector<audio_io_handle_t> inputsToClose;
3206 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003207 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003208 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003209 }
3210 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003211 for (const audio_io_handle_t handle : inputsToClose) {
3212 ALOGV("%s closing input %d", __func__, handle);
3213 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003214 }
Eric Laurentd4692962014-05-05 18:13:44 -07003215}
3216
François Gaffie251c7f02018-11-07 10:41:08 +01003217void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003218{
3219 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003220 if (indexMin < 0 || indexMax < 0) {
3221 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3222 return;
3223 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003224 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003225
3226 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003227 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3228 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003229 continue;
3230 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003231 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003232 }
Eric Laurente552edb2014-03-10 17:42:56 -07003233}
3234
Eric Laurente0720872014-03-11 09:30:41 -07003235status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003236 int index,
3237 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003238{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003239 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003240 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3241 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3242 return NO_ERROR;
3243 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003244 ALOGV("%s: stream %s attributes=%s", __func__,
3245 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003246 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003247}
3248
Eric Laurente0720872014-03-11 09:30:41 -07003249status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003250 int *index,
3251 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003252{
François Gaffiec005e562018-11-06 15:04:49 +01003253 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3254 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003255 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003256 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003257 deviceTypes = mEngine->getOutputDevicesForStream(
3258 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003259 }
jiabin9a3361e2019-10-01 09:38:30 -07003260 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003261}
3262
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003263status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003264 int index,
3265 audio_devices_t device)
3266{
3267 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003268 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3269 if (group == VOLUME_GROUP_NONE) {
3270 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003271 return BAD_VALUE;
3272 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003273 ALOGV("%s: group %d matching with %s index %d",
3274 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003275 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003276 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003277 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003278 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3279 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3280 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3281 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003282 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3283
3284 status = setVolumeCurveIndex(index, device, curves);
3285 if (status != NO_ERROR) {
3286 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3287 return status;
3288 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003289
jiabin9a3361e2019-10-01 09:38:30 -07003290 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003291 auto curCurvAttrs = curves.getAttributes();
3292 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3293 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003294 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003295 } else if (!curves.getStreamTypes().empty()) {
3296 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003297 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003298 } else {
3299 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3300 return BAD_VALUE;
3301 }
jiabin9a3361e2019-10-01 09:38:30 -07003302 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3303 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003304
François Gaffiecfe17322018-11-07 13:41:29 +01003305 // update volume on all outputs and streams matching the following:
3306 // - The requested stream (or a stream matching for volume control) is active on the output
3307 // - The device (or devices) selected by the engine for this stream includes
3308 // the requested device
3309 // - For non default requested device, currently selected device on the output is either the
3310 // requested device or one of the devices selected by the engine for this stream
3311 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3312 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003313 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003314 for (size_t i = 0; i < mOutputs.size(); i++) {
3315 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003316 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003317
jiabin9a3361e2019-10-01 09:38:30 -07003318 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3319 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003320 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003321
3322 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003323 continue;
3324 }
3325 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3326 curDevices.find(device) == curDevices.end()) {
3327 continue;
3328 }
3329 bool applyVolume = false;
3330 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3331 curSrcDevices.insert(device);
3332 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003333 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3334 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003335 } else {
3336 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3337 }
3338 if (!applyVolume) {
3339 continue; // next output
3340 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003341 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3342 // If a higher priority strategy is active, and the output is routed to a device with a
3343 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003344 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003345 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003346 // If the volume source is active with higher priority source, ensure at least Sw Muted
3347 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003348 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3349 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3350 false /*preferredDevice*/);
3351 if (activeClients.empty()) {
3352 continue;
3353 }
3354 bool isPreempted = false;
3355 bool isHigherPriority = productStrategy < strategy;
3356 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003357 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003358 ALOGV("%s: Strategy=%d (\nrequester:\n"
3359 " group %d, volumeGroup=%d attributes=%s)\n"
3360 " higher priority source active:\n"
3361 " volumeGroup=%d attributes=%s) \n"
3362 " on output %zu, bailing out", __func__, productStrategy,
3363 group, group, toString(attributes).c_str(),
3364 client->volumeSource(), toString(client->attributes()).c_str(), i);
3365 applyVolume = false;
3366 isPreempted = true;
3367 break;
3368 }
3369 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003370 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003371 applyVolume = true;
3372 }
3373 }
3374 if (isPreempted || applyVolume) {
3375 break;
3376 }
3377 }
3378 if (!applyVolume) {
3379 continue; // next output
3380 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003381 }
François Gaffieed91f582020-01-31 10:35:37 +01003382 //FIXME: workaround for truncated touch sounds
3383 // delayed volume change for system stream to be removed when the problem is
3384 // handled by system UI
3385 status_t volStatus = checkAndSetVolume(
3386 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003387 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003388 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3389 if (volStatus != NO_ERROR) {
3390 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003391 }
3392 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003393
3394 // update voice volume if the an active call route exists
3395 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3396 && (curSrcDevices.find(
3397 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3398 != curSrcDevices.end())) {
3399 bool isVoiceVolSrc;
3400 bool isBtScoVolSrc;
3401 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3402 isVoiceVolSrc, isBtScoVolSrc, __func__)
3403 && (isVoiceVolSrc || isBtScoVolSrc)) {
3404 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3405 }
3406 }
3407
François Gaffiecfe17322018-11-07 13:41:29 +01003408 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3409 return status;
3410}
3411
François Gaffieaaac0fd2018-11-22 17:56:39 +01003412status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003413 audio_devices_t device,
3414 IVolumeCurves &volumeCurves)
3415{
3416 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3417 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003418 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3419 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003420 (index > volumeCurves.getVolumeIndexMax())) {
3421 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3422 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3423 return BAD_VALUE;
3424 }
3425 if (!audio_is_output_device(device)) {
3426 return BAD_VALUE;
3427 }
3428
3429 // Force max volume if stream cannot be muted
3430 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3431
François Gaffieaaac0fd2018-11-22 17:56:39 +01003432 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003433 volumeCurves.addCurrentVolumeIndex(device, index);
3434 return NO_ERROR;
3435}
3436
3437status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3438 int &index,
3439 audio_devices_t device)
3440{
3441 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3442 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003443 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003444 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003445 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003446 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003447 }
jiabin9a3361e2019-10-01 09:38:30 -07003448 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003449}
3450
3451status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3452 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003453 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003454{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003455 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003456 return BAD_VALUE;
3457 }
jiabin9a3361e2019-10-01 09:38:30 -07003458 index = curves.getVolumeIndex(deviceTypes);
3459 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003460 return NO_ERROR;
3461}
3462
3463status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3464 int &index)
3465{
3466 index = getVolumeCurves(attr).getVolumeIndexMin();
3467 return NO_ERROR;
3468}
3469
3470status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3471 int &index)
3472{
3473 index = getVolumeCurves(attr).getVolumeIndexMax();
3474 return NO_ERROR;
3475}
3476
Eric Laurent36829f92017-04-07 19:04:42 -07003477audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003478{
3479 // select one output among several suitable for global effects.
3480 // The priority is as follows:
3481 // 1: An offloaded output. If the effect ends up not being offloadable,
3482 // AudioFlinger will invalidate the track and the offloaded output
3483 // will be closed causing the effect to be moved to a PCM output.
3484 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003485 // 3: The primary output
3486 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003487
François Gaffiec005e562018-11-06 15:04:49 +01003488 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3489 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003490 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003491
Eric Laurent36829f92017-04-07 19:04:42 -07003492 if (outputs.size() == 0) {
3493 return AUDIO_IO_HANDLE_NONE;
3494 }
Eric Laurente552edb2014-03-10 17:42:56 -07003495
Eric Laurent36829f92017-04-07 19:04:42 -07003496 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3497 bool activeOnly = true;
3498
3499 while (output == AUDIO_IO_HANDLE_NONE) {
3500 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3501 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3502 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3503
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003504 for (audio_io_handle_t output : outputs) {
3505 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003506 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003507 continue;
3508 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003509 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3510 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003511 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003512 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003513 }
3514 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003515 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003516 }
3517 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003518 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003519 }
3520 }
3521 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3522 output = outputOffloaded;
3523 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3524 output = outputDeepBuffer;
3525 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3526 output = outputPrimary;
3527 } else {
3528 output = outputs[0];
3529 }
3530 activeOnly = false;
3531 }
3532
3533 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003534 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3535 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003536 mMusicEffectOutput = output;
3537 }
3538
3539 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003540 return output;
3541}
3542
Eric Laurent36829f92017-04-07 19:04:42 -07003543audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3544{
3545 return selectOutputForMusicEffects();
3546}
3547
Eric Laurente0720872014-03-11 09:30:41 -07003548status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003549 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003550 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003551 int session,
3552 int id)
3553{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003554 if (session != AUDIO_SESSION_DEVICE) {
3555 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003556 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003557 index = mInputs.indexOfKey(io);
3558 if (index < 0) {
3559 ALOGW("registerEffect() unknown io %d", io);
3560 return INVALID_OPERATION;
3561 }
Eric Laurente552edb2014-03-10 17:42:56 -07003562 }
3563 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003564 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3565 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3566 || strategy == PRODUCT_STRATEGY_NONE));
3567 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003568}
3569
Eric Laurentc241b0d2018-11-28 09:08:49 -08003570status_t AudioPolicyManager::unregisterEffect(int id)
3571{
3572 if (mEffects.getEffect(id) == nullptr) {
3573 return INVALID_OPERATION;
3574 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003575 if (mEffects.isEffectEnabled(id)) {
3576 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3577 setEffectEnabled(id, false);
3578 }
3579 return mEffects.unregisterEffect(id);
3580}
3581
3582status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3583{
3584 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3585 if (effect == nullptr) {
3586 return INVALID_OPERATION;
3587 }
3588
3589 status_t status = mEffects.setEffectEnabled(id, enabled);
3590 if (status == NO_ERROR) {
3591 mInputs.trackEffectEnabled(effect, enabled);
3592 }
3593 return status;
3594}
3595
Eric Laurent6c796322019-04-09 14:13:17 -07003596
3597status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3598{
3599 mEffects.moveEffects(ids, io);
3600 return NO_ERROR;
3601}
3602
Eric Laurentc75307b2015-03-17 15:29:32 -07003603bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3604{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003605 auto vs = toVolumeSource(stream, false);
3606 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003607}
3608
3609bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3610{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003611 auto vs = toVolumeSource(stream, false);
3612 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003613}
3614
Eric Laurente0720872014-03-11 09:30:41 -07003615bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003616{
3617 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003618 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003619 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003620 return true;
3621 }
3622 }
3623 return false;
3624}
3625
Eric Laurent275e8e92014-11-30 15:14:47 -08003626// Register a list of custom mixes with their attributes and format.
3627// When a mix is registered, corresponding input and output profiles are
3628// added to the remote submix hw module. The profile contains only the
3629// parameters (sampling rate, format...) specified by the mix.
3630// The corresponding input remote submix device is also connected.
3631//
3632// When a remote submix device is connected, the address is checked to select the
3633// appropriate profile and the corresponding input or output stream is opened.
3634//
3635// When capture starts, getInputForAttr() will:
3636// - 1 look for a mix matching the address passed in attribtutes tags if any
3637// - 2 if none found, getDeviceForInputSource() will:
3638// - 2.1 look for a mix matching the attributes source
3639// - 2.2 if none found, default to device selection by policy rules
3640// At this time, the corresponding output remote submix device is also connected
3641// and active playback use cases can be transferred to this mix if needed when reconnecting
3642// after AudioTracks are invalidated
3643//
3644// When playback starts, getOutputForAttr() will:
3645// - 1 look for a mix matching the address passed in attribtutes tags if any
3646// - 2 if none found, look for a mix matching the attributes usage
3647// - 3 if none found, default to device and output selection by policy rules.
3648
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003649status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003650{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003651 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3652 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003653 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003654 sp<HwModule> rSubmixModule;
3655 // examine each mix's route type
3656 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003657 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003658 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3659 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3660 ALOGE("Unsupported Policy Mix %zu of %zu: "
3661 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3662 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003663 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003664 break;
3665 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003666 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3667 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003668 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003669 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3670 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003671 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003672 rSubmixModule = mHwModules.getModuleFromName(
3673 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3674 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003675 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003676 i);
3677 res = INVALID_OPERATION;
3678 break;
3679 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003680 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003681
Eric Laurent97ac8712018-07-27 18:59:02 -07003682 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003683 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003684 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003685 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003686 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3687 } else {
3688 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3689 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003690 }
François Gaffie036e1e92015-03-19 10:16:24 +01003691
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003692 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003693 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003694 res = INVALID_OPERATION;
3695 break;
3696 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003697 audio_config_t outputConfig = mix.mFormat;
3698 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003699 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3700 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003701 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3702 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003703 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003704 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3705 audio_is_linear_pcm(outputConfig.format)
3706 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003707 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003708 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3709 audio_is_linear_pcm(inputConfig.format)
3710 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003711
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003712 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003713 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003714 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003715 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003716 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003717 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003718 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003719 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3720 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003721 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003722 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003723 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003724
3725 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3726 mix.mDeviceType, mix.mDeviceAddress,
3727 String8(), AUDIO_FORMAT_DEFAULT);
3728 if (device == nullptr) {
3729 res = INVALID_OPERATION;
3730 break;
3731 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003732
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003733 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003734 // First try to find an already opened output supporting the device
3735 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003736 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003737
Eric Laurentc529cf62020-04-17 18:19:10 -07003738 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003739 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003740 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003741 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003742 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003743 } else {
3744 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003745 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003746 }
3747 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003748 // If no output found, try to find a direct output profile supporting the device
3749 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3750 sp<HwModule> module = mHwModules[i];
3751 for (size_t j = 0;
3752 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3753 j++) {
3754 sp<IOProfile> profile = module->getOutputProfiles()[j];
3755 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3756 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3757 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003758 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003759 res = INVALID_OPERATION;
3760 } else {
3761 foundOutput = true;
3762 }
3763 }
3764 }
3765 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003766 if (res != NO_ERROR) {
3767 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003768 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003769 res = INVALID_OPERATION;
3770 break;
3771 } else if (!foundOutput) {
3772 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003773 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003774 res = INVALID_OPERATION;
3775 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003776 } else {
3777 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003778 }
Eric Laurentc722f302014-12-10 11:21:49 -08003779 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003780 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003781 if (res != NO_ERROR) {
3782 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003783 } else if (checkOutputs) {
3784 checkForDeviceAndOutputChanges();
3785 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003786 }
3787 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003788}
3789
3790status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3791{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003792 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003793 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003794 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003795 sp<HwModule> rSubmixModule;
3796 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003797 for (const auto& mix : mixes) {
3798 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003799
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003800 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003801 rSubmixModule = mHwModules.getModuleFromName(
3802 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3803 if (rSubmixModule == 0) {
3804 res = INVALID_OPERATION;
3805 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003806 }
3807 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003808
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003809 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003810
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003811 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003812 res = INVALID_OPERATION;
3813 continue;
3814 }
3815
Kevin Rocard04ed0462019-05-02 17:53:24 -07003816 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003817 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003818 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3819 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003820 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003821 AUDIO_FORMAT_DEFAULT);
3822 if (res != OK) {
3823 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003824 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003825 }
3826 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003827 }
jiabin5740f082019-08-19 15:08:30 -07003828 rSubmixModule->removeOutputProfile(address.c_str());
3829 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003830
Kevin Rocard153f92d2018-12-18 18:33:28 -08003831 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003832 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003833 res = INVALID_OPERATION;
3834 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003835 } else {
3836 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003837 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003838 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003839 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003840 if (res == NO_ERROR && checkOutputs) {
3841 checkForDeviceAndOutputChanges();
3842 updateCallAndOutputRouting();
3843 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003844 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003845}
3846
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003847status_t AudioPolicyManager::updatePolicyMix(
3848 const AudioMix& mix,
3849 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3850 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3851 if (res == NO_ERROR) {
3852 checkForDeviceAndOutputChanges();
3853 updateCallAndOutputRouting();
3854 }
3855 return res;
3856}
3857
Mikhail Naganov100f0122018-11-29 11:22:16 -08003858void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3859{
3860 size_t i = 0;
3861 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3862 for (const auto& fmt : mManualSurroundFormats) {
3863 if (i++ != 0) dst->append(", ");
3864 std::string sfmt;
3865 FormatConverter::toString(fmt, sfmt);
3866 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3867 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3868 }
3869}
3870
Eric Laurentc529cf62020-04-17 18:19:10 -07003871// Returns true if all devices types match the predicate and are supported by one HW module
3872bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003873 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003874 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003875 const char *context,
3876 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003877 for (size_t i = 0; i < devices.size(); i++) {
3878 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003879 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003880 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003881 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003882 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003883 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003884 return false;
3885 }
3886 }
3887 return true;
3888}
3889
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003890void AudioPolicyManager::changeOutputDevicesMuteState(
3891 const AudioDeviceTypeAddrVector& devices) {
3892 ALOGVV("%s() num devices %zu", __func__, devices.size());
3893
3894 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3895 getSoftwareOutputsForDevices(devices);
3896
3897 for (size_t i = 0; i < outputs.size(); i++) {
3898 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3899 DeviceVector prevDevices = outputDesc->devices();
3900 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3901 }
3902}
3903
3904std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3905 const AudioDeviceTypeAddrVector& devices) const
3906{
3907 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3908 DeviceVector deviceDescriptors;
3909 for (size_t j = 0; j < devices.size(); j++) {
3910 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3911 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3912 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3913 ALOGE("%s: device type %#x address %s not supported or not an output device",
3914 __func__, devices[j].mType, devices[j].getAddress());
3915 continue;
3916 }
3917 deviceDescriptors.add(desc);
3918 }
3919 for (size_t i = 0; i < mOutputs.size(); i++) {
3920 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3921 continue;
3922 }
3923 outputs.push_back(mOutputs.valueAt(i));
3924 }
3925 return outputs;
3926}
3927
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003928status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003929 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003930 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003931 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3932 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003933 }
3934 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003935 if (res != NO_ERROR) {
3936 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3937 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003938 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003939
3940 checkForDeviceAndOutputChanges();
3941 updateCallAndOutputRouting();
3942
3943 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003944}
3945
3946status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3947 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003948 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3949 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003950 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003951 __FUNCTION__, uid);
3952 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003953 }
3954
Eric Laurentc529cf62020-04-17 18:19:10 -07003955 checkForDeviceAndOutputChanges();
3956 updateCallAndOutputRouting();
3957
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003958 return res;
3959}
3960
Eric Laurent2517af32020-11-25 15:31:27 +01003961
jiabin0a488932020-08-07 17:32:40 -07003962status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3963 device_role_t role,
3964 const AudioDeviceTypeAddrVector &devices) {
3965 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3966 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003967
Eric Laurentc529cf62020-04-17 18:19:10 -07003968 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003969 return BAD_VALUE;
3970 }
jiabin0a488932020-08-07 17:32:40 -07003971 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003972 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003973 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3974 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003975 return status;
3976 }
3977
3978 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003979
3980 bool forceVolumeReeval = false;
3981 // FIXME: workaround for truncated touch sounds
3982 // to be removed when the problem is handled by system UI
3983 uint32_t delayMs = 0;
3984 if (strategy == mCommunnicationStrategy) {
3985 forceVolumeReeval = true;
3986 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3987 updateInputRouting();
3988 }
3989 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003990
3991 return NO_ERROR;
3992}
3993
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003994void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3995 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003996{
3997 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003998 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003999 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004000 // Only apply special touch sound delay once
4001 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004002 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004003 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004004 for (size_t i = 0; i < mOutputs.size(); i++) {
4005 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4006 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004007 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4008 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004009 // As done in setDeviceConnectionState, we could also fix default device issue by
4010 // preventing the force re-routing in case of default dev that distinguishes on address.
4011 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004012 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004013 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4014 // If the device is using preferred mixer attributes, the output need to reopen
4015 // with default configuration when the new selected devices are different from
4016 // current routing devices.
4017 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4018 continue;
4019 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304020
4021 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4022 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004023 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004024 // Only apply special touch sound delay once
4025 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004026 }
4027 if (forceVolumeReeval && !newDevices.isEmpty()) {
4028 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4029 }
4030 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004031 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004032 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004033}
4034
Eric Laurent2517af32020-11-25 15:31:27 +01004035void AudioPolicyManager::updateInputRouting() {
4036 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304037 // Skip for hotword recording as the input device switch
4038 // is handled within sound trigger HAL
4039 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4040 continue;
4041 }
Eric Laurent2517af32020-11-25 15:31:27 +01004042 auto newDevice = getNewInputDevice(activeDesc);
4043 // Force new input selection if the new device can not be reached via current input
4044 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4045 setInputDevice(activeDesc->mIoHandle, newDevice);
4046 } else {
4047 closeInput(activeDesc->mIoHandle);
4048 }
4049 }
4050}
4051
Paul Wang5d7cdb52022-11-22 09:45:06 +00004052status_t
4053AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4054 device_role_t role,
4055 const AudioDeviceTypeAddrVector &devices) {
4056 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4057 dumpAudioDeviceTypeAddrVector(devices).c_str());
4058
Eric Laurent78fedbf2023-03-09 14:40:44 +01004059 if (!areAllDevicesSupported(
4060 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004061 return BAD_VALUE;
4062 }
4063 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4064 if (status != NO_ERROR) {
4065 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4066 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4067 return status;
4068 }
4069
4070 checkForDeviceAndOutputChanges();
4071
4072 bool forceVolumeReeval = false;
4073 // TODO(b/263479999): workaround for truncated touch sounds
4074 // to be removed when the problem is handled by system UI
4075 uint32_t delayMs = 0;
4076 if (strategy == mCommunnicationStrategy) {
4077 forceVolumeReeval = true;
4078 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4079 updateInputRouting();
4080 }
4081 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4082
4083 return NO_ERROR;
4084}
4085
4086status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4087 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004088{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004089 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004090
Paul Wang5d7cdb52022-11-22 09:45:06 +00004091 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004092 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004093 ALOGW_IF(status != NAME_NOT_FOUND,
4094 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004095 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004096 return status;
4097 }
4098
4099 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004100
4101 bool forceVolumeReeval = false;
4102 // FIXME: workaround for truncated touch sounds
4103 // to be removed when the problem is handled by system UI
4104 uint32_t delayMs = 0;
4105 if (strategy == mCommunnicationStrategy) {
4106 forceVolumeReeval = true;
4107 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4108 updateInputRouting();
4109 }
4110 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004111
4112 return NO_ERROR;
4113}
4114
jiabin0a488932020-08-07 17:32:40 -07004115status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4116 device_role_t role,
4117 AudioDeviceTypeAddrVector &devices) {
4118 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004119}
4120
Jiabin Huang3b98d322020-09-03 17:54:16 +00004121status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4122 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4123 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4124 dumpAudioDeviceTypeAddrVector(devices).c_str());
4125
Mikhail Naganov55773032020-10-01 15:08:13 -07004126 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004127 return BAD_VALUE;
4128 }
4129 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4130 ALOGW_IF(status != NO_ERROR,
4131 "Engine could not set preferred devices %s for audio source %d role %d",
4132 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4133
4134 return status;
4135}
4136
4137status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4138 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4139 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4140 dumpAudioDeviceTypeAddrVector(devices).c_str());
4141
Mikhail Naganov55773032020-10-01 15:08:13 -07004142 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004143 return BAD_VALUE;
4144 }
4145 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4146 ALOGW_IF(status != NO_ERROR,
4147 "Engine could not add preferred devices %s for audio source %d role %d",
4148 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4149
Eric Laurent2517af32020-11-25 15:31:27 +01004150 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004151 return status;
4152}
4153
4154status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4155 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4156{
4157 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4158 dumpAudioDeviceTypeAddrVector(devices).c_str());
4159
Eric Laurent78fedbf2023-03-09 14:40:44 +01004160 if (!areAllDevicesSupported(
4161 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004162 return BAD_VALUE;
4163 }
4164
4165 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4166 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004167 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004168 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004169 if (status == NO_ERROR) {
4170 updateInputRouting();
4171 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004172 return status;
4173}
4174
4175status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4176 device_role_t role) {
4177 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4178
4179 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004180 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004181 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004182 if (status == NO_ERROR) {
4183 updateInputRouting();
4184 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004185 return status;
4186}
4187
4188status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4189 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4190 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4191}
4192
Oscar Azucena90e77632019-11-27 17:12:28 -08004193status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004194 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004195 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004196 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4197 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004198 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004199 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4200 if (status != NO_ERROR) {
4201 ALOGE("%s() could not set device affinity for userId %d",
4202 __FUNCTION__, userId);
4203 return status;
4204 }
4205
4206 // reevaluate outputs for all devices
4207 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004208 changeOutputDevicesMuteState(devices);
4209 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4210 true /* skipDelays */);
4211 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004212
4213 return NO_ERROR;
4214}
4215
4216status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004217 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004218 AudioDeviceTypeAddrVector devices;
4219 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004220 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4221 if (status != NO_ERROR) {
4222 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4223 __FUNCTION__, userId);
4224 return status;
4225 }
4226
4227 // reevaluate outputs for all devices
4228 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004229 changeOutputDevicesMuteState(devices);
4230 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4231 true /* skipDelays */);
4232 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004233
4234 return NO_ERROR;
4235}
4236
Andy Hungc29d82b2018-10-05 12:23:17 -07004237void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004238{
Andy Hungc29d82b2018-10-05 12:23:17 -07004239 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004240 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004241 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004242 std::string stateLiteral;
4243 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004244 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004245 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4246 "communications", "media", "record", "dock", "system",
4247 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4248 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4249 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004250 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4251 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4252 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4253 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4254 dst->append(" (MANUAL: ");
4255 dumpManualSurroundFormats(dst);
4256 dst->append(")");
4257 }
4258 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004259 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004260 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4261 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004262 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004263 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004264
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004265 dst->append("\n");
4266 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4267 dst->append("\n");
4268 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004269 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004270 mOutputs.dump(dst);
4271 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004272 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004273 mAudioPatches.dump(dst);
4274 mPolicyMixes.dump(dst);
4275 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004276
Kevin Rocardb99cc752019-03-21 20:52:24 -07004277 dst->appendFormat(" AllowedCapturePolicies:\n");
4278 for (auto& policy : mAllowedCapturePolicies) {
4279 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4280 }
4281
jiabina84c3d32022-12-02 18:59:55 +00004282 dst->appendFormat(" Preferred mixer audio configuration:\n");
4283 for (const auto it : mPreferredMixerAttrInfos) {
4284 dst->appendFormat(" - device port id: %d\n", it.first);
4285 for (const auto preferredMixerInfoIt : it.second) {
4286 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4287 preferredMixerInfoIt.second->dump(dst);
4288 }
4289 }
4290
François Gaffiec005e562018-11-06 15:04:49 +01004291 dst->appendFormat("\nPolicy Engine dump:\n");
4292 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004293}
4294
4295status_t AudioPolicyManager::dump(int fd)
4296{
4297 String8 result;
4298 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004299 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004300 return NO_ERROR;
4301}
4302
Kevin Rocardb99cc752019-03-21 20:52:24 -07004303status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4304{
4305 mAllowedCapturePolicies[uid] = capturePolicy;
4306 return NO_ERROR;
4307}
4308
Eric Laurente552edb2014-03-10 17:42:56 -07004309// This function checks for the parameters which can be offloaded.
4310// This can be enhanced depending on the capability of the DSP and policy
4311// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004312audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004313{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004314 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004315 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004316 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004317 offloadInfo.format,
4318 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4319 offloadInfo.has_video);
4320
jiabin2b9d5a12021-12-10 01:06:29 +00004321 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004322 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004323 }
4324
4325 // See if there is a profile to support this.
4326 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004327 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004328 offloadInfo.sample_rate,
4329 offloadInfo.format,
4330 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004331 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4332 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004333 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4334 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4335 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004336 if (profile == nullptr) {
4337 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4338 }
4339 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4340 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4341 }
4342 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004343}
4344
Michael Chana94fbb22018-04-24 14:31:19 +10004345bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4346 const audio_attributes_t& attributes) {
4347 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004348 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004349 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4350 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004351 config.sample_rate,
4352 config.format,
4353 config.channel_mask,
4354 output_flags,
4355 true /* directOnly */);
4356 ALOGV("%s() profile %sfound with name: %s, "
4357 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4358 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004359 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004360 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004361
4362 // also try the MSD module if compatible profile not found
4363 if (profile == nullptr) {
4364 profile = getMsdProfileForOutput(outputDevices,
4365 config.sample_rate,
4366 config.format,
4367 config.channel_mask,
4368 output_flags,
4369 true /* directOnly */);
4370 ALOGV("%s() MSD profile %sfound with name: %s, "
4371 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4372 __FUNCTION__, profile != 0 ? "" : "NOT ",
4373 (profile != 0 ? profile->getTagName().c_str() : "null"),
4374 config.sample_rate, config.format, config.channel_mask, output_flags);
4375 }
4376 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004377}
4378
jiabin2b9d5a12021-12-10 01:06:29 +00004379bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4380 bool durationIgnored) {
4381 if (mMasterMono) {
4382 return false; // no offloading if mono is set.
4383 }
4384
4385 // Check if offload has been disabled
4386 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4387 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4388 return false;
4389 }
4390
4391 // Check if stream type is music, then only allow offload as of now.
4392 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4393 {
4394 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4395 return false;
4396 }
4397
4398 //TODO: enable audio offloading with video when ready
4399 const bool allowOffloadWithVideo =
4400 property_get_bool("audio.offload.video", false /* default_value */);
4401 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4402 ALOGV("%s: has_video == true, returning false", __func__);
4403 return false;
4404 }
4405
4406 //If duration is less than minimum value defined in property, return false
4407 const int min_duration_secs = property_get_int32(
4408 "audio.offload.min.duration.secs", -1 /* default_value */);
4409 if (!durationIgnored) {
4410 if (min_duration_secs >= 0) {
4411 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4412 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4413 __func__, min_duration_secs);
4414 return false;
4415 }
4416 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4417 ALOGV("%s: Offload denied by duration < default min(=%u)",
4418 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4419 return false;
4420 }
4421 }
4422
4423 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4424 // creating an offloaded track and tearing it down immediately after start when audioflinger
4425 // detects there is an active non offloadable effect.
4426 // FIXME: We should check the audio session here but we do not have it in this context.
4427 // This may prevent offloading in rare situations where effects are left active by apps
4428 // in the background.
4429 if (mEffects.isNonOffloadableEffectEnabled()) {
4430 return false;
4431 }
4432
4433 return true;
4434}
4435
4436audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4437 const audio_config_t *config) {
4438 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4439 offloadInfo.format = config->format;
4440 offloadInfo.sample_rate = config->sample_rate;
4441 offloadInfo.channel_mask = config->channel_mask;
4442 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4443 offloadInfo.has_video = false;
4444 offloadInfo.is_streaming = false;
4445 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4446
4447 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4448 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4449 audio_flags_to_audio_output_flags(attr->flags, &flags);
4450 // only retain flags that will drive compressed offload or passthrough
4451 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4452 if (offloadPossible) {
4453 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4454 }
4455 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4456
Dorin Drimusfae3c642022-03-17 18:36:30 +01004457 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004458 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004459 DeviceVector outputDevices = engineOutputDevices;
4460 // the MSD module checks for different conditions and output devices
4461 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4462 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4463 continue;
4464 }
4465 outputDevices = getMsdAudioOutDevices();
4466 }
jiabin2b9d5a12021-12-10 01:06:29 +00004467 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinde7ae442024-02-06 00:57:36 +00004468 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004469 config->sample_rate, nullptr /*updatedSamplingRate*/,
4470 config->format, nullptr /*updatedFormat*/,
4471 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabinde7ae442024-02-06 00:57:36 +00004472 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004473 continue;
4474 }
4475 // reject profiles not corresponding to a device currently available
4476 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4477 continue;
4478 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004479 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4480 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004481 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004482 != AUDIO_DIRECT_NOT_SUPPORTED) {
4483 // Already reports offload gapless supported. No need to report offload support.
4484 continue;
4485 }
4486 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4487 != AUDIO_OUTPUT_FLAG_NONE) {
4488 // If offload gapless is reported, no need to report offload support.
4489 directMode = (audio_direct_mode_t) ((directMode &
4490 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4491 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4492 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004493 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004494 }
4495 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004496 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004497 }
4498 }
4499 }
4500 return directMode;
4501}
4502
Dorin Drimusf2196d82022-01-03 12:11:18 +01004503status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4504 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004505 if (mEffects.isNonOffloadableEffectEnabled()) {
4506 return OK;
4507 }
jiabinf1c73972022-04-14 16:28:52 -07004508 DeviceVector devices;
4509 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004510 if (status != OK) {
4511 return status;
4512 }
4513 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4514 if (devices.empty()) {
4515 return OK; // no output devices for the attributes
4516 }
jiabinf1c73972022-04-14 16:28:52 -07004517 return getProfilesForDevices(devices, audioProfilesVector,
4518 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004519}
4520
jiabina84c3d32022-12-02 18:59:55 +00004521status_t AudioPolicyManager::getSupportedMixerAttributes(
4522 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4523 ALOGV("%s, portId=%d", __func__, portId);
4524 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4525 if (deviceDescriptor == nullptr) {
4526 ALOGE("%s the requested device is currently unavailable", __func__);
4527 return BAD_VALUE;
4528 }
jiabin96daffc2023-05-11 17:51:55 +00004529 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4530 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4531 deviceDescriptor->type());
4532 return BAD_VALUE;
4533 }
jiabina84c3d32022-12-02 18:59:55 +00004534 for (const auto& hwModule : mHwModules) {
4535 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4536 if (curProfile->supportsDevice(deviceDescriptor)) {
4537 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4538 }
4539 }
4540 }
4541 return NO_ERROR;
4542}
4543
4544status_t AudioPolicyManager::setPreferredMixerAttributes(
4545 const audio_attributes_t *attr,
4546 audio_port_handle_t portId,
4547 uid_t uid,
4548 const audio_mixer_attributes_t *mixerAttributes) {
4549 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4550 "mixerBehavior=%d}, uid=%d, portId=%u",
4551 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4552 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4553 mixerAttributes->mixer_behavior, uid, portId);
4554 if (attr->usage != AUDIO_USAGE_MEDIA) {
4555 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4556 return BAD_VALUE;
4557 }
4558 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4559 if (deviceDescriptor == nullptr) {
4560 ALOGE("%s the requested device is currently unavailable", __func__);
4561 return BAD_VALUE;
4562 }
4563 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4564 ALOGE("%s(%d), type=%d, is not a usb output device",
4565 __func__, portId, deviceDescriptor->type());
4566 return BAD_VALUE;
4567 }
4568
4569 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4570 audio_flags_to_audio_output_flags(attr->flags, &flags);
4571 flags = (audio_output_flags_t) (flags |
4572 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4573 sp<IOProfile> profile = nullptr;
4574 DeviceVector devices(deviceDescriptor);
4575 for (const auto& hwModule : mHwModules) {
4576 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4577 if (curProfile->hasDynamicAudioProfile()
jiabinde7ae442024-02-06 00:57:36 +00004578 && curProfile->getCompatibilityScore(
4579 devices,
4580 mixerAttributes->config.sample_rate,
4581 nullptr /*updatedSamplingRate*/,
4582 mixerAttributes->config.format,
4583 nullptr /*updatedFormat*/,
4584 mixerAttributes->config.channel_mask,
4585 nullptr /*updatedChannelMask*/,
4586 flags,
4587 false /*exactMatchRequiredForInputFlags*/)
4588 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004589 profile = curProfile;
4590 break;
4591 }
4592 }
4593 }
4594 if (profile == nullptr) {
4595 ALOGE("%s, there is no compatible profile found", __func__);
4596 return BAD_VALUE;
4597 }
4598
4599 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4600 sp<PreferredMixerAttributesInfo>::make(
4601 uid, portId, profile, flags, *mixerAttributes);
4602 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4603 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4604
4605 // If 1) there is any client from the preferred mixer configuration owner that is currently
4606 // active and matches the strategy and 2) current output is on the preferred device and the
4607 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4608 // configuration.
4609 std::vector<audio_io_handle_t> outputsToReopen;
4610 for (size_t i = 0; i < mOutputs.size(); i++) {
4611 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004612 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4613 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4614 output->mUsePreferredMixerAttributes = true;
4615 } else {
4616 for (const auto &client: output->getActiveClients()) {
4617 if (client->uid() == uid && client->strategy() == strategy) {
4618 client->setIsInvalid();
4619 outputsToReopen.push_back(output->mIoHandle);
4620 }
jiabina84c3d32022-12-02 18:59:55 +00004621 }
4622 }
4623 }
4624 }
4625 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4626 config.sample_rate = mixerAttributes->config.sample_rate;
4627 config.channel_mask = mixerAttributes->config.channel_mask;
4628 config.format = mixerAttributes->config.format;
4629 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004630 sp<SwAudioOutputDescriptor> desc =
4631 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4632 if (desc == nullptr) {
4633 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4634 continue;
4635 }
4636 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004637 }
4638
4639 return NO_ERROR;
4640}
4641
4642sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004643 audio_port_handle_t devicePortId,
4644 product_strategy_t strategy,
4645 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004646 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4647 if (it == mPreferredMixerAttrInfos.end()) {
4648 return nullptr;
4649 }
jiabind9a58d32023-06-01 17:57:30 +00004650 if (activeBitPerfectPreferred) {
4651 for (auto [strategy, info] : it->second) {
4652 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4653 && info->getActiveClientCount() != 0) {
4654 return info;
4655 }
4656 }
jiabina84c3d32022-12-02 18:59:55 +00004657 }
jiabind9a58d32023-06-01 17:57:30 +00004658 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4659 return strategyMatchedMixerAttrInfoIt == it->second.end()
4660 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004661}
4662
4663status_t AudioPolicyManager::getPreferredMixerAttributes(
4664 const audio_attributes_t *attr,
4665 audio_port_handle_t portId,
4666 audio_mixer_attributes_t* mixerAttributes) {
4667 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4668 portId, mEngine->getProductStrategyForAttributes(*attr));
4669 if (info == nullptr) {
4670 return NAME_NOT_FOUND;
4671 }
4672 *mixerAttributes = info->getMixerAttributes();
4673 return NO_ERROR;
4674}
4675
4676status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4677 audio_port_handle_t portId,
4678 uid_t uid) {
4679 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4680 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4681 if (preferredMixerAttrInfo == nullptr) {
4682 return NAME_NOT_FOUND;
4683 }
4684 if (preferredMixerAttrInfo->getUid() != uid) {
4685 ALOGE("%s, requested uid=%d, owned uid=%d",
4686 __func__, uid, preferredMixerAttrInfo->getUid());
4687 return PERMISSION_DENIED;
4688 }
4689 mPreferredMixerAttrInfos[portId].erase(strategy);
4690 if (mPreferredMixerAttrInfos[portId].empty()) {
4691 mPreferredMixerAttrInfos.erase(portId);
4692 }
4693
4694 // Reconfig existing output
4695 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4696 for (size_t i = 0; i < mOutputs.size(); i++) {
4697 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4698 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4699 }
4700 }
4701 for (const auto output : potentialOutputsToReopen) {
4702 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4703 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4704 preferredMixerAttrInfo->getFlags())) {
4705 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4706 }
4707 }
4708 return NO_ERROR;
4709}
4710
Eric Laurent6a94d692014-05-20 11:18:06 -07004711status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4712 audio_port_type_t type,
4713 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004714 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004715 unsigned int *generation)
4716{
jiabin19cdba52020-11-24 11:28:58 -08004717 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4718 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004719 return BAD_VALUE;
4720 }
4721 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004722 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004723 *num_ports = 0;
4724 }
4725
4726 size_t portsWritten = 0;
4727 size_t portsMax = *num_ports;
4728 *num_ports = 0;
4729 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004730 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4731 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004733 for (const auto& dev : mAvailableOutputDevices) {
4734 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004735 continue;
4736 }
4737 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004738 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004739 }
4740 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004741 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 }
4743 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004744 for (const auto& dev : mAvailableInputDevices) {
4745 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004746 continue;
4747 }
4748 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004749 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004750 }
4751 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004752 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004753 }
4754 }
4755 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4756 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4757 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4758 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4759 }
4760 *num_ports += mInputs.size();
4761 }
4762 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004763 size_t numOutputs = 0;
4764 for (size_t i = 0; i < mOutputs.size(); i++) {
4765 if (!mOutputs[i]->isDuplicated()) {
4766 numOutputs++;
4767 if (portsWritten < portsMax) {
4768 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4769 }
4770 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004771 }
Eric Laurent84c70242014-06-23 08:46:27 -07004772 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004773 }
4774 }
jiabina84c3d32022-12-02 18:59:55 +00004775
Eric Laurent6a94d692014-05-20 11:18:06 -07004776 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004777 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004778 return NO_ERROR;
4779}
4780
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004781status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4782 std::vector<media::AudioPortFw>* _aidl_return) {
4783 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4784 audio_port_v7 port;
4785 dev->toAudioPort(&port);
4786 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4787 _aidl_return->push_back(std::move(aidlPort));
4788 return OK;
4789 };
4790
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004791 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004792 for (const auto& dev : module->getDeclaredDevices()) {
4793 if (role == media::AudioPortRole::NONE ||
4794 ((role == media::AudioPortRole::SOURCE)
4795 == audio_is_input_device(dev->type()))) {
4796 RETURN_STATUS_IF_ERROR(pushPort(dev));
4797 }
4798 }
4799 }
4800 return OK;
4801}
4802
jiabin19cdba52020-11-24 11:28:58 -08004803status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004804{
Eric Laurent99fcae42018-05-17 16:59:18 -07004805 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4806 return BAD_VALUE;
4807 }
4808 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4809 if (dev != 0) {
4810 dev->toAudioPort(port);
4811 return NO_ERROR;
4812 }
4813 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4814 if (dev != 0) {
4815 dev->toAudioPort(port);
4816 return NO_ERROR;
4817 }
4818 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4819 if (out != 0) {
4820 out->toAudioPort(port);
4821 return NO_ERROR;
4822 }
4823 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4824 if (in != 0) {
4825 in->toAudioPort(port);
4826 return NO_ERROR;
4827 }
4828 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004829}
4830
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004831status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4832 audio_patch_handle_t *handle,
4833 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004834{
François Gaffieafd4cea2019-11-18 15:50:22 +01004835 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004836 if (handle == NULL || patch == NULL) {
4837 return BAD_VALUE;
4838 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004839 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004840 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004841 return BAD_VALUE;
4842 }
4843 // only one source per audio patch supported for now
4844 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004845 return INVALID_OPERATION;
4846 }
Eric Laurent874c42872014-08-08 15:13:39 -07004847 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004848 return INVALID_OPERATION;
4849 }
Eric Laurent874c42872014-08-08 15:13:39 -07004850 for (size_t i = 0; i < patch->num_sinks; i++) {
4851 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4852 return INVALID_OPERATION;
4853 }
4854 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004855
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004856 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4857 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4858 if (srcDevice == nullptr || sinkDevice == nullptr) {
4859 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4860 return BAD_VALUE;
4861 }
4862 ALOGV("%s between source %s and sink %s", __func__,
4863 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4864 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4865 // Default attributes, default volume priority, not to infer with non raw audio patches.
4866 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4867 const struct audio_port_config *source = &patch->sources[0];
4868 sp<SourceClientDescriptor> sourceDesc =
4869 new InternalSourceClientDescriptor(
4870 portId, uid, attributes, *source, srcDevice, sinkDevice,
4871 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4872
4873 status_t status =
4874 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4875
4876 if (status != NO_ERROR) {
4877 return INVALID_OPERATION;
4878 }
4879 mAudioSources.add(portId, sourceDesc);
4880 return NO_ERROR;
4881}
4882
4883status_t AudioPolicyManager::connectAudioSourceToSink(
4884 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4885 const struct audio_patch *patch,
4886 audio_patch_handle_t &handle,
4887 uid_t uid, uint32_t delayMs)
4888{
4889 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4890 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4891 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4892 return INVALID_OPERATION;
4893 }
4894 sourceDesc->connect(handle, sinkDevice);
4895 if (isMsdPatch(handle)) {
4896 return NO_ERROR;
4897 }
4898 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4899 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4900 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4901 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4902 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4903 goto FailurePatchAdded;
4904 }
4905 status = swOutput->start();
4906 if (status != NO_ERROR) {
4907 goto FailureSourceAdded;
4908 }
4909 swOutput->addClient(sourceDesc);
4910 status = startSource(swOutput, sourceDesc, &delayMs);
4911 if (status != NO_ERROR) {
4912 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4913 goto FailureSourceActive;
4914 }
4915 if (delayMs != 0) {
4916 usleep(delayMs * 1000);
4917 }
4918 return NO_ERROR;
4919
4920FailureSourceActive:
4921 swOutput->stop();
4922 releaseOutput(sourceDesc->portId());
4923FailureSourceAdded:
4924 sourceDesc->setSwOutput(nullptr);
4925FailurePatchAdded:
4926 releaseAudioPatchInternal(handle);
4927 return INVALID_OPERATION;
4928}
4929
4930status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4931 audio_patch_handle_t *handle,
4932 uid_t uid, uint32_t delayMs,
4933 const sp<SourceClientDescriptor>& sourceDesc)
4934{
4935 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 sp<AudioPatch> patchDesc;
4937 ssize_t index = mAudioPatches.indexOfKey(*handle);
4938
François Gaffieafd4cea2019-11-18 15:50:22 +01004939 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4940 patch->sources[0].role,
4941 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004942#if LOG_NDEBUG == 0
4943 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004944 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4945 patch->sinks[i].role,
4946 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004947 }
4948#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004949
4950 if (index >= 0) {
4951 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004952 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4953 __func__, mUidCached, patchDesc->getUid(), uid);
4954 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004955 return INVALID_OPERATION;
4956 }
4957 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004958 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004959 }
4960
4961 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004962 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004963 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004964 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004965 return BAD_VALUE;
4966 }
Eric Laurent84c70242014-06-23 08:46:27 -07004967 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4968 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004969 if (patchDesc != 0) {
4970 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004971 ALOGV("%s source id differs for patch current id %d new id %d",
4972 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004973 return BAD_VALUE;
4974 }
4975 }
Eric Laurent874c42872014-08-08 15:13:39 -07004976 DeviceVector devices;
4977 for (size_t i = 0; i < patch->num_sinks; i++) {
4978 // Only support mix to devices connection
4979 // TODO add support for mix to mix connection
4980 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004981 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004982 return INVALID_OPERATION;
4983 }
4984 sp<DeviceDescriptor> devDesc =
4985 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4986 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004987 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004988 return BAD_VALUE;
4989 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004990
jiabinde7ae442024-02-06 00:57:36 +00004991 if (outputDesc->mProfile->getCompatibilityScore(
4992 DeviceVector(devDesc),
4993 patch->sources[0].sample_rate,
4994 nullptr, // updatedSamplingRate
4995 patch->sources[0].format,
4996 nullptr, // updatedFormat
4997 patch->sources[0].channel_mask,
4998 nullptr, // updatedChannelMask
4999 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005000 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005001 return INVALID_OPERATION;
5002 }
5003 devices.add(devDesc);
5004 }
5005 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005006 return INVALID_OPERATION;
5007 }
Eric Laurent874c42872014-08-08 15:13:39 -07005008
Eric Laurent6a94d692014-05-20 11:18:06 -07005009 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005010 ALOGV("%s setting device %s on output %d",
5011 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305012 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005013 index = mAudioPatches.indexOfKey(*handle);
5014 if (index >= 0) {
5015 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005016 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005017 }
5018 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005019 patchDesc->setUid(uid);
5020 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005022 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005023 return INVALID_OPERATION;
5024 }
5025 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5026 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5027 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005028 // only one sink supported when connecting an input device to a mix
5029 if (patch->num_sinks > 1) {
5030 return INVALID_OPERATION;
5031 }
François Gaffie53615e22015-03-19 09:24:12 +01005032 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005033 if (inputDesc == NULL) {
5034 return BAD_VALUE;
5035 }
5036 if (patchDesc != 0) {
5037 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5038 return BAD_VALUE;
5039 }
5040 }
François Gaffie11d30102018-11-02 16:09:09 +01005041 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005042 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005043 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005044 return BAD_VALUE;
5045 }
5046
jiabinde7ae442024-02-06 00:57:36 +00005047 if (inputDesc->mProfile->getCompatibilityScore(
5048 DeviceVector(device),
5049 patch->sinks[0].sample_rate,
5050 nullptr, /*updatedSampleRate*/
5051 patch->sinks[0].format,
5052 nullptr, /*updatedFormat*/
5053 patch->sinks[0].channel_mask,
5054 nullptr, /*updatedChannelMask*/
5055 // FIXME for the parameter type,
5056 // and the NONE
5057 (audio_output_flags_t)
5058 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005059 return INVALID_OPERATION;
5060 }
5061 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005062 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005063 device->toString().c_str(), inputDesc->mIoHandle);
5064 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005065 index = mAudioPatches.indexOfKey(*handle);
5066 if (index >= 0) {
5067 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005068 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005069 }
5070 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005071 patchDesc->setUid(uid);
5072 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005073 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005074 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005075 return INVALID_OPERATION;
5076 }
5077 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5078 // device to device connection
5079 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005080 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005081 return BAD_VALUE;
5082 }
5083 }
François Gaffie11d30102018-11-02 16:09:09 +01005084 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005085 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005086 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005087 return BAD_VALUE;
5088 }
Eric Laurent874c42872014-08-08 15:13:39 -07005089
Eric Laurent6a94d692014-05-20 11:18:06 -07005090 //update source and sink with our own data as the data passed in the patch may
5091 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005092 PatchBuilder patchBuilder;
5093 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005094
5095 // if first sink is to MSD, establish single MSD patch
5096 if (getMsdAudioOutDevices().contains(
5097 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5098 ALOGV("%s patching to MSD", __FUNCTION__);
5099 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5100 goto installPatch;
5101 }
5102
François Gaffieafd4cea2019-11-18 15:50:22 +01005103 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5104 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005105
Eric Laurent874c42872014-08-08 15:13:39 -07005106 for (size_t i = 0; i < patch->num_sinks; i++) {
5107 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005108 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005109 return INVALID_OPERATION;
5110 }
François Gaffie11d30102018-11-02 16:09:09 +01005111 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005112 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005113 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005114 return BAD_VALUE;
5115 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005116 audio_port_config sinkPortConfig = {};
5117 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5118 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005119
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005120 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5121 // volume management purpose (tracking activity)
5122 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5123 // in config XML to reach the sink so that is can be declared as available.
5124 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005125 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005126 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005127 // take care of dynamic routing for SwOutput selection,
5128 audio_attributes_t attributes = sourceDesc->attributes();
5129 audio_stream_type_t stream = sourceDesc->stream();
5130 audio_attributes_t resultAttr;
5131 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5132 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005133 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5134 config.channel_mask =
5135 (audio_channel_mask_get_representation(sourceMask)
5136 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5137 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005138 config.format = sourceDesc->config().format;
5139 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5140 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5141 bool isRequestedDeviceForExclusiveUse = false;
5142 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005143 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005144 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005145 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5146 &stream, sourceDesc->uid(), &config, &flags,
5147 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005148 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005149 if (output == AUDIO_IO_HANDLE_NONE) {
5150 ALOGV("%s no output for device %s",
5151 __FUNCTION__, sinkDevice->toString().c_str());
5152 return INVALID_OPERATION;
5153 }
5154 outputDesc = mOutputs.valueFor(output);
5155 if (outputDesc->isDuplicated()) {
5156 ALOGE("%s output is duplicated", __func__);
5157 return INVALID_OPERATION;
5158 }
François Gaffie7e39df22022-04-26 12:48:49 +02005159 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5160 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005161 } else {
5162 // Same for "raw patches" aka created from createAudioPatch API
5163 SortedVector<audio_io_handle_t> outputs =
5164 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5165 // if the sink device is reachable via an opened output stream, request to
5166 // go via this output stream by adding a second source to the patch
5167 // description
5168 output = selectOutput(outputs);
5169 if (output == AUDIO_IO_HANDLE_NONE) {
5170 ALOGE("%s no output available for internal patch sink", __func__);
5171 return INVALID_OPERATION;
5172 }
5173 outputDesc = mOutputs.valueFor(output);
5174 if (outputDesc->isDuplicated()) {
5175 ALOGV("%s output for device %s is duplicated",
5176 __func__, sinkDevice->toString().c_str());
5177 return INVALID_OPERATION;
5178 }
François Gaffie7e39df22022-04-26 12:48:49 +02005179 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005180 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005181 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005182 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005183 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005184 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005185 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5186 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005187 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5188 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005189 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005190 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005191 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005192 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005193 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005194 return INVALID_OPERATION;
5195 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005196 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005197 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005198 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005199 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005200 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005201 srcMixPortConfig.ext.mix.usecase.stream =
5202 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005203 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5204 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005205 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005206 }
Eric Laurent83b88082014-06-20 18:31:16 -07005207 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005208 }
5209 // TODO: check from routing capabilities in config file and other conflicting patches
5210
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005211installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005212 status_t status = installPatch(
5213 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005214 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005215 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005216 return INVALID_OPERATION;
5217 }
5218 } else {
5219 return BAD_VALUE;
5220 }
5221 } else {
5222 return BAD_VALUE;
5223 }
5224 return NO_ERROR;
5225}
5226
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005227status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005228{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005229 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005230 ssize_t index = mAudioPatches.indexOfKey(handle);
5231
5232 if (index < 0) {
5233 return BAD_VALUE;
5234 }
5235 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005236 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5237 __func__, mUidCached, patchDesc->getUid(), uid);
5238 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005239 return INVALID_OPERATION;
5240 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005241 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5242 for (size_t i = 0; i < mAudioSources.size(); i++) {
5243 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5244 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5245 portId = sourceDesc->portId();
5246 break;
5247 }
5248 }
5249 return portId != AUDIO_PORT_HANDLE_NONE ?
5250 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005251}
Eric Laurent6a94d692014-05-20 11:18:06 -07005252
François Gaffieafd4cea2019-11-18 15:50:22 +01005253status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005254 uint32_t delayMs,
5255 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005256{
5257 ALOGV("%s patch %d", __func__, handle);
5258 if (mAudioPatches.indexOfKey(handle) < 0) {
5259 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5260 return BAD_VALUE;
5261 }
5262 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005264 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005265 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005266 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005267 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005268 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 return BAD_VALUE;
5270 }
5271
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305272 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005273 getNewOutputDevices(outputDesc, true /*fromCache*/),
5274 true,
5275 0,
5276 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005277 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5278 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005279 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005281 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005282 return BAD_VALUE;
5283 }
5284 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005285 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005286 true,
5287 NULL);
5288 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005289 status_t status =
5290 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5291 ALOGV("%s patch panel returned %d patchHandle %d",
5292 __func__, status, patchDesc->getAfHandle());
5293 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005295 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005296 // SW or HW Bridge
5297 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5298 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005299 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005300 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5301 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5302 outputDesc = sourceDesc->swOutput().promote();
5303 }
5304 if (outputDesc == nullptr) {
5305 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5306 // releaseOutput has already called closeOutput in case of direct output
5307 return NO_ERROR;
5308 }
François Gaffie7e39df22022-04-26 12:48:49 +02005309 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005310 // While using a HwBridge, force reconsidering device only if not reusing an existing
5311 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005312 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005313 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5314 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5315 // Reconsider device only for cases:
5316 // 1 / Active Output
5317 // 2 / Inactive Output previously hosting HwBridge
5318 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5319 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5320 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305321 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005322 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5323 outputDesc->devices(),
5324 force,
5325 0,
5326 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005327 } else {
5328 return BAD_VALUE;
5329 }
5330 } else {
5331 return BAD_VALUE;
5332 }
5333 return NO_ERROR;
5334}
5335
5336status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5337 struct audio_patch *patches,
5338 unsigned int *generation)
5339{
François Gaffie53615e22015-03-19 09:24:12 +01005340 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005341 return BAD_VALUE;
5342 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005343 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005344 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005345}
5346
Eric Laurente1715a42014-05-20 11:30:42 -07005347status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005348{
Eric Laurente1715a42014-05-20 11:30:42 -07005349 ALOGV("setAudioPortConfig()");
5350
5351 if (config == NULL) {
5352 return BAD_VALUE;
5353 }
5354 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5355 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005356 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5357 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005358 }
5359
Eric Laurenta121f902014-06-03 13:32:54 -07005360 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005361 if (config->type == AUDIO_PORT_TYPE_MIX) {
5362 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005363 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005364 if (outputDesc == NULL) {
5365 return BAD_VALUE;
5366 }
Eric Laurent84c70242014-06-23 08:46:27 -07005367 ALOG_ASSERT(!outputDesc->isDuplicated(),
5368 "setAudioPortConfig() called on duplicated output %d",
5369 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005370 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005371 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005372 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005373 if (inputDesc == NULL) {
5374 return BAD_VALUE;
5375 }
Eric Laurenta121f902014-06-03 13:32:54 -07005376 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005377 } else {
5378 return BAD_VALUE;
5379 }
5380 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5381 sp<DeviceDescriptor> deviceDesc;
5382 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5383 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5384 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5385 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5386 } else {
5387 return BAD_VALUE;
5388 }
5389 if (deviceDesc == NULL) {
5390 return BAD_VALUE;
5391 }
Eric Laurenta121f902014-06-03 13:32:54 -07005392 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005393 } else {
5394 return BAD_VALUE;
5395 }
5396
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005397 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005398 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5399 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005400 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005401 audioPortConfig->toAudioPortConfig(&newConfig, config);
5402 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005403 }
Eric Laurenta121f902014-06-03 13:32:54 -07005404 if (status != NO_ERROR) {
5405 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005406 }
Eric Laurente1715a42014-05-20 11:30:42 -07005407
5408 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005409}
5410
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005411void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5412{
Eric Laurentd60560a2015-04-10 11:31:20 -07005413 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005414 clearAudioPatches(uid);
5415 clearSessionRoutes(uid);
5416}
5417
Eric Laurent6a94d692014-05-20 11:18:06 -07005418void AudioPolicyManager::clearAudioPatches(uid_t uid)
5419{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005420 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005421 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005422 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005423 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005424 }
5425 }
5426}
5427
François Gaffiec005e562018-11-06 15:04:49 +01005428void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005429{
François Gaffiec005e562018-11-06 15:04:49 +01005430 // Take the first attributes following the product strategy as it is used to retrieve the routed
5431 // device. All attributes wihin a strategy follows the same "routing strategy"
5432 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5433 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005434 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005435 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005436 for (size_t j = 0; j < mOutputs.size(); j++) {
5437 if (mOutputs.keyAt(j) == ouptutToSkip) {
5438 continue;
5439 }
5440 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005441 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005442 continue;
5443 }
5444 // If the default device for this strategy is on another output mix,
5445 // invalidate all tracks in this strategy to force re connection.
5446 // Otherwise select new device on the output mix.
5447 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005448 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005449 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005450 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5451 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5452 // If the device is using preferred mixer attributes, the output need to reopen
5453 // with default configuration when the new selected devices are different from
5454 // current routing devices.
5455 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5456 continue;
5457 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305458 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005459 }
5460 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005461 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005462}
5463
5464void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5465{
5466 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005467 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005468 for (size_t i = 0; i < mOutputs.size(); i++) {
5469 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005470 for (const auto& client : outputDesc->getClientIterable()) {
5471 if (client->hasPreferredDevice() && client->uid() == uid) {
5472 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005473 auto clientStrategy = client->strategy();
5474 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5475 end(affectedStrategies)) {
5476 continue;
5477 }
5478 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005479 }
5480 }
5481 }
5482 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005483 for (const auto& strategy : affectedStrategies) {
5484 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005485 }
5486
5487 // remove input routes associated with this uid
5488 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005489 for (size_t i = 0; i < mInputs.size(); i++) {
5490 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005491 for (const auto& client : inputDesc->getClientIterable()) {
5492 if (client->hasPreferredDevice() && client->uid() == uid) {
5493 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5494 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005495 }
5496 }
5497 }
5498 // reroute inputs if necessary
5499 SortedVector<audio_io_handle_t> inputsToClose;
5500 for (size_t i = 0; i < mInputs.size(); i++) {
5501 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005502 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005503 inputsToClose.add(inputDesc->mIoHandle);
5504 }
5505 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005506 for (const auto& input : inputsToClose) {
5507 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005508 }
5509}
5510
Eric Laurentd60560a2015-04-10 11:31:20 -07005511void AudioPolicyManager::clearAudioSources(uid_t uid)
5512{
5513 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005514 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5515 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005516 stopAudioSource(mAudioSources.keyAt(i));
5517 }
5518 }
5519}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005520
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005521status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5522 audio_io_handle_t *ioHandle,
5523 audio_devices_t *device)
5524{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005525 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5526 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005527 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005528 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5529 if (deviceDesc == nullptr) {
5530 return INVALID_OPERATION;
5531 }
5532 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005533
François Gaffiedf372692015-03-19 10:43:27 +01005534 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005535}
5536
Eric Laurentd60560a2015-04-10 11:31:20 -07005537status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005538 const audio_attributes_t *attributes,
5539 audio_port_handle_t *portId,
5540 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005541{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005542 ALOGV("%s", __FUNCTION__);
5543 *portId = AUDIO_PORT_HANDLE_NONE;
5544
5545 if (source == NULL || attributes == NULL || portId == NULL) {
5546 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5547 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005548 return BAD_VALUE;
5549 }
5550
Eric Laurentd60560a2015-04-10 11:31:20 -07005551 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5552 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005553 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5554 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005555 return INVALID_OPERATION;
5556 }
5557
François Gaffie11d30102018-11-02 16:09:09 +01005558 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005559 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005560 String8(source->ext.device.address),
5561 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005562 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005563 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005564 return BAD_VALUE;
5565 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005566
jiabin4ef93452019-09-10 14:29:54 -07005567 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005568
François Gaffieaaac0fd2018-11-22 17:56:39 +01005569 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005570 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005571 mEngine->getStreamTypeForAttributes(*attributes),
5572 mEngine->getProductStrategyForAttributes(*attributes),
5573 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005574
5575 status_t status = connectAudioSource(sourceDesc);
5576 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005577 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005578 }
5579 return status;
5580}
5581
Francois Gaffie601801d2021-06-22 13:27:39 +02005582sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5583 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5584{
5585 ALOGV("%s", __FUNCTION__);
5586 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5587
5588 status_t status = startAudioSource(source, attributes, &portId, uid);
5589 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5590 return mAudioSources.valueFor(portId);
5591}
5592
5593
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005594status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005595{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005596 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005597
5598 // make sure we only have one patch per source.
5599 disconnectAudioSource(sourceDesc);
5600
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005601 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005602 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5603 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5604 sourceDesc->srcDevice()->type(),
5605 String8(sourceDesc->srcDevice()->address().c_str()),
5606 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005607 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005608 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005609 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005610 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005611 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5612 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5613 return INVALID_OPERATION;
5614 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005615 PatchBuilder patchBuilder;
5616 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5617 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005618
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005619 return connectAudioSourceToSink(
5620 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005621}
5622
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005623status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005624{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005625 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5626 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005627 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005628 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005629 return BAD_VALUE;
5630 }
5631 status_t status = disconnectAudioSource(sourceDesc);
5632
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005633 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005634 return status;
5635}
5636
Andy Hung2ddee192015-12-18 17:34:44 -08005637status_t AudioPolicyManager::setMasterMono(bool mono)
5638{
5639 if (mMasterMono == mono) {
5640 return NO_ERROR;
5641 }
5642 mMasterMono = mono;
5643 // if enabling mono we close all offloaded devices, which will invalidate the
5644 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5645 // for recreating the new AudioTrack as non-offloaded PCM.
5646 //
5647 // If disabling mono, we leave all tracks as is: we don't know which clients
5648 // and tracks are able to be recreated as offloaded. The next "song" should
5649 // play back offloaded.
5650 if (mMasterMono) {
5651 Vector<audio_io_handle_t> offloaded;
5652 for (size_t i = 0; i < mOutputs.size(); ++i) {
5653 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5654 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5655 offloaded.push(desc->mIoHandle);
5656 }
5657 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005658 for (const auto& handle : offloaded) {
5659 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005660 }
5661 }
5662 // update master mono for all remaining outputs
5663 for (size_t i = 0; i < mOutputs.size(); ++i) {
5664 updateMono(mOutputs.keyAt(i));
5665 }
5666 return NO_ERROR;
5667}
5668
5669status_t AudioPolicyManager::getMasterMono(bool *mono)
5670{
5671 *mono = mMasterMono;
5672 return NO_ERROR;
5673}
5674
Eric Laurentac9cef52017-06-09 15:46:26 -07005675float AudioPolicyManager::getStreamVolumeDB(
5676 audio_stream_type_t stream, int index, audio_devices_t device)
5677{
jiabin9a3361e2019-10-01 09:38:30 -07005678 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005679}
5680
jiabin81772902018-04-02 17:52:27 -07005681status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5682 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005683 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005684{
Kriti Dang6537def2021-03-02 13:46:59 +01005685 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5686 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005687 return BAD_VALUE;
5688 }
Kriti Dang6537def2021-03-02 13:46:59 +01005689 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5690 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005691
5692 size_t formatsWritten = 0;
5693 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005694
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005695 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005696 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5697 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005698 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005699 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005700 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005701 bool formatEnabled = true;
5702 switch (forceUse) {
5703 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005704 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005705 break;
5706 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5707 formatEnabled = false;
5708 break;
5709 default: // AUTO or ALWAYS => true
5710 break;
jiabin81772902018-04-02 17:52:27 -07005711 }
5712 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5713 }
jiabin81772902018-04-02 17:52:27 -07005714 }
5715 return NO_ERROR;
5716}
5717
Kriti Dang6537def2021-03-02 13:46:59 +01005718status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5719 audio_format_t *surroundFormats) {
5720 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5721 return BAD_VALUE;
5722 }
5723 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5724 __func__, *numSurroundFormats, surroundFormats);
5725
5726 size_t formatsWritten = 0;
5727 size_t formatsMax = *numSurroundFormats;
5728 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5729
5730 // Return formats from all device profiles that have already been resolved by
5731 // checkOutputsForDevice().
5732 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5733 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5734 audio_devices_t deviceType = device->type();
5735 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5736 // returns formats reported by HDMI devices.
5737 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5738 continue;
5739 }
5740 // Formats reported by sink devices
5741 std::unordered_set<audio_format_t> formatset;
5742 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5743 formatset.insert(it->second.begin(), it->second.end());
5744 }
5745
5746 // Formats hard-coded in the in policy configuration file (if any).
5747 FormatVector encodedFormats = device->encodedFormats();
5748 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5749 // Filter the formats which are supported by the vendor hardware.
5750 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005751 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005752 formats.insert(*it);
5753 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005754 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005755 if (pair.second.count(*it) != 0) {
5756 formats.insert(pair.first);
5757 break;
5758 }
5759 }
5760 }
5761 }
5762 }
5763 *numSurroundFormats = formats.size();
5764 for (const auto& format: formats) {
5765 if (formatsWritten < formatsMax) {
5766 surroundFormats[formatsWritten++] = format;
5767 }
5768 }
5769 return NO_ERROR;
5770}
5771
jiabin81772902018-04-02 17:52:27 -07005772status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5773{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005774 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005775 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5776 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005777 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005778 return BAD_VALUE;
5779 }
5780
Mikhail Naganov100f0122018-11-29 11:22:16 -08005781 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5782 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005783 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005784 return INVALID_OPERATION;
5785 }
5786
Mikhail Naganov100f0122018-11-29 11:22:16 -08005787 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005788 return NO_ERROR;
5789 }
5790
Mikhail Naganov100f0122018-11-29 11:22:16 -08005791 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005792 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005793 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005794 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005795 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005796 }
5797 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005798 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005799 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005800 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005801 }
5802 }
5803
5804 sp<SwAudioOutputDescriptor> outputDesc;
5805 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005806 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5807 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005808 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5809 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005810 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005811 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005812 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5813 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5814 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005815 name.c_str(),
5816 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005817 if (status != NO_ERROR) {
5818 continue;
5819 }
5820 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5821 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5822 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005823 name.c_str(),
5824 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005825 profileUpdated |= (status == NO_ERROR);
5826 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005827 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005828 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005829 AUDIO_DEVICE_IN_HDMI);
5830 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5831 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005832 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005833 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005834 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5835 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5836 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005837 name.c_str(),
5838 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005839 if (status != NO_ERROR) {
5840 continue;
5841 }
5842 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5843 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5844 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005845 name.c_str(),
5846 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005847 profileUpdated |= (status == NO_ERROR);
5848 }
5849
jiabin81772902018-04-02 17:52:27 -07005850 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005851 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005852 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005853 }
5854
5855 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5856}
5857
Eric Laurent5ada82e2019-08-29 17:53:54 -07005858void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005859{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005860 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005861 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005862 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005863 }
5864}
5865
jiabin6012f912018-11-02 17:06:30 -07005866bool AudioPolicyManager::isHapticPlaybackSupported()
5867{
5868 for (const auto& hwModule : mHwModules) {
5869 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5870 for (const auto &outProfile : outputProfiles) {
5871 struct audio_port audioPort;
5872 outProfile->toAudioPort(&audioPort);
5873 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5874 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5875 return true;
5876 }
5877 }
5878 }
5879 }
5880 return false;
5881}
5882
Carter Hsu325a8eb2022-01-19 19:56:51 +08005883bool AudioPolicyManager::isUltrasoundSupported()
5884{
5885 bool hasUltrasoundOutput = false;
5886 bool hasUltrasoundInput = false;
5887 for (const auto& hwModule : mHwModules) {
5888 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5889 if (!hasUltrasoundOutput) {
5890 for (const auto &outProfile : outputProfiles) {
5891 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5892 hasUltrasoundOutput = true;
5893 break;
5894 }
5895 }
5896 }
5897
5898 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5899 if (!hasUltrasoundInput) {
5900 for (const auto &inputProfile : inputProfiles) {
5901 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5902 hasUltrasoundInput = true;
5903 break;
5904 }
5905 }
5906 }
5907
5908 if (hasUltrasoundOutput && hasUltrasoundInput)
5909 return true;
5910 }
5911 return false;
5912}
5913
Atneya Nair698f5ef2022-12-15 16:15:09 -08005914bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5915{
5916 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5917 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5918 for (const auto& hwModule : mHwModules) {
5919 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5920 for (const auto &inputProfile : inputProfiles) {
5921 if ((inputProfile->getFlags() & mask) == mask) {
5922 return true;
5923 }
5924 }
5925 }
5926 return false;
5927}
5928
Eric Laurent8340e672019-11-06 11:01:08 -08005929bool AudioPolicyManager::isCallScreenModeSupported()
5930{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005931 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005932}
5933
5934
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005935status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005936{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005937 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005938 if (!sourceDesc->isConnected()) {
5939 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5940 return NO_ERROR;
5941 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005942 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5943 if (swOutput != 0) {
5944 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005945 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005946 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005947 }
jiabinbce0c1d2020-10-05 11:20:18 -07005948 if (releaseOutput(sourceDesc->portId())) {
5949 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5950 // no need to release audio patch here but just return NO_ERROR.
5951 return NO_ERROR;
5952 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005953 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005954 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005955 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005956 // close Hwoutput and remove from mHwOutputs
5957 } else {
5958 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5959 }
5960 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005961 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005962 sourceDesc->disconnect();
5963 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005964}
5965
François Gaffiec005e562018-11-06 15:04:49 +01005966sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5967 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005968{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005969 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005970 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005971 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005972 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005973 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5974 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005975 source = sourceDesc;
5976 break;
5977 }
5978 }
5979 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005980}
5981
Eric Laurentb4f42a92022-01-17 17:37:31 +01005982bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005983 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005984 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005985{
5986 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5987 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005988 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005989 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005990 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5991 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5992 return false;
5993 }
5994 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5995 return false;
5996 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005997 }
5998
Eric Laurentd332bc82023-08-04 11:45:23 +02005999 // The caller can have the audio config criteria ignored by either passing a null ptr or
6000 // the AUDIO_CONFIG_INITIALIZER value.
6001 // If an audio config is specified, current policy is to only allow spatialization for
6002 // some positional channel masks and PCM format
6003
6004 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
6005 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
6006 return false;
6007 }
6008 if (!audio_is_linear_pcm(config->format)) {
6009 return false;
6010 }
6011 }
6012
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006013 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006014 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006015 if (profile == nullptr) {
6016 return false;
6017 }
6018
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006019 return true;
6020}
6021
6022void AudioPolicyManager::checkVirtualizerClientRoutes() {
6023 std::set<audio_stream_type_t> streamsToInvalidate;
6024 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006025 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6026 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006027 audio_attributes_t attr = client->attributes();
6028 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6029 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6030 audio_config_base_t clientConfig = client->config();
6031 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006032 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006033 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006034 streamsToInvalidate.insert(client->stream());
6035 }
6036 }
6037 }
6038
jiabinc44b3462022-12-08 12:52:31 -08006039 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006040}
6041
Eric Laurente191d1b2022-04-15 11:59:25 +02006042
6043bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6044 const sp<SwAudioOutputDescriptor>& outputDesc) {
6045 if (outputDesc->isDuplicated()) {
6046 return false;
6047 }
6048 DeviceVector devices = outputDesc->supportedDevices();
6049 for (size_t i = 0; i < mOutputs.size(); i++) {
6050 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6051 if (desc == outputDesc || desc->isDuplicated()) {
6052 continue;
6053 }
6054 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6055 if (!sharedDevices.isEmpty()
6056 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6057 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6058 return false;
6059 }
6060 }
6061 return true;
6062}
6063
6064
Eric Laurentfa0f6742021-08-17 18:39:44 +02006065status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006066 const audio_attributes_t *attr,
6067 audio_io_handle_t *output) {
6068 *output = AUDIO_IO_HANDLE_NONE;
6069
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006070 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6071 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6072 audio_config_t *configPtr = nullptr;
6073 audio_config_t config;
6074 if (mixerConfig != nullptr) {
6075 config = audio_config_initializer(mixerConfig);
6076 configPtr = &config;
6077 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006078 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006079 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006080 return BAD_VALUE;
6081 }
6082
6083 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006084 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006085 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006086 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006087 return BAD_VALUE;
6088 }
6089
Eric Laurente191d1b2022-04-15 11:59:25 +02006090 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006091 for (size_t i = 0; i < mOutputs.size(); i++) {
6092 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006093 if (!desc->isDuplicated()
6094 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6095 spatializerOutputs.push_back(desc);
6096 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006097 }
6098 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006099 mSpatializerOutput.clear();
6100 bool outputsChanged = false;
6101 for (const auto& desc : spatializerOutputs) {
6102 if (desc->mProfile == profile
6103 && (configPtr == nullptr
6104 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6105 mSpatializerOutput = desc;
6106 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6107 } else {
6108 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6109 " and devices %s", __func__, desc->mIoHandle,
6110 configPtr != nullptr ? configPtr->channel_mask : 0,
6111 devices.toString().c_str());
6112 closeOutput(desc->mIoHandle);
6113 outputsChanged = true;
6114 }
Eric Laurent39095982021-08-24 18:29:27 +02006115 }
6116
Eric Laurente191d1b2022-04-15 11:59:25 +02006117 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006118 sp<SwAudioOutputDescriptor> desc =
6119 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006120 if (desc != nullptr) {
6121 mSpatializerOutput = desc;
6122 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006123 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006124 }
6125
6126 checkVirtualizerClientRoutes();
6127
Eric Laurente191d1b2022-04-15 11:59:25 +02006128 if (outputsChanged) {
6129 mPreviousOutputs = mOutputs;
6130 mpClientInterface->onAudioPortListUpdate();
6131 }
6132
6133 if (mSpatializerOutput == nullptr) {
6134 ALOGV("%s could not open spatializer output with requested config", __func__);
6135 return BAD_VALUE;
6136 }
Eric Laurent39095982021-08-24 18:29:27 +02006137 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006138 ALOGV("%s returning new spatializer output %d", __func__, *output);
6139 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006140}
6141
Eric Laurentfa0f6742021-08-17 18:39:44 +02006142status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6143 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006144 return INVALID_OPERATION;
6145 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006146 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006147 return BAD_VALUE;
6148 }
Eric Laurent39095982021-08-24 18:29:27 +02006149
Eric Laurente191d1b2022-04-15 11:59:25 +02006150 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6151 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6152 closeOutput(mSpatializerOutput->mIoHandle);
6153 //from now on mSpatializerOutput is null
6154 checkVirtualizerClientRoutes();
6155 }
Eric Laurent39095982021-08-24 18:29:27 +02006156
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006157 return NO_ERROR;
6158}
6159
Eric Laurente552edb2014-03-10 17:42:56 -07006160// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006161// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006162// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006163uint32_t AudioPolicyManager::nextAudioPortGeneration()
6164{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006165 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006166}
6167
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006168AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006169 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006170 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006171 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006172 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006173 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006174 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006175 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006176 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006177 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006178 mAudioPortGeneration(1),
6179 mBeaconMuteRefCount(0),
6180 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006181 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006182 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006183 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006184 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006185{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006186}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006187
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006188status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006189 if (mEngine == nullptr) {
6190 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006191 }
6192 mEngine->setObserver(this);
6193 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006194 if (status != NO_ERROR) {
6195 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6196 return status;
6197 }
François Gaffie2110e042015-03-24 08:41:51 +01006198
jiabin29230182023-04-04 21:02:36 +00006199 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6200 // at the end of this function.
6201 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006202 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6203 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6204
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006205 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006206 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006207 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006208
Eric Laurent3a4311c2014-03-17 12:00:47 -07006209 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006210 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6211 defaultOutputDevice == nullptr ||
6212 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6213 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6214 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006215 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006216 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006217 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006218
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006219 // Silence ALOGV statements
6220 property_set("log.tag." LOG_TAG, "D");
6221
Eric Laurente552edb2014-03-10 17:42:56 -07006222 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006223 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006224}
6225
Eric Laurente0720872014-03-11 09:30:41 -07006226AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006227{
Eric Laurente552edb2014-03-10 17:42:56 -07006228 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006229 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006230 }
6231 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006232 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006233 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006234 mAvailableOutputDevices.clear();
6235 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006236 mOutputs.clear();
6237 mInputs.clear();
6238 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006239 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006240 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006241}
6242
Eric Laurente0720872014-03-11 09:30:41 -07006243status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006244{
Eric Laurent87ffa392015-05-22 10:32:38 -07006245 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006246}
6247
Eric Laurente552edb2014-03-10 17:42:56 -07006248// ---
6249
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006250void AudioPolicyManager::onNewAudioModulesAvailable()
6251{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006252 DeviceVector newDevices;
6253 onNewAudioModulesAvailableInt(&newDevices);
6254 if (!newDevices.empty()) {
6255 nextAudioPortGeneration();
6256 mpClientInterface->onAudioPortListUpdate();
6257 }
6258}
6259
6260void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6261{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006262 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006263 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6264 continue;
6265 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006266 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006267 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6268 handle != AUDIO_MODULE_HANDLE_NONE) {
6269 hwModule->setHandle(handle);
6270 } else {
6271 ALOGW("could not load HW module %s", hwModule->getName());
6272 continue;
6273 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006274 }
6275 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006276 // open all output streams needed to access attached devices.
6277 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006278 // This also validates mAvailableOutputDevices list
6279 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6280 if (!outProfile->canOpenNewIo()) {
6281 ALOGE("Invalid Output profile max open count %u for profile %s",
6282 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6283 continue;
6284 }
6285 if (!outProfile->hasSupportedDevices()) {
6286 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6287 continue;
6288 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006289 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6290 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006291 mTtsOutputAvailable = true;
6292 }
6293
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006294 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006295 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006296 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006297 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6298 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006299 } else {
6300 // choose first device present in profile's SupportedDevices also part of
6301 // mAvailableOutputDevices.
6302 if (availProfileDevices.isEmpty()) {
6303 continue;
6304 }
6305 supportedDevice = availProfileDevices.itemAt(0);
6306 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006307 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006308 continue;
6309 }
6310 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6311 mpClientInterface);
6312 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006313 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6314 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006315 AUDIO_STREAM_DEFAULT,
6316 AUDIO_OUTPUT_FLAG_NONE, &output);
6317 if (status != NO_ERROR) {
6318 ALOGW("Cannot open output stream for devices %s on hw module %s",
6319 supportedDevice->toString().c_str(), hwModule->getName());
6320 continue;
6321 }
6322 for (const auto &device : availProfileDevices) {
6323 // give a valid ID to an attached device once confirmed it is reachable
6324 if (!device->isAttached()) {
6325 device->attach(hwModule);
6326 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006327 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006328 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006329 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6330 }
6331 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006332 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006333 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6334 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006335 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006336 }
Eric Laurent39095982021-08-24 18:29:27 +02006337 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006338 outputDesc->close();
6339 } else {
6340 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306341 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006342 DeviceVector(supportedDevice),
6343 true,
6344 0,
6345 NULL);
6346 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006347 }
6348 // open input streams needed to access attached devices to validate
6349 // mAvailableInputDevices list
6350 for (const auto& inProfile : hwModule->getInputProfiles()) {
6351 if (!inProfile->canOpenNewIo()) {
6352 ALOGE("Invalid Input profile max open count %u for profile %s",
6353 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6354 continue;
6355 }
6356 if (!inProfile->hasSupportedDevices()) {
6357 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6358 continue;
6359 }
6360 // chose first device present in profile's SupportedDevices also part of
6361 // available input devices
6362 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006363 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006364 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006365 ALOGV("%s: Input device list is empty! for profile %s",
6366 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006367 continue;
6368 }
6369 sp<AudioInputDescriptor> inputDesc =
6370 new AudioInputDescriptor(inProfile, mpClientInterface);
6371
6372 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6373 status_t status = inputDesc->open(nullptr,
6374 availProfileDevices.itemAt(0),
6375 AUDIO_SOURCE_MIC,
6376 AUDIO_INPUT_FLAG_NONE,
6377 &input);
6378 if (status != NO_ERROR) {
6379 ALOGW("Cannot open input stream for device %s on hw module %s",
6380 availProfileDevices.toString().c_str(),
6381 hwModule->getName());
6382 continue;
6383 }
6384 for (const auto &device : availProfileDevices) {
6385 // give a valid ID to an attached device once confirmed it is reachable
6386 if (!device->isAttached()) {
6387 device->attach(hwModule);
6388 device->importAudioPortAndPickAudioProfile(inProfile, true);
6389 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006390 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006391 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6392 }
6393 }
6394 inputDesc->close();
6395 }
6396 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006397
6398 // Check if spatializer outputs can be closed until used.
6399 // mOutputs vector never contains duplicated outputs at this point.
6400 std::vector<audio_io_handle_t> outputsClosed;
6401 for (size_t i = 0; i < mOutputs.size(); i++) {
6402 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6403 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6404 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6405 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006406 nextAudioPortGeneration();
6407 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6408 if (index >= 0) {
6409 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6410 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6411 patchDesc->getAfHandle(), 0);
6412 mAudioPatches.removeItemsAt(index);
6413 mpClientInterface->onAudioPatchListUpdate();
6414 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006415 desc->close();
6416 }
6417 }
6418 for (auto output : outputsClosed) {
6419 removeOutput(output);
6420 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006421}
6422
Eric Laurent98e38192018-02-15 18:31:53 -08006423void AudioPolicyManager::addOutput(audio_io_handle_t output,
6424 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006425{
Eric Laurent1c333e22014-05-20 10:48:17 -07006426 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006427 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006428 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006429 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006430 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006431}
6432
François Gaffie53615e22015-03-19 09:24:12 +01006433void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6434{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006435 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6436 ALOGV("%s: removing primary output", __func__);
6437 mPrimaryOutput = nullptr;
6438 }
François Gaffie53615e22015-03-19 09:24:12 +01006439 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006440 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006441}
6442
Eric Laurent98e38192018-02-15 18:31:53 -08006443void AudioPolicyManager::addInput(audio_io_handle_t input,
6444 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006445{
Eric Laurent1c333e22014-05-20 10:48:17 -07006446 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006447 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006448}
Eric Laurente552edb2014-03-10 17:42:56 -07006449
François Gaffie11d30102018-11-02 16:09:09 +01006450status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006451 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006452 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006453{
François Gaffie11d30102018-11-02 16:09:09 +01006454 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006455 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006456 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006457
François Gaffie11d30102018-11-02 16:09:09 +01006458 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006459 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006460 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006461 }
Eric Laurente552edb2014-03-10 17:42:56 -07006462
Eric Laurent3b73df72014-03-11 09:06:29 -07006463 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006464 // first call getAudioPort to get the supported attributes from the HAL
6465 struct audio_port_v7 port = {};
6466 device->toAudioPort(&port);
6467 status_t status = mpClientInterface->getAudioPort(&port);
6468 if (status == NO_ERROR) {
6469 device->importAudioPort(port);
6470 }
6471
6472 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006473 for (size_t i = 0; i < mOutputs.size(); i++) {
6474 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006475 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006476 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006477 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6478 mOutputs.keyAt(i), device->toString().c_str());
6479 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006480 }
6481 }
6482 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006483 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006484 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006485 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6486 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006487 if (profile->supportsDevice(device)) {
6488 profiles.add(profile);
6489 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6490 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006491 }
6492 }
6493 }
6494
Eric Laurent7b279bb2015-12-14 10:18:23 -08006495 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006496
Eric Laurente552edb2014-03-10 17:42:56 -07006497 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006498 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006499 return BAD_VALUE;
6500 }
6501
6502 // open outputs for matching profiles if needed. Direct outputs are also opened to
6503 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6504 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006505 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006506
6507 // nothing to do if one output is already opened for this profile
6508 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006509 for (j = 0; j < outputs.size(); j++) {
6510 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006511 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006512 // matching profile: save the sample rates, format and channel masks supported
6513 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006514 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006515 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006516 }
Eric Laurente552edb2014-03-10 17:42:56 -07006517 break;
6518 }
6519 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006520 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006521 continue;
6522 }
6523
Eric Laurent3974e3b2017-12-07 17:58:43 -08006524 if (!profile->canOpenNewIo()) {
6525 ALOGW("Max Output number %u already opened for this profile %s",
6526 profile->maxOpenCount, profile->getTagName().c_str());
6527 continue;
6528 }
6529
Eric Laurent83efe1c2017-07-09 16:51:08 -07006530 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006531 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006532 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6533 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006534 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006535 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006536 profiles.removeAt(profile_index);
6537 profile_index--;
6538 } else {
6539 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006540 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006541 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006542 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6543 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006544 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006545 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006546
François Gaffie11d30102018-11-02 16:09:09 +01006547 if (device_distinguishes_on_address(deviceType)) {
6548 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6549 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306550 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6551 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006552 }
Eric Laurente552edb2014-03-10 17:42:56 -07006553 ALOGV("checkOutputsForDevice(): adding output %d", output);
6554 }
6555 }
6556
6557 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006558 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006559 return BAD_VALUE;
6560 }
Eric Laurentd4692962014-05-05 18:13:44 -07006561 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006562 // check if one opened output is not needed any more after disconnecting one device
6563 for (size_t i = 0; i < mOutputs.size(); i++) {
6564 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006565 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006566 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006567 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006568 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006569 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006570 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006571 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6572 mOutputs.keyAt(i));
6573 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006574 }
Eric Laurente552edb2014-03-10 17:42:56 -07006575 }
6576 }
Eric Laurentd4692962014-05-05 18:13:44 -07006577 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006578 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006579 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6580 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006581 if (!profile->supportsDevice(device)) {
6582 continue;
6583 }
6584 ALOGV("checkOutputsForDevice(): "
6585 "clearing direct output profile %zu on module %s",
6586 j, hwModule->getName());
6587 profile->clearAudioProfiles();
6588 if (!profile->hasDynamicAudioProfile()) {
6589 continue;
6590 }
6591 // When a device is disconnected, if there is an IOProfile that contains dynamic
6592 // profiles and supports the disconnected device, call getAudioPort to repopulate
6593 // the capabilities of the devices that is supported by the IOProfile.
6594 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6595 if (supportedDevice == device ||
6596 !mAvailableOutputDevices.contains(supportedDevice)) {
6597 continue;
6598 }
6599 struct audio_port_v7 port;
6600 supportedDevice->toAudioPort(&port);
6601 status_t status = mpClientInterface->getAudioPort(&port);
6602 if (status == NO_ERROR) {
6603 supportedDevice->importAudioPort(port);
6604 }
Eric Laurente552edb2014-03-10 17:42:56 -07006605 }
6606 }
6607 }
6608 }
6609 return NO_ERROR;
6610}
6611
François Gaffie11d30102018-11-02 16:09:09 +01006612status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006613 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006614{
François Gaffie11d30102018-11-02 16:09:09 +01006615 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006616 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006617 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006618 }
6619
Eric Laurentd4692962014-05-05 18:13:44 -07006620 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006621 sp<AudioInputDescriptor> desc;
6622
jiabinbf5f4262023-04-12 21:48:34 +00006623 // first call getAudioPort to get the supported attributes from the HAL
6624 struct audio_port_v7 port = {};
6625 device->toAudioPort(&port);
6626 status_t status = mpClientInterface->getAudioPort(&port);
6627 if (status == NO_ERROR) {
6628 device->importAudioPort(port);
6629 }
6630
Eric Laurent0dd51852019-04-19 18:18:58 -07006631 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006632 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006633 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006634 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006635 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006636 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006637 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006638
François Gaffie11d30102018-11-02 16:09:09 +01006639 if (profile->supportsDevice(device)) {
6640 profiles.add(profile);
6641 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6642 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006643 }
6644 }
6645 }
6646
Eric Laurent0dd51852019-04-19 18:18:58 -07006647 if (profiles.isEmpty()) {
6648 ALOGW("%s: No input profile available for device %s",
6649 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006650 return BAD_VALUE;
6651 }
6652
6653 // open inputs for matching profiles if needed. Direct inputs are also opened to
6654 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6655 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6656
Eric Laurent1c333e22014-05-20 10:48:17 -07006657 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006658
Eric Laurentd4692962014-05-05 18:13:44 -07006659 // nothing to do if one input is already opened for this profile
6660 size_t input_index;
6661 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6662 desc = mInputs.valueAt(input_index);
6663 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006664 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006665 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006666 }
Eric Laurentd4692962014-05-05 18:13:44 -07006667 break;
6668 }
6669 }
6670 if (input_index != mInputs.size()) {
6671 continue;
6672 }
6673
Eric Laurent3974e3b2017-12-07 17:58:43 -08006674 if (!profile->canOpenNewIo()) {
6675 ALOGW("Max Input number %u already opened for this profile %s",
6676 profile->maxOpenCount, profile->getTagName().c_str());
6677 continue;
6678 }
6679
Eric Laurentfe231122017-11-17 17:48:06 -08006680 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006681 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006682 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006683
Eric Laurentcf2c0212014-07-25 16:20:43 -07006684 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006685 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006686 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006687 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006688 mpClientInterface->setParameters(input, String8(param));
6689 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006690 }
jiabin12537fc2023-10-12 17:56:08 +00006691 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006692 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006693 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006694 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006695 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006696 }
6697
Eric Laurent0dd51852019-04-19 18:18:58 -07006698 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006699 addInput(input, desc);
6700 }
6701 } // endif input != 0
6702
Eric Laurentcf2c0212014-07-25 16:20:43 -07006703 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006704 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006705 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006706 profiles.removeAt(profile_index);
6707 profile_index--;
6708 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006709 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006710 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006711 }
Eric Laurentd4692962014-05-05 18:13:44 -07006712 ALOGV("checkInputsForDevice(): adding input %d", input);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006713
6714 if (checkCloseInput(desc)) {
6715 ALOGV("%s closing input %d", __func__, input);
6716 closeInput(input);
6717 }
Eric Laurentd4692962014-05-05 18:13:44 -07006718 }
6719 } // end scan profiles
6720
6721 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006722 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006723 return BAD_VALUE;
6724 }
6725 } else {
6726 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006727 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006728 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006729 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006730 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006731 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006732 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006733 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006734 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6735 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006736 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006737 }
6738 }
6739 }
6740 } // end disconnect
6741
6742 return NO_ERROR;
6743}
6744
6745
Eric Laurente0720872014-03-11 09:30:41 -07006746void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006747{
6748 ALOGV("closeOutput(%d)", output);
6749
François Gaffie1c878552018-11-22 16:53:21 +01006750 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6751 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006752 ALOGW("closeOutput() unknown output %d", output);
6753 return;
6754 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006755 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006756 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006757
Eric Laurente552edb2014-03-10 17:42:56 -07006758 // look for duplicated outputs connected to the output being removed.
6759 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006760 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6761 if (dupOutput->isDuplicated() &&
6762 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6763 sp<SwAudioOutputDescriptor> remainingOutput =
6764 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006765 // As all active tracks on duplicated output will be deleted,
6766 // and as they were also referenced on the other output, the reference
6767 // count for their stream type must be adjusted accordingly on
6768 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006769 const bool wasActive = remainingOutput->isActive();
6770 // Note: no-op on the closing output where all clients has already been set inactive
6771 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006772 // stop() will be a no op if the output is still active but is needed in case all
6773 // active streams refcounts where cleared above
6774 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006775 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006776 }
Eric Laurente552edb2014-03-10 17:42:56 -07006777 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6778 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6779
6780 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006781 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006782 }
6783 }
6784
Eric Laurent05b90f82014-08-27 15:32:29 -07006785 nextAudioPortGeneration();
6786
François Gaffie1c878552018-11-22 16:53:21 +01006787 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006788 if (index >= 0) {
6789 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006790 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6791 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006792 mAudioPatches.removeItemsAt(index);
6793 mpClientInterface->onAudioPatchListUpdate();
6794 }
6795
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006796 if (closingOutputWasActive) {
6797 closingOutput->stop();
6798 }
François Gaffie1c878552018-11-22 16:53:21 +01006799 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006800
François Gaffie53615e22015-03-19 09:24:12 +01006801 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006802 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006803 if (closingOutput == mSpatializerOutput) {
6804 mSpatializerOutput.clear();
6805 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006806
6807 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6808 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006809 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006810 bool directOutputOpen = false;
6811 for (size_t i = 0; i < mOutputs.size(); i++) {
6812 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6813 directOutputOpen = true;
6814 break;
6815 }
6816 }
6817 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006818 ALOGV("no direct outputs open, reset MSD patches");
6819 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6820 // how output devices for patching are resolved. Avoid by caching and reusing the
6821 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6822 // devices to patch to. This may be complicated by the fact that devices may become
6823 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006824 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006825 }
6826 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006827}
6828
6829void AudioPolicyManager::closeInput(audio_io_handle_t input)
6830{
6831 ALOGV("closeInput(%d)", input);
6832
6833 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6834 if (inputDesc == NULL) {
6835 ALOGW("closeInput() unknown input %d", input);
6836 return;
6837 }
6838
Eric Laurent6a94d692014-05-20 11:18:06 -07006839 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006840
François Gaffie11d30102018-11-02 16:09:09 +01006841 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006842 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006843 if (index >= 0) {
6844 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006845 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6846 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006847 mAudioPatches.removeItemsAt(index);
6848 mpClientInterface->onAudioPatchListUpdate();
6849 }
6850
François Gaffie6ebbce02023-07-19 13:27:53 +02006851 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006852 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006853 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006854
François Gaffie11d30102018-11-02 16:09:09 +01006855 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6856 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006857 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006858 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006859 }
Eric Laurente552edb2014-03-10 17:42:56 -07006860}
6861
François Gaffie11d30102018-11-02 16:09:09 +01006862SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6863 const DeviceVector &devices,
6864 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006865{
6866 SortedVector<audio_io_handle_t> outputs;
6867
François Gaffie11d30102018-11-02 16:09:09 +01006868 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006869 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006870 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006871 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006872 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006873 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006874 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006875 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006876 outputs.add(openOutputs.keyAt(i));
6877 }
6878 }
6879 return outputs;
6880}
6881
Mikhail Naganov37977152018-07-11 15:54:44 -07006882void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6883{
6884 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6885 // output is suspended before any tracks are moved to it
6886 checkA2dpSuspend();
6887 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006888 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006889 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006890 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006891 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006892 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6893 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6894 // configuration changes will ultimately be rerouted correctly. We can still avoid
6895 // unnecessary rerouting by caching and reusing the arguments to
6896 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6897 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006898 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006899 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006900 // an event that changed routing likely occurred, inform upper layers
6901 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006902}
6903
François Gaffiec005e562018-11-06 15:04:49 +01006904bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6905 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006906{
François Gaffiec005e562018-11-06 15:04:49 +01006907 return mEngine->getProductStrategyForAttributes(lAttr) ==
6908 mEngine->getProductStrategyForAttributes(rAttr);
6909}
6910
Francois Gaffieff1eb522020-05-06 18:37:04 +02006911void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6912{
6913 for (size_t i = 0; i < mAudioSources.size(); i++) {
6914 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6915 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006916 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006917 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006918 connectAudioSource(sourceDesc);
6919 }
6920 }
6921}
6922
6923void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6924{
6925 for (size_t i = 0; i < mAudioSources.size(); i++) {
6926 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6927 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6928 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6929 disconnectAudioSource(sourceDesc);
6930 }
6931 }
6932}
6933
François Gaffiec005e562018-11-06 15:04:49 +01006934void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6935{
6936 auto psId = mEngine->getProductStrategyForAttributes(attr);
6937
6938 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6939 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006940
François Gaffie11d30102018-11-02 16:09:09 +01006941 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6942 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006943
Eric Laurentc209fe42020-06-05 18:11:23 -07006944 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006945 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006946 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006947 // take into account dynamic audio policies related changes: if a client is now associated
6948 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006949 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006950 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6951 if (desc->isDuplicated()) {
6952 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006953 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006954 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6955 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6956 continue;
6957 }
6958 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006959 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006960 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6961 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6962 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006963 if (status != OK) {
6964 continue;
6965 }
yucliuf4de36d2020-09-14 14:57:56 -07006966 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006967 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006968 maxLatency = desc->latency();
6969 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006970 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006971 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006972 }
6973 }
6974
Eric Laurent56ed8842022-11-15 16:04:41 +01006975 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006976 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6977 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006978 for (audio_io_handle_t srcOut : srcOutputs) {
6979 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006980 if (desc == nullptr) continue;
6981
6982 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006983 maxLatency = desc->latency();
6984 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006985
Eric Laurent56ed8842022-11-15 16:04:41 +01006986 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006987 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006988 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006989 // a client on a non direct outputs has necessarily a linear PCM format
6990 // so we can call selectOutput() safely
6991 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6992 client->flags(),
6993 client->config().format,
6994 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006995 client->config().sample_rate,
6996 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006997 if (newOutput != srcOut) {
6998 invalidate = true;
6999 break;
7000 }
7001 } else {
7002 sp<IOProfile> profile = getProfileForOutput(newDevices,
7003 client->config().sample_rate,
7004 client->config().format,
7005 client->config().channel_mask,
7006 client->flags(),
7007 true /* directOnly */);
7008 if (profile != desc->mProfile) {
7009 invalidate = true;
7010 break;
7011 }
7012 }
7013 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007014 // mute strategy while moving tracks from one output to another
7015 if (invalidate) {
7016 invalidatedOutputs.push_back(desc);
7017 if (desc->isStrategyActive(psId)) {
7018 setStrategyMute(psId, true, desc);
7019 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7020 newDevices.types());
7021 }
Eric Laurente552edb2014-03-10 17:42:56 -07007022 }
François Gaffiec005e562018-11-06 15:04:49 +01007023 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007024 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007025 connectAudioSource(source);
7026 }
Eric Laurente552edb2014-03-10 17:42:56 -07007027 }
7028
Eric Laurent56ed8842022-11-15 16:04:41 +01007029 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7030 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7031 std::to_string(srcOutputs[0]).c_str(),
7032 std::to_string(dstOutputs[0]).c_str());
7033
François Gaffiec005e562018-11-06 15:04:49 +01007034 // Move effects associated to this stream from previous output to new output
7035 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007036 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007037 }
François Gaffiec005e562018-11-06 15:04:49 +01007038 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007039 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007040 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007041 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007042 desc->setTracksInvalidatedStatusByStrategy(psId);
7043 }
Eric Laurente552edb2014-03-10 17:42:56 -07007044 }
7045 }
7046}
7047
Eric Laurente0720872014-03-11 09:30:41 -07007048void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007049{
François Gaffiec005e562018-11-06 15:04:49 +01007050 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7051 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7052 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007053 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007054 }
Eric Laurente552edb2014-03-10 17:42:56 -07007055}
7056
Kevin Rocard153f92d2018-12-18 18:33:28 -08007057void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007058 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007059 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007060 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007061 for (size_t i = 0; i < mOutputs.size(); i++) {
7062 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7063 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007064 sp<AudioPolicyMix> primaryMix;
7065 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007066 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007067 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7068 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7069 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007070 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7071 for (auto &secondaryMix : secondaryMixes) {
7072 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7073 if (outputDesc != nullptr &&
7074 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7075 secondaryDescs.push_back(outputDesc);
7076 }
7077 }
7078
jiabinc44b3462022-12-08 12:52:31 -08007079 if (status != OK &&
7080 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7081 // When it failed to query secondary output, only invalidate the client that is not
7082 // MMAP. The reason is that MMAP stream will not support secondary output.
7083 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007084 } else if (!std::equal(
7085 client->getSecondaryOutputs().begin(),
7086 client->getSecondaryOutputs().end(),
7087 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007088 if (!audio_is_linear_pcm(client->config().format)) {
7089 // If the format is not PCM, the tracks should be invalidated to get correct
7090 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007091 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007092 } else {
7093 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7094 std::vector<audio_io_handle_t> secondaryOutputIds;
7095 for (const auto &secondaryDesc: secondaryDescs) {
7096 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7097 weakSecondaryDescs.push_back(secondaryDesc);
7098 }
7099 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7100 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007101 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007102 }
7103 }
7104 }
jiabin10a03f12021-05-07 23:46:28 +00007105 if (!trackSecondaryOutputs.empty()) {
7106 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7107 }
jiabinc44b3462022-12-08 12:52:31 -08007108 if (!clientsToInvalidate.empty()) {
7109 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7110 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007111 }
7112}
7113
Eric Laurent2517af32020-11-25 15:31:27 +01007114bool AudioPolicyManager::isScoRequestedForComm() const {
7115 AudioDeviceTypeAddrVector devices;
7116 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7117 for (const auto &device : devices) {
7118 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7119 return true;
7120 }
7121 }
7122 return false;
7123}
7124
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007125bool AudioPolicyManager::isHearingAidUsedForComm() const {
7126 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7127 true /*fromCache*/);
7128 for (const auto &device : devices) {
7129 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7130 return true;
7131 }
7132 }
7133 return false;
7134}
7135
7136
Eric Laurente0720872014-03-11 09:30:41 -07007137void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007138{
François Gaffie53615e22015-03-19 09:24:12 +01007139 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007140 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007141 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007142 return;
7143 }
7144
Eric Laurent3a4311c2014-03-17 12:00:47 -07007145 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007146 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7147 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007148 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007149
7150 // if suspended, restore A2DP output if:
7151 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007152 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007153 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007154 //
Eric Laurentf732e072016-08-03 19:30:28 -07007155 // if not suspended, suspend A2DP output if:
7156 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007157 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007158 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007159 //
7160 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007161 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007162 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007163 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007164 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007165
7166 mpClientInterface->restoreOutput(a2dpOutput);
7167 mA2dpSuspended = false;
7168 }
7169 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007170 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007171 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007172 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007173 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007174
7175 mpClientInterface->suspendOutput(a2dpOutput);
7176 mA2dpSuspended = true;
7177 }
7178 }
7179}
7180
François Gaffie11d30102018-11-02 16:09:09 +01007181DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7182 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007183{
François Gaffiedb1755b2023-09-01 11:50:35 +02007184 if (outputDesc == nullptr) {
7185 return DeviceVector{};
7186 }
François Gaffie11d30102018-11-02 16:09:09 +01007187
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007188 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007189 if (index >= 0) {
7190 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007191 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007192 ALOGV("%s device %s forced by patch %d", __func__,
7193 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7194 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007195 }
7196 }
7197
Dean Wheatley514b4312020-06-17 21:45:00 +10007198 // Do not retrieve engine device for outputs through MSD
7199 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7200 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7201 return outputDesc->devices();
7202 }
7203
Eric Laurent97ac8712018-07-27 18:59:02 -07007204 // Honor explicit routing requests only if no client using default routing is active on this
7205 // input: a specific app can not force routing for other apps by setting a preferred device.
7206 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007207 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007208 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007209 if (device != nullptr) {
7210 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007211 }
7212
François Gaffiea807ef92018-11-05 10:44:33 +01007213 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7214 // of setForceUse / Default Bus device here
7215 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7216 if (device != nullptr) {
7217 return DeviceVector(device);
7218 }
7219
François Gaffiedb1755b2023-09-01 11:50:35 +02007220 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007221 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7222 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307223 auto hasStreamActive = [&](auto stream) {
7224 return hasStream(streams, stream) && isStreamActive(stream, 0);
7225 };
Eric Laurent484e9272018-06-07 17:29:23 -07007226
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307227 auto doGetOutputDevicesForVoice = [&]() {
7228 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007229 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307230 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007231 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7232 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307233 };
7234
7235 // With low-latency playing on speaker, music on WFD, when the first low-latency
7236 // output is stopped, getNewOutputDevices checks for a product strategy
7237 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007238 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307239 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7240 // stream is associated to the output descriptor.
7241 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7242 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7243 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7244 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007245 // Retrieval of devices for voice DL is done on primary output profile, cannot
7246 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007247 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007248 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7249 break;
7250 }
Eric Laurente552edb2014-03-10 17:42:56 -07007251 }
François Gaffiec005e562018-11-06 15:04:49 +01007252 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007253 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007254}
7255
François Gaffie11d30102018-11-02 16:09:09 +01007256sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7257 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007258{
François Gaffie11d30102018-11-02 16:09:09 +01007259 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007260
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007261 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007262 if (index >= 0) {
7263 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007264 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007265 ALOGV("getNewInputDevice() device %s forced by patch %d",
7266 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7267 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007268 }
7269 }
7270
Eric Laurent97ac8712018-07-27 18:59:02 -07007271 // Honor explicit routing requests only if no client using default routing is active on this
7272 // input: a specific app can not force routing for other apps by setting a preferred device.
7273 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007274 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7275 if (device != nullptr) {
7276 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007277 }
7278
Eric Laurentdc95a252018-04-12 12:46:56 -07007279 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007280 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007281 audio_attributes_t attributes;
7282 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007283 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007284 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7285 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007286 attributes = topClient->attributes();
7287 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007288 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007289 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007290 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7291 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007292 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007293 }
7294
Francois Gaffie716e1432019-01-14 16:58:59 +01007295 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7296 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007297 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007298 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007299 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007300 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007301
Eric Laurente552edb2014-03-10 17:42:56 -07007302 return device;
7303}
7304
Eric Laurent794fde22016-03-11 09:50:45 -08007305bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7306 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007307 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007308}
7309
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007310status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007311 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007312 if (devices == nullptr) {
7313 return BAD_VALUE;
7314 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007315
Andy Hung6d23c0f2022-02-16 09:37:15 -08007316 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007317 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7318 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007319 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007320 for (const auto& device : curDevices) {
7321 devices->push_back(device->getDeviceTypeAddr());
7322 }
7323 return NO_ERROR;
7324}
7325
Eric Laurente0720872014-03-11 09:30:41 -07007326void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007327 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007328 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007329 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007330 updateDevicesAndOutputs();
7331 break;
7332 default:
7333 break;
7334 }
7335}
7336
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007337uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007338
7339 // skip beacon mute management if a dedicated TTS output is available
7340 if (mTtsOutputAvailable) {
7341 return 0;
7342 }
7343
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007344 switch(event) {
7345 case STARTING_OUTPUT:
7346 mBeaconMuteRefCount++;
7347 break;
7348 case STOPPING_OUTPUT:
7349 if (mBeaconMuteRefCount > 0) {
7350 mBeaconMuteRefCount--;
7351 }
7352 break;
7353 case STARTING_BEACON:
7354 mBeaconPlayingRefCount++;
7355 break;
7356 case STOPPING_BEACON:
7357 if (mBeaconPlayingRefCount > 0) {
7358 mBeaconPlayingRefCount--;
7359 }
7360 break;
7361 }
7362
7363 if (mBeaconMuteRefCount > 0) {
7364 // any playback causes beacon to be muted
7365 return setBeaconMute(true);
7366 } else {
7367 // no other playback: unmute when beacon starts playing, mute when it stops
7368 return setBeaconMute(mBeaconPlayingRefCount == 0);
7369 }
7370}
7371
7372uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7373 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7374 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7375 // keep track of muted state to avoid repeating mute/unmute operations
7376 if (mBeaconMuted != mute) {
7377 // mute/unmute AUDIO_STREAM_TTS on all outputs
7378 ALOGV("\t muting %d", mute);
7379 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007380 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7381 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7382 ALOGV("\t no tts volume source available");
7383 return 0;
7384 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007385 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007386 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007387 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007388 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007389 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007390 maxLatency = latency;
7391 }
7392 }
7393 mBeaconMuted = mute;
7394 return maxLatency;
7395 }
7396 return 0;
7397}
7398
Eric Laurente0720872014-03-11 09:30:41 -07007399void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007400{
François Gaffiec005e562018-11-06 15:04:49 +01007401 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007402 mPreviousOutputs = mOutputs;
7403}
7404
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007405uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007406 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007407 uint32_t delayMs)
7408{
7409 // mute/unmute strategies using an incompatible device combination
7410 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7411 // if unmuting, unmute only after the specified delay
7412 if (outputDesc->isDuplicated()) {
7413 return 0;
7414 }
7415
7416 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007417 DeviceVector devices = outputDesc->devices();
7418 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007419
François Gaffiec005e562018-11-06 15:04:49 +01007420 auto productStrategies = mEngine->getOrderedProductStrategies();
7421 for (const auto &productStrategy : productStrategies) {
7422 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7423 DeviceVector curDevices =
7424 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7425 curDevices = curDevices.filter(outputDesc->supportedDevices());
7426 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007427 bool doMute = false;
7428
François Gaffiec005e562018-11-06 15:04:49 +01007429 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007430 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007431 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7432 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007433 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007434 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007435 }
Eric Laurent99401132014-05-07 19:48:15 -07007436 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007437 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007438 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007439 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007440 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007441 continue;
7442 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307443 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007444 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7445 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7446 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007447 if (mute) {
7448 // FIXME: should not need to double latency if volume could be applied
7449 // immediately by the audioflinger mixer. We must account for the delay
7450 // between now and the next time the audioflinger thread for this output
7451 // will process a buffer (which corresponds to one buffer size,
7452 // usually 1/2 or 1/4 of the latency).
7453 if (muteWaitMs < desc->latency() * 2) {
7454 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007455 }
7456 }
7457 }
7458 }
7459 }
7460 }
7461
Eric Laurent99401132014-05-07 19:48:15 -07007462 // temporary mute output if device selection changes to avoid volume bursts due to
7463 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007464 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007465 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007466
Eric Laurentdc462862016-07-19 12:29:53 -07007467 if (muteWaitMs < tempMuteWaitMs) {
7468 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007469 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007470
7471 // If recommended duration is defined, replace temporary mute duration to avoid
7472 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7473 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7474 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7475 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7476 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7477
François Gaffieaaac0fd2018-11-22 17:56:39 +01007478 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7479 // make sure that we do not start the temporary mute period too early in case of
7480 // delayed device change
7481 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7482 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007483 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007484 }
7485 }
7486
Eric Laurente552edb2014-03-10 17:42:56 -07007487 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7488 if (muteWaitMs > delayMs) {
7489 muteWaitMs -= delayMs;
7490 usleep(muteWaitMs * 1000);
7491 return muteWaitMs;
7492 }
7493 return 0;
7494}
7495
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307496uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7497 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007498 const DeviceVector &devices,
7499 bool force,
7500 int delayMs,
7501 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007502 bool requiresMuteCheck, bool requiresVolumeCheck,
7503 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007504{
jiabin3ff8d7d2022-12-13 06:27:44 +00007505 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307506 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7507 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7508 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007509 uint32_t muteWaitMs;
7510
7511 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307512 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007513 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307514 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007515 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007516 return muteWaitMs;
7517 }
Eric Laurente552edb2014-03-10 17:42:56 -07007518
7519 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007520 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007521 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007522 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007523
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307524 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7525 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007526
7527 if (!filteredDevices.isEmpty()) {
7528 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007529 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007530
7531 // if the outputs are not materially active, there is no need to mute.
7532 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007533 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007534 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307535 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7536 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007537 muteWaitMs = 0;
7538 }
Eric Laurente552edb2014-03-10 17:42:56 -07007539
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007540 bool outputRouted = outputDesc->isRouted();
7541
Eric Laurent79ea9582020-06-11 18:49:24 -07007542 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7543 // output profile or if new device is not supported AND previous device(s) is(are) still
7544 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007545 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307546 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7547 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007548 // restore previous device after evaluating strategy mute state
7549 outputDesc->setDevices(prevDevices);
7550 return muteWaitMs;
7551 }
7552
Eric Laurente552edb2014-03-10 17:42:56 -07007553 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007554 // the requested device is AUDIO_DEVICE_NONE
7555 // OR the requested device is the same as current device
7556 // AND force is not specified
7557 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007558 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007559 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307560 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7561 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7562 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007563 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307564 ALOGV("%s %s setting same device on routed output, force apply volumes",
7565 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007566 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7567 }
Eric Laurente552edb2014-03-10 17:42:56 -07007568 return muteWaitMs;
7569 }
7570
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307571 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7572 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007573
Eric Laurente552edb2014-03-10 17:42:56 -07007574 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007575 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007576 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007577 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007578 PatchBuilder patchBuilder;
7579 patchBuilder.addSource(outputDesc);
7580 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7581 for (const auto &filteredDevice : filteredDevices) {
7582 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007583 }
7584
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007585 // Add half reported latency to delayMs when muteWaitMs is null in order
7586 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007587 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7588 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7589 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007590 }
Eric Laurente552edb2014-03-10 17:42:56 -07007591
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007592 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7593 if (!skipMuteDelay) {
7594 // update stream volumes according to new device
7595 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7596 }
Eric Laurente552edb2014-03-10 17:42:56 -07007597
7598 return muteWaitMs;
7599}
7600
Eric Laurentc75307b2015-03-17 15:29:32 -07007601status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007602 int delayMs,
7603 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007604{
Eric Laurent6a94d692014-05-20 11:18:06 -07007605 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007606 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7607 return INVALID_OPERATION;
7608 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007609 if (patchHandle) {
7610 index = mAudioPatches.indexOfKey(*patchHandle);
7611 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007612 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007613 }
7614 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007615 return INVALID_OPERATION;
7616 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007617 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007618 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007619 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007620 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007621 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007622 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007623 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007624 return status;
7625}
7626
7627status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007628 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007629 bool force,
7630 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007631{
7632 status_t status = NO_ERROR;
7633
Eric Laurent1f2f2232014-06-02 12:01:23 -07007634 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007635 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7636 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007637
François Gaffie11d30102018-11-02 16:09:09 +01007638 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007639 PatchBuilder patchBuilder;
7640 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007641 // AUDIO_SOURCE_HOTWORD is for internal use only:
7642 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007643 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7644 auto result = usecase;
7645 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7646 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7647 }
7648 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007649 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007650 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007651 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007652 }
7653 }
7654 return status;
7655}
7656
Eric Laurent6a94d692014-05-20 11:18:06 -07007657status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7658 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007659{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007660 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007661 ssize_t index;
7662 if (patchHandle) {
7663 index = mAudioPatches.indexOfKey(*patchHandle);
7664 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007665 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007666 }
7667 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007668 return INVALID_OPERATION;
7669 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007670 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007671 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007672 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007673 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007674 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007675 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007676 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007677 return status;
7678}
7679
François Gaffie11d30102018-11-02 16:09:09 +01007680sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007681 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007682 audio_format_t& format,
7683 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007684 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007685{
7686 // Choose an input profile based on the requested capture parameters: select the first available
7687 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007688 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007689
Atneya Nair0f0a8032022-12-12 16:20:12 -08007690 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7691 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7692 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7693
7694 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007695
jiabin2fd710d2022-05-02 23:20:22 +00007696 for (;;) {
7697 sp<IOProfile> firstInexact = nullptr;
7698 uint32_t updatedSamplingRate = 0;
7699 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7700 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7701 for (const auto& hwModule : mHwModules) {
7702 for (const auto& profile : hwModule->getInputProfiles()) {
7703 // profile->log();
7704 //updatedFormat = format;
jiabinde7ae442024-02-06 00:57:36 +00007705 if (profile->getCompatibilityScore(
7706 DeviceVector(device),
7707 samplingRate,
7708 &updatedSamplingRate,
7709 format,
7710 &updatedFormat,
7711 channelMask,
7712 &updatedChannelMask,
7713 // FIXME ugly cast
7714 (audio_output_flags_t) flags,
7715 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7716 samplingRate = updatedSamplingRate;
7717 format = updatedFormat;
7718 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007719 return profile;
7720 }
jiabinde7ae442024-02-06 00:57:36 +00007721 if (firstInexact == nullptr
7722 && profile->getCompatibilityScore(
7723 DeviceVector(device),
7724 samplingRate,
7725 &updatedSamplingRate,
7726 format,
7727 &updatedFormat,
7728 channelMask,
7729 &updatedChannelMask,
7730 // FIXME ugly cast
7731 (audio_output_flags_t) flags,
7732 false /*exactMatchRequiredForInputFlags*/)
7733 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007734 firstInexact = profile;
7735 }
7736 }
7737 }
7738
7739 if (firstInexact != nullptr) {
7740 samplingRate = updatedSamplingRate;
7741 format = updatedFormat;
7742 channelMask = updatedChannelMask;
7743 return firstInexact;
7744 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7745 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7746 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7747 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7748 flags = AUDIO_INPUT_FLAG_NONE;
7749 } else { // fail
7750 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7751 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7752 samplingRate, format, channelMask, oriFlags);
7753 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007754 }
7755 }
jiabin2fd710d2022-05-02 23:20:22 +00007756
7757 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007758}
7759
François Gaffieaaac0fd2018-11-22 17:56:39 +01007760float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7761 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007762 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007763 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007764{
jiabin9a3361e2019-10-01 09:38:30 -07007765 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007766
7767 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7768 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7769 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7770 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007771 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7772 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7773 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7774 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7775 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena5300db62023-08-30 18:45:18 -07007776 // Verify that the current volume source is not the ringer volume to prevent recursively
7777 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7778 // to the same volume group.
7779 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007780 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7781 mOutputs.isActive(ringVolumeSrc, 0)) {
7782 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007783 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007784 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007785 }
7786
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007787 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007788 if ((volumeSource != callVolumeSrc && (isInCall() ||
7789 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007790 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007791 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7792 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007793 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7794 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7795 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007796 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007797 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007798 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007799 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007800 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007801 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007802 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7803 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7804 // programmatically muted.
7805 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7806 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7807 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007808 bool exemptFromCapping =
7809 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7810 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007811 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7812 volumeSource, volumeDb);
7813 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007814 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7815 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7816 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007817 }
7818 }
Eric Laurente552edb2014-03-10 17:42:56 -07007819 // if a headset is connected, apply the following rules to ring tones and notifications
7820 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007821 // - always attenuate notifications volume by 6dB
7822 // - attenuate ring tones volume by 6dB unless music is not playing and
7823 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007824 // - if music is playing, always limit the volume to current music volume,
7825 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007826 if (!Intersection(deviceTypes,
7827 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7828 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007829 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7830 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007831 ((volumeSource == alarmVolumeSrc ||
7832 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007833 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7834 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7835 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007836 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7837 curves.canBeMuted()) {
7838
Eric Laurente552edb2014-03-10 17:42:56 -07007839 // when the phone is ringing we must consider that music could have been paused just before
7840 // by the music application and behave as if music was active if the last music track was
7841 // just stopped
Oscar Azucena5300db62023-08-30 18:45:18 -07007842 // Verify that the current volume source is not the music volume to prevent recursively
7843 // calling to compute volume. This could happen in cases where music and
7844 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7845 if (volumeSource != musicVolumeSrc &&
7846 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7847 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007848 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007849 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007850 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7851 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007852 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007853 float musicVolDb = computeVolume(musicCurves,
7854 musicVolumeSrc,
7855 musicCurves.getVolumeIndex(musicDevice),
7856 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007857 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7858 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7859 if (volumeDb > minVolDb) {
7860 volumeDb = minVolDb;
7861 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007862 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007863 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7864 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7865 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007866 // on A2DP, also ensure notification volume is not too low compared to media when
7867 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007868 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007869 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007870 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7871 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007872 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7873 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007874 }
7875 }
jiabin9a3361e2019-10-01 09:38:30 -07007876 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007877 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007878 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007879 }
7880 }
7881
François Gaffie43c73442018-11-08 08:21:55 +01007882 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007883}
7884
Eric Laurent3839bc02018-07-10 18:33:34 -07007885int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007886 VolumeSource fromVolumeSource,
7887 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007888{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007889 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007890 return srcIndex;
7891 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007892 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7893 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007894 float minSrc = (float)srcCurves.getVolumeIndexMin();
7895 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7896 float minDst = (float)dstCurves.getVolumeIndexMin();
7897 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007898
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007899 // preserve mute request or correct range
7900 if (srcIndex < minSrc) {
7901 if (srcIndex == 0) {
7902 return 0;
7903 }
7904 srcIndex = minSrc;
7905 } else if (srcIndex > maxSrc) {
7906 srcIndex = maxSrc;
7907 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007908 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7909}
7910
François Gaffieaaac0fd2018-11-22 17:56:39 +01007911status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7912 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007913 int index,
7914 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007915 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007916 int delayMs,
7917 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007918{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007919 // do not change actual attributes volume if the attributes is muted
7920 if (outputDesc->isMuted(volumeSource)) {
7921 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7922 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007923 return NO_ERROR;
7924 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007925
Eric Laurent5baf07c2024-01-11 16:57:27 +00007926 bool isVoiceVolSrc;
7927 bool isBtScoVolSrc;
7928 if (!isVolumeConsistentForCalls(
7929 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07007930 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00007931 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07007932 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007933 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00007934
jiabin9a3361e2019-10-01 09:38:30 -07007935 if (deviceTypes.empty()) {
7936 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007937 index = curves.getVolumeIndex(deviceTypes);
7938 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7939 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007940 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007941
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007942 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7943 ALOGE("invalid volume index range");
7944 return BAD_VALUE;
7945 }
7946
jiabin9a3361e2019-10-01 09:38:30 -07007947 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7948 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007949 // Force VoIP volume to max for bluetooth SCO device except if muted
7950 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007951 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007952 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007953 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007954 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007955 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7956 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007957
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007958 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00007959 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007960 }
Eric Laurente552edb2014-03-10 17:42:56 -07007961 return NO_ERROR;
7962}
7963
Eric Laurent5baf07c2024-01-11 16:57:27 +00007964void AudioPolicyManager::setVoiceVolume(
7965 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
7966 float voiceVolume;
7967 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
7968 // by the headset
7969 if (isVoiceVolSrc) {
7970 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
7971 } else {
7972 voiceVolume = index == 0 ? 0.0 : 1.0;
7973 }
7974 if (voiceVolume != mLastVoiceVolume) {
7975 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7976 mLastVoiceVolume = voiceVolume;
7977 }
7978}
7979
7980bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
7981 const DeviceTypeSet& deviceTypes,
7982 bool& isVoiceVolSrc,
7983 bool& isBtScoVolSrc,
7984 const char* caller) {
7985 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7986 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7987 const bool isScoRequested = isScoRequestedForComm();
7988 const bool isHAUsed = isHearingAidUsedForComm();
7989
7990 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7991 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
7992
7993 if ((callVolSrc != btScoVolSrc) &&
7994 ((isVoiceVolSrc && isScoRequested) ||
7995 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7996 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
7997 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
7998 volumeSource, isScoRequested ? " " : " not ");
7999 return false;
8000 }
8001 return true;
8002}
8003
Eric Laurentc75307b2015-03-17 15:29:32 -07008004void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008005 const DeviceTypeSet& deviceTypes,
8006 int delayMs,
8007 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008008{
jiabincd510522020-01-22 09:40:55 -08008009 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008010 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8011 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8012 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008013 curves.getVolumeIndex(deviceTypes),
8014 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008015 }
8016}
8017
François Gaffiec005e562018-11-06 15:04:49 +01008018void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8019 bool on,
8020 const sp<AudioOutputDescriptor>& outputDesc,
8021 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008022 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008023{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008024 std::vector<VolumeSource> sourcesToMute;
8025 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8026 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8027 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008028 VolumeSource source = toVolumeSource(attributes, false);
8029 if ((source != VOLUME_SOURCE_NONE) &&
8030 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8031 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008032 sourcesToMute.push_back(source);
8033 }
Eric Laurente552edb2014-03-10 17:42:56 -07008034 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008035 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008036 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008037 }
8038
Eric Laurente552edb2014-03-10 17:42:56 -07008039}
8040
François Gaffieaaac0fd2018-11-22 17:56:39 +01008041void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8042 bool on,
8043 const sp<AudioOutputDescriptor>& outputDesc,
8044 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008045 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008046{
jiabin9a3361e2019-10-01 09:38:30 -07008047 if (deviceTypes.empty()) {
8048 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008049 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008050 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008051 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008052 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008053 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008054 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008055 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8056 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008057 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008058 }
8059 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008060 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8061 // ignored
8062 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008063 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008064 if (!outputDesc->isMuted(volumeSource)) {
8065 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008066 return;
8067 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008068 if (outputDesc->decMuteCount(volumeSource) == 0) {
8069 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008070 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008071 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008072 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008073 delayMs);
8074 }
8075 }
8076}
8077
François Gaffie53615e22015-03-19 09:24:12 +01008078bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8079{
François Gaffiec005e562018-11-06 15:04:49 +01008080 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008081 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8082 return true;
8083 }
8084
8085 // has known usage?
8086 switch (paa->usage) {
8087 case AUDIO_USAGE_UNKNOWN:
8088 case AUDIO_USAGE_MEDIA:
8089 case AUDIO_USAGE_VOICE_COMMUNICATION:
8090 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8091 case AUDIO_USAGE_ALARM:
8092 case AUDIO_USAGE_NOTIFICATION:
8093 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8094 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8095 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8096 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8097 case AUDIO_USAGE_NOTIFICATION_EVENT:
8098 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8099 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8100 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8101 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008102 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008103 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008104 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008105 case AUDIO_USAGE_EMERGENCY:
8106 case AUDIO_USAGE_SAFETY:
8107 case AUDIO_USAGE_VEHICLE_STATUS:
8108 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008109 break;
8110 default:
8111 return false;
8112 }
8113 return true;
8114}
8115
François Gaffie2110e042015-03-24 08:41:51 +01008116audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8117{
8118 return mEngine->getForceUse(usage);
8119}
8120
Eric Laurent96d1dda2022-03-14 17:14:19 +01008121bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008122 return isStateInCall(mEngine->getPhoneState());
8123}
8124
Eric Laurent96d1dda2022-03-14 17:14:19 +01008125bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008126 return is_state_in_call(state);
8127}
8128
Eric Laurentf9cccec2022-11-16 19:12:00 +01008129bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008130 audio_mode_t mode = mEngine->getPhoneState();
8131 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008132 || (mode == AUDIO_MODE_CALL_SCREEN)
8133 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008134}
8135
Eric Laurentf9cccec2022-11-16 19:12:00 +01008136bool AudioPolicyManager::isInCallOrScreening() const {
8137 audio_mode_t mode = mEngine->getPhoneState();
8138 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8139}
8140
Eric Laurentd60560a2015-04-10 11:31:20 -07008141void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8142{
8143 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008144 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008145 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008146 sourceDesc->sinkDevice()->equals(deviceDesc))
8147 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008148 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008149 }
8150 }
8151
8152 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8153 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8154 bool release = false;
8155 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8156 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8157 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8158 source->ext.device.type == deviceDesc->type()) {
8159 release = true;
8160 }
8161 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008162 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008163 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8164 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8165 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008166 sink->ext.device.type == deviceDesc->type() &&
8167 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8168 || strncmp(sink->ext.device.address, address,
8169 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008170 release = true;
8171 }
8172 }
8173 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008174 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8175 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008176 }
8177 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008178
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008179 mInputs.clearSessionRoutesForDevice(deviceDesc);
8180
Francois Gaffie716e1432019-01-14 16:58:59 +01008181 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008182}
8183
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008184void AudioPolicyManager::modifySurroundFormats(
8185 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008186 std::unordered_set<audio_format_t> enforcedSurround(
8187 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008188 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008189 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008190 allSurround.insert(pair.first);
8191 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8192 }
Phil Burk09bc4612016-02-24 15:58:15 -08008193
8194 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8195 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008196 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008197 // This is the resulting set of formats depending on the surround mode:
8198 // 'all surround' = allSurround
8199 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8200 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8201 // 'manual surround' = mManualSurroundFormats
8202 // AUTO: formats v 'enforced surround'
8203 // ALWAYS: formats v 'all surround' v 'enforced surround'
8204 // NEVER: formats ^ 'non-surround'
8205 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008206
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008207 std::unordered_set<audio_format_t> formatSet;
8208 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8209 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008210 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008211 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008212 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008213 formatSet.insert(*formatIter);
8214 }
8215 }
8216 } else {
8217 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8218 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008219 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008220
jiabin81772902018-04-02 17:52:27 -07008221 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008222 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008223 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8224 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8225 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008226 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008227 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8228 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8229 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008230 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008231 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008232 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008233 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008234 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008235 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008236}
8237
jiabin06e4bab2019-07-29 10:13:34 -07008238void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8239 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008240 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8241 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8242
8243 // If NEVER, then remove support for channelMasks > stereo.
8244 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008245 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8246 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008247 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008248 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008249 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008250 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008251 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008252 }
8253 }
jiabin81772902018-04-02 17:52:27 -07008254 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8255 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8256 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008257 bool supports5dot1 = false;
8258 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008259 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008260 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8261 supports5dot1 = true;
8262 break;
8263 }
8264 }
8265 // If not then add 5.1 support.
8266 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008267 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008268 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008269 }
Phil Burk09bc4612016-02-24 15:58:15 -08008270 }
8271}
8272
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008273void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008274 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008275 const sp<IOProfile>& profile) {
8276 if (!profile->hasDynamicAudioProfile()) {
8277 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008278 }
François Gaffie112b0af2015-11-19 16:13:25 +01008279
jiabin12537fc2023-10-12 17:56:08 +00008280 audio_port_v7 devicePort;
8281 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008282
jiabin12537fc2023-10-12 17:56:08 +00008283 audio_port_v7 mixPort;
8284 profile->toAudioPort(&mixPort);
8285 mixPort.ext.mix.handle = ioHandle;
8286
8287 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8288 if (status != NO_ERROR) {
8289 ALOGE("%s failed to query the attributes of the mix port", __func__);
8290 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008291 }
jiabin12537fc2023-10-12 17:56:08 +00008292
8293 std::set<audio_format_t> supportedFormats;
8294 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8295 supportedFormats.insert(mixPort.audio_profiles[i].format);
8296 }
8297 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8298 mReportedFormatsMap[devDesc] = formats;
8299
8300 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8301 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8302 modifySurroundFormats(devDesc, &formats);
8303 size_t modifiedNumProfiles = 0;
8304 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8305 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8306 formats.end()) {
8307 // Skip the format that is not present after modifying surround formats.
8308 continue;
8309 }
8310 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8311 sizeof(struct audio_profile));
8312 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8313 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8314 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8315 modifySurroundChannelMasks(&channels);
8316 std::copy(channels.begin(), channels.end(),
8317 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8318 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8319 }
8320 mixPort.num_audio_profiles = modifiedNumProfiles;
8321 }
8322 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008323}
Eric Laurentd60560a2015-04-10 11:31:20 -07008324
Mikhail Naganovdc769682018-05-04 15:34:08 -07008325status_t AudioPolicyManager::installPatch(const char *caller,
8326 audio_patch_handle_t *patchHandle,
8327 AudioIODescriptorInterface *ioDescriptor,
8328 const struct audio_patch *patch,
8329 int delayMs)
8330{
8331 ssize_t index = mAudioPatches.indexOfKey(
8332 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8333 *patchHandle : ioDescriptor->getPatchHandle());
8334 sp<AudioPatch> patchDesc;
8335 status_t status = installPatch(
8336 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8337 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008338 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008339 }
8340 return status;
8341}
8342
8343status_t AudioPolicyManager::installPatch(const char *caller,
8344 ssize_t index,
8345 audio_patch_handle_t *patchHandle,
8346 const struct audio_patch *patch,
8347 int delayMs,
8348 uid_t uid,
8349 sp<AudioPatch> *patchDescPtr)
8350{
8351 sp<AudioPatch> patchDesc;
8352 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8353 if (index >= 0) {
8354 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008355 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008356 }
8357
8358 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8359 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8360 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8361 if (status == NO_ERROR) {
8362 if (index < 0) {
8363 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008364 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008365 } else {
8366 patchDesc->mPatch = *patch;
8367 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008368 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008369 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008370 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008371 }
8372 nextAudioPortGeneration();
8373 mpClientInterface->onAudioPatchListUpdate();
8374 }
8375 if (patchDescPtr) *patchDescPtr = patchDesc;
8376 return status;
8377}
8378
jiabinbce0c1d2020-10-05 11:20:18 -07008379bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8380{
8381 const TrackClientVector activeClients = output->getActiveClients();
8382 if (activeClients.empty()) {
8383 return true;
8384 }
8385 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8386 if (index < 0) {
8387 ALOGE("%s, no audio patch found while there are active clients on output %d",
8388 __func__, output->getId());
8389 return false;
8390 }
8391 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8392 DeviceVector routedDevices;
8393 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8394 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8395 patchDesc->mPatch.sinks[i].id);
8396 if (device == nullptr) {
8397 ALOGE("%s, no audio device found with id(%d)",
8398 __func__, patchDesc->mPatch.sinks[i].id);
8399 return false;
8400 }
8401 routedDevices.add(device);
8402 }
8403 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008404 if (client->isInvalid()) {
8405 // No need to take care about invalidated clients.
8406 continue;
8407 }
jiabinbce0c1d2020-10-05 11:20:18 -07008408 sp<DeviceDescriptor> preferredDevice =
8409 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8410 if (mEngine->getOutputDevicesForAttributes(
8411 client->attributes(), preferredDevice, false) == routedDevices) {
8412 return false;
8413 }
8414 }
8415 return true;
8416}
8417
8418sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008419 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008420 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8421 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008422{
8423 for (const auto& device : devices) {
8424 // TODO: This should be checking if the profile supports the device combo.
8425 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008426 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8427 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008428 return nullptr;
8429 }
8430 }
8431 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8432 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008433 status_t status = desc->open(halConfig, mixerConfig, devices,
8434 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008435 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008436 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008437 return nullptr;
8438 }
8439
8440 // Here is where the out_set_parameters() for card & device gets called
8441 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8442 const audio_devices_t deviceType = device->type();
8443 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008444 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008445 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8446 mpClientInterface->setParameters(output, String8(param));
8447 free(param);
8448 }
jiabin12537fc2023-10-12 17:56:08 +00008449 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008450 if (!profile->hasValidAudioProfile()) {
8451 ALOGW("%s() missing param", __func__);
8452 desc->close();
8453 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008454 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8455 // Reopen the output with the best audio profile picked by APM when the profile supports
8456 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008457 desc->close();
8458 output = AUDIO_IO_HANDLE_NONE;
8459 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8460 profile->pickAudioProfile(
8461 config.sample_rate, config.channel_mask, config.format);
8462 config.offload_info.sample_rate = config.sample_rate;
8463 config.offload_info.channel_mask = config.channel_mask;
8464 config.offload_info.format = config.format;
8465
jiabina84c3d32022-12-02 18:59:55 +00008466 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008467 if (status != NO_ERROR) {
8468 return nullptr;
8469 }
8470 }
8471
8472 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008473
baek.kim -61c20122022-07-27 10:05:32 +00008474 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8475 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8476
jiabinbce0c1d2020-10-05 11:20:18 -07008477 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8478 sp<AudioPolicyMix> policyMix;
8479 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8480 policyMix->setOutput(desc);
8481 desc->mPolicyMix = policyMix;
8482 } else {
8483 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008484 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008485 }
8486
baek.kim -61c20122022-07-27 10:05:32 +00008487 } else if (hasPrimaryOutput() && speaker != nullptr
8488 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008489 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8490 // no duplicated output for:
8491 // - direct outputs
8492 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008493 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008494 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8495
8496 //TODO: configure audio effect output stage here
8497
8498 // open a duplicating output thread for the new output and the primary output
8499 sp<SwAudioOutputDescriptor> dupOutputDesc =
8500 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8501 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8502 if (status == NO_ERROR) {
8503 // add duplicated output descriptor
8504 addOutput(duplicatedOutput, dupOutputDesc);
8505 } else {
8506 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8507 mPrimaryOutput->mIoHandle, output);
8508 desc->close();
8509 removeOutput(output);
8510 nextAudioPortGeneration();
8511 return nullptr;
8512 }
8513 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008514 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8515 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8516 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008517 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008518 }
jiabinbce0c1d2020-10-05 11:20:18 -07008519 return desc;
8520}
8521
jiabinf1c73972022-04-14 16:28:52 -07008522status_t AudioPolicyManager::getDevicesForAttributes(
8523 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8524 // Devices are determined in the following precedence:
8525 //
8526 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8527 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8528 //
8529 // If no such dynamic policy then
8530 // 2) Devices containing an active client using setPreferredDevice
8531 // with same strategy as the attributes.
8532 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8533 //
8534 // If no corresponding active client with setPreferredDevice then
8535 // 3) Devices associated with the strategy determined by the attributes
8536 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8537 //
8538 // See related getOutputForAttrInt().
8539
8540 // check dynamic policies but only for primary descriptors (secondary not used for audible
8541 // audio routing, only used for duplication for playback capture)
8542 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008543 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008544 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008545 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8546 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8547 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008548 if (status != OK) {
8549 return status;
8550 }
8551
8552 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8553 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8554 // as they are unaffected by device/stream volume
8555 // (per SwAudioOutputDescriptor::isFixedVolume()).
8556 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8557 ) {
8558 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8559 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8560 devices.add(deviceDesc);
8561 } else {
8562 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8563 // which selects setPreferredDevice if active. This means forVolume call
8564 // will take an active setPreferredDevice, if such exists.
8565
8566 devices = mEngine->getOutputDevicesForAttributes(
8567 attr, nullptr /* preferredDevice */, false /* fromCache */);
8568 }
8569
8570 if (forVolume) {
8571 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8572 // for single volume control in AudioService (such relationship should exist if
8573 // SPEAKER_SAFE is present).
8574 //
8575 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8576 DeviceVector speakerSafeDevices =
8577 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8578 if (!speakerSafeDevices.isEmpty()) {
8579 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8580 devices.remove(speakerSafeDevices);
8581 }
8582 }
8583
8584 return NO_ERROR;
8585}
8586
8587status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8588 AudioProfileVector& audioProfiles,
8589 uint32_t flags,
8590 bool isInput) {
8591 for (const auto& hwModule : mHwModules) {
8592 // the MSD module checks for different conditions
8593 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8594 continue;
8595 }
8596 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8597 : hwModule->getOutputProfiles();
8598 for (const auto& profile : ioProfiles) {
8599 if (!profile->areAllDevicesSupported(devices) ||
8600 !profile->isCompatibleProfileForFlags(
8601 flags, false /*exactMatchRequiredForInputFlags*/)) {
8602 continue;
8603 }
8604 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8605 }
8606 }
8607
8608 if (!isInput) {
8609 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8610 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8611 if (msdModule != nullptr) {
8612 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8613 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8614 for (const auto &profile: msdModule->getOutputProfiles()) {
8615 if (!profile->asAudioPort()->isDirectOutput()) {
8616 continue;
8617 }
8618 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8619 }
8620 } else {
8621 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8622 }
8623 }
8624 }
8625
8626 return NO_ERROR;
8627}
8628
jiabin3ff8d7d2022-12-13 06:27:44 +00008629sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8630 const audio_config_t *config,
8631 audio_output_flags_t flags,
8632 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008633 closeOutput(outputDesc->mIoHandle);
8634 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8635 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8636 if (preferredOutput == nullptr) {
8637 ALOGE("%s failed to reopen output device=%d, caller=%s",
8638 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008639 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008640 return preferredOutput;
8641}
8642
8643void AudioPolicyManager::reopenOutputsWithDevices(
8644 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8645 for (const auto& [output, devices] : outputsToReopen) {
8646 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8647 closeOutput(output);
8648 openOutputWithProfileAndDevice(desc->mProfile, devices);
8649 }
jiabina84c3d32022-12-02 18:59:55 +00008650}
8651
jiabinc44b3462022-12-08 12:52:31 -08008652PortHandleVector AudioPolicyManager::getClientsForStream(
8653 audio_stream_type_t streamType) const {
8654 PortHandleVector clients;
8655 for (size_t i = 0; i < mOutputs.size(); ++i) {
8656 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8657 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8658 }
8659 return clients;
8660}
8661
8662void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8663 PortHandleVector clients;
8664 for (auto stream : streams) {
8665 PortHandleVector clientsForStream = getClientsForStream(stream);
8666 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8667 }
8668 mpClientInterface->invalidateTracks(clients);
8669}
8670
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008671} // namespace android