blob: d427de45a4cdc9f1647671ab9f1d278de6b9dce5 [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);
François Gaffie44481e72016-04-20 07:49:57 +0200393
Eric Laurent0dd51852019-04-19 18:18:58 -0700394 if (checkInputsForDevice(device, state) != NO_ERROR) {
395 mAvailableInputDevices.remove(device);
396
jiabinc0048632023-04-27 22:04:31 +0000397 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100398
399 mHwModules.cleanUpForDevice(device);
400
Eric Laurentd4692962014-05-05 18:13:44 -0700401 return INVALID_OPERATION;
402 }
403
Eric Laurentd4692962014-05-05 18:13:44 -0700404 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700405
406 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700407 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700408 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100409 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700410 return INVALID_OPERATION;
411 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700412
François Gaffie11d30102018-11-02 16:09:09 +0100413 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700414
jiabinc0048632023-04-27 22:04:31 +0000415 // Notify the HAL to prepare to disconnect device
416 broadcastDeviceConnectionState(
417 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700418
François Gaffie11d30102018-11-02 16:09:09 +0100419 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700420
421 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100422
jiabinc0048632023-04-27 22:04:31 +0000423 // Set Disconnect to HALs
424 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
425
Kriti Dangef6be8f2020-11-05 11:58:19 +0100426 // remove device from mReportedFormatsMap cache
427 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700428 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700429
430 default:
François Gaffie11d30102018-11-02 16:09:09 +0100431 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700432 return BAD_VALUE;
433 }
434
Eric Laurent736a1022019-03-27 18:28:46 -0700435 // Propagate device availability to Engine
436 setEngineDeviceConnectionState(device, state);
437
Eric Laurent0dd51852019-04-19 18:18:58 -0700438 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700439 // As the input device list can impact the output device selection, update
440 // getDeviceForStrategy() cache
441 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700442
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100443 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200444 // Reconnect Audio Source
445 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
446 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
447 checkAudioSourceForAttributes(attributes);
448 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700449 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100450 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700451 }
452
Eric Laurentb52c1522014-05-20 11:27:36 -0700453 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700454 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700455 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700456
François Gaffie11d30102018-11-02 16:09:09 +0100457 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700458 return BAD_VALUE;
459}
460
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100461status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
462 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800463 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000464 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
465 devDescr->setName(device_name);
466 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100467}
468
Eric Laurent736a1022019-03-27 18:28:46 -0700469void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
470 audio_policy_dev_state_t state) {
471
472 // the Engine does not have to know about remote submix devices used by dynamic audio policies
473 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
474 return;
475 }
476 mEngine->setDeviceConnectionState(device, state);
477}
478
479
Eric Laurente0720872014-03-11 09:30:41 -0700480audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100481 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700482{
Eric Laurent634b7142016-04-20 13:48:02 -0700483 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800484 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
485 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700486 (strlen(device_address) != 0)/*matchAddress*/);
487
488 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100489 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700490 device, device_address);
491 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
492 }
François Gaffie53615e22015-03-19 09:24:12 +0100493
Eric Laurent3a4311c2014-03-17 12:00:47 -0700494 DeviceVector *deviceVector;
495
Eric Laurente552edb2014-03-10 17:42:56 -0700496 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700497 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700498 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700499 deviceVector = &mAvailableInputDevices;
500 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100501 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700502 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700503 }
Eric Laurent634b7142016-04-20 13:48:02 -0700504
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800505 return (deviceVector->getDevice(
506 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700507 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800508}
509
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800510status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
511 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800512 const char *device_name,
513 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800514{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800515 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
516 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800517
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800518 // connect/disconnect only 1 device at a time
519 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
520
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800521 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700522 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800523 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800524 // Nothing to do: device is not connected
525 return NO_ERROR;
526 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700529 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800530 // configure codecs.
531 // Handle two specific cases by sending a set parameter to
532 // configure A2DP codecs. No need to toggle device state.
533 // Case 1: A2DP active device switches from primary to primary
534 // module
535 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100536 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700537 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
539 if (availablePrimaryOutputDevices().contains(devDesc) &&
540 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100541 bool isA2dp = audio_is_a2dp_out_device(device);
542 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
543 : String8(AudioParameter::keyReconfigLeSupported);
544 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800545 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100546 int isReconfigSupported;
547 repliedParameters.getInt(supportKey, isReconfigSupported);
548 if (isReconfigSupported) {
549 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
550 : String8(AudioParameter::keyReconfigLe);
551 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800552 param.add(key, String8("true"));
553 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
554 devDesc->setEncodedFormat(encodedFormat);
555 return NO_ERROR;
556 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700557 }
558 }
cnx421bd2dcc42020-07-11 14:58:44 +0800559 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
560 for (size_t i = 0; i < mOutputs.size(); i++) {
561 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
562 // mute media strategies and delay device switch by the largest
563 // This avoid sending the music tail into the earpiece or headset.
564 setStrategyMute(musicStrategy, true, desc);
565 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
566 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
567 nullptr, true /*fromCache*/).types());
568 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800569 // Toggle the device state: UNAVAILABLE -> AVAILABLE
570 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100571 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800572 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800573 device_address, device_name,
574 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800575 if (status != NO_ERROR) {
576 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
577 status);
578 return status;
579 }
580
581 status = setDeviceConnectionState(device,
582 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800583 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800584 if (status != NO_ERROR) {
585 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
586 status);
587 return status;
588 }
589
590 return NO_ERROR;
591}
592
Pattydd807582021-11-04 21:01:03 +0800593status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
594 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800595{
Pattydd807582021-11-04 21:01:03 +0800596 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800597 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800598 std::unordered_set<audio_format_t> formatSet;
599 sp<HwModule> primaryModule =
600 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700601 if (primaryModule == nullptr) {
602 ALOGE("%s() unable to get primary module", __func__);
603 return NO_INIT;
604 }
Pattydd807582021-11-04 21:01:03 +0800605
606 DeviceTypeSet audioDeviceSet;
607
608 switch(device) {
609 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
610 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
611 break;
612 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800613 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
614 break;
615 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
616 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800617 break;
618 default:
619 ALOGE("%s() device type 0x%08x not supported", __func__, device);
620 return BAD_VALUE;
621 }
622
jiabin9a3361e2019-10-01 09:38:30 -0700623 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800624 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800625 for (const auto& device : declaredDevices) {
626 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800627 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800628 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800629 return status;
630}
631
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100632DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
633{
634 DeviceVector rxSinkdevices{};
635 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
636 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
637 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
638 auto rxSinkDevice = rxSinkdevices.itemAt(0);
639 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
640 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
641 // retrieve Rx Source device descriptor
642 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
643 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
644
645 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
646 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
647 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
648 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
649 return DeviceVector(rxSinkDevice);
650 }
651 }
652 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
653 // the device returned is not necessarily reachable via this output
654 // (filter later by setOutputDevices())
655 return getNewOutputDevices(mPrimaryOutput, fromCache);
656}
657
658status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
659{
François Gaffiedb1755b2023-09-01 11:50:35 +0200660 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100661 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
662 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
663 }
664 return INVALID_OPERATION;
665}
666
667status_t AudioPolicyManager::updateCallRoutingInternal(
668 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700669{
670 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100671 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700672 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200673 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700674 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100675 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700676 }
François Gaffie11d30102018-11-02 16:09:09 +0100677
Francois Gaffie716e1432019-01-14 16:58:59 +0100678 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100679 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200680
681 disconnectTelephonyAudioSource(mCallRxSourceClient);
682 disconnectTelephonyAudioSource(mCallTxSourceClient);
683
684 if (rxDevices.isEmpty()) {
685 ALOGW("%s() no selected output device", __func__);
686 return INVALID_OPERATION;
687 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000688 if (txSourceDevice == nullptr) {
689 ALOGE("%s() selected input device not available", __func__);
690 return INVALID_OPERATION;
691 }
François Gaffiec005e562018-11-06 15:04:49 +0100692
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100693 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100694 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700695
François Gaffie9eb18552018-11-05 10:33:26 +0100696 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700697 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100698 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700699 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100700 // retrieve Rx Source and Tx Sink device descriptors
701 sp<DeviceDescriptor> rxSourceDevice =
702 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
703 String8(),
704 AUDIO_FORMAT_DEFAULT);
705 sp<DeviceDescriptor> txSinkDevice =
706 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
707 String8(),
708 AUDIO_FORMAT_DEFAULT);
709
710 // RX and TX Telephony device are declared by Primary Audio HAL
711 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
712 (telephonyRxModule->getHalVersionMajor() >= 3)) {
713 if (rxSourceDevice == 0 || txSinkDevice == 0) {
714 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100715 ALOGE("%s() no telephony Tx and/or RX device", __func__);
716 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100717 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100718 // createAudioPatchInternal now supports both HW / SW bridging
719 createRxPatch = true;
720 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100721 } else {
722 // If the RX device is on the primary HW module, then use legacy routing method for
723 // voice calls via setOutputDevice() on primary output.
724 // Otherwise, create two audio patches for TX and RX path.
725 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
726 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700727 // If the TX device is also on the primary HW module, setOutputDevice() will take care
728 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100729 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
730 (txSinkDevice != 0);
731 }
732 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
733 // Otherwise, create two audio patches for TX and RX path.
734 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200735 if (!hasPrimaryOutput()) {
736 ALOGW("%s() no primary output available", __func__);
737 return INVALID_OPERATION;
738 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530739 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700740 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200741 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800742 // If the TX device is on the primary HW module but RX device is
743 // on other HW module, SinkMetaData of telephony input should handle it
744 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700745 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700746 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100747 // terminate active capture if on the same HW module as the call TX source device
748 // FIXME: would be better to refine to only inputs whose profile connects to the
749 // call TX device but this information is not in the audio patch and logic here must be
750 // symmetric to the one in startInput()
751 for (const auto& activeDesc : mInputs.getActiveInputs()) {
752 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
753 closeActiveClients(activeDesc);
754 }
755 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200756 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800757 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100758 if (waitMs != nullptr) {
759 *waitMs = muteWaitMs;
760 }
761 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800762}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700763
Mikhail Naganov100f0122018-11-29 11:22:16 -0800764bool AudioPolicyManager::isDeviceOfModule(
765 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
766 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
767 if (module != 0) {
768 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
769 .indexOf(devDesc) != NAME_NOT_FOUND
770 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
771 .indexOf(devDesc) != NAME_NOT_FOUND;
772 }
773 return false;
774}
775
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200776void AudioPolicyManager::connectTelephonyRxAudioSource()
777{
Francois Gaffie601801d2021-06-22 13:27:39 +0200778 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200779 const struct audio_port_config source = {
780 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
781 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
782 };
783 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200784 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
785 ALOGE_IF(mCallRxSourceClient == nullptr,
786 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200787}
788
Francois Gaffie601801d2021-06-22 13:27:39 +0200789void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200790{
Francois Gaffie601801d2021-06-22 13:27:39 +0200791 if (clientDesc == nullptr) {
792 return;
793 }
794 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
795 "%s error stopping audio source", __func__);
796 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200797}
798
799void AudioPolicyManager::connectTelephonyTxAudioSource(
800 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
801 uint32_t delayMs)
802{
Francois Gaffie601801d2021-06-22 13:27:39 +0200803 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200804 if (srcDevice == nullptr || sinkDevice == nullptr) {
805 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
806 return;
807 }
808 PatchBuilder patchBuilder;
809 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
810 ALOGV("%s between source %s and sink %s", __func__,
811 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200812 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200813 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
814
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200815 struct audio_port_config source = {};
816 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200817 mCallTxSourceClient = new InternalSourceClientDescriptor(
818 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200819 mCommunnicationStrategy, toVolumeSource(aa));
820 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
821 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200822 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
823 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200824 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
825 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200826 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200827 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200828}
829
Eric Laurente0720872014-03-11 09:30:41 -0700830void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700831{
832 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100833 // store previous phone state for management of sonification strategy below
834 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100835 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100836
837 if (mEngine->setPhoneState(state) != NO_ERROR) {
838 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700839 return;
840 }
François Gaffie2110e042015-03-24 08:41:51 +0100841 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700842 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700843 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700844 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800845 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700846 }
847
François Gaffie2110e042015-03-24 08:41:51 +0100848 /**
849 * Switching to or from incall state or switching between telephony and VoIP lead to force
850 * routing command.
851 */
Eric Laurent74b71512019-11-06 17:21:57 -0800852 bool force = ((isStateInCall(oldState) != isStateInCall(state))
853 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700854
855 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700856 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700857
Eric Laurente552edb2014-03-10 17:42:56 -0700858 int delayMs = 0;
859 if (isStateInCall(state)) {
860 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100861 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
862 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700863 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700864 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700865 // mute media and sonification strategies and delay device switch by the largest
866 // latency of any output where either strategy is active.
867 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100868 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
869 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
870 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700871 (delayMs < (int)desc->latency()*2)) {
872 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700873 }
François Gaffiec005e562018-11-06 15:04:49 +0100874 setStrategyMute(musicStrategy, true, desc);
875 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
876 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
877 nullptr, true /*fromCache*/).types());
878 setStrategyMute(sonificationStrategy, true, desc);
879 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
880 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
881 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700882 }
883 }
884
François Gaffiedb1755b2023-09-01 11:50:35 +0200885 if (state == AUDIO_MODE_IN_CALL) {
886 (void)updateCallRouting(false /*fromCache*/, delayMs);
887 } else {
888 if (oldState == AUDIO_MODE_IN_CALL) {
889 disconnectTelephonyAudioSource(mCallRxSourceClient);
890 disconnectTelephonyAudioSource(mCallTxSourceClient);
891 }
892 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100893 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
894 // force routing command to audio hardware when ending call
895 // even if no device change is needed
896 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
897 rxDevices = mPrimaryOutput->devices();
898 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530899 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700900 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700901 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700902
jiabin3ff8d7d2022-12-13 06:27:44 +0000903 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700904 // reevaluate routing on all outputs in case tracks have been started during the call
905 for (size_t i = 0; i < mOutputs.size(); i++) {
906 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100907 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200908 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
909 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000910 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
911 // If the device is using preferred mixer attributes, the output need to reopen
912 // with default configuration when the new selected devices are different from
913 // current routing devices.
914 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
915 continue;
916 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530917 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200918 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700919 }
920 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000921 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700922
Eric Laurent96d1dda2022-03-14 17:14:19 +0100923 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
924
Eric Laurente552edb2014-03-10 17:42:56 -0700925 if (isStateInCall(state)) {
926 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700927 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800928 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700929 }
930
931 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100932 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
933 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700934}
935
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700936audio_mode_t AudioPolicyManager::getPhoneState() {
937 return mEngine->getPhoneState();
938}
939
Eric Laurente0720872014-03-11 09:30:41 -0700940void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100941 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700942{
François Gaffie2110e042015-03-24 08:41:51 +0100943 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700944 if (config == mEngine->getForceUse(usage)) {
945 return;
946 }
Eric Laurente552edb2014-03-10 17:42:56 -0700947
François Gaffie2110e042015-03-24 08:41:51 +0100948 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
949 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
950 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700951 }
François Gaffie2110e042015-03-24 08:41:51 +0100952 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
953 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
954 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700955
956 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700957 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800958
Eric Laurent22fcda22019-05-17 16:28:47 -0700959 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
960 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800961 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700962 }
963
Eric Laurentdc462862016-07-19 12:29:53 -0700964 //FIXME: workaround for truncated touch sounds
965 // to be removed when the problem is handled by system UI
966 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700967 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
968 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
969 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700970
971 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100972 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700973}
974
Eric Laurente0720872014-03-11 09:30:41 -0700975void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700976{
977 ALOGV("setSystemProperty() property %s, value %s", property, value);
978}
979
Dorin Drimusecc9f422022-03-09 17:57:40 +0100980// Find an MSD output profile compatible with the parameters passed.
981// When "directOnly" is set, restrict search to profiles for direct outputs.
982sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
983 const DeviceVector& devices,
984 uint32_t samplingRate,
985 audio_format_t format,
986 audio_channel_mask_t channelMask,
987 audio_output_flags_t flags,
988 bool directOnly)
989{
990 flags = getRelevantFlags(flags, directOnly);
991
992 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
993 if (msdModule != nullptr) {
994 // for the msd module check if there are patches to the output devices
995 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
996 HwModuleCollection modules;
997 modules.add(msdModule);
998 return searchCompatibleProfileHwModules(
999 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1000 flags, directOnly);
1001 }
1002 }
1003 return nullptr;
1004}
1005
Michael Chana94fbb22018-04-24 14:31:19 +10001006// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1007// search to profiles for direct outputs.
1008sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001009 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001010 uint32_t samplingRate,
1011 audio_format_t format,
1012 audio_channel_mask_t channelMask,
1013 audio_output_flags_t flags,
1014 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001015{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001016 flags = getRelevantFlags(flags, directOnly);
1017
1018 return searchCompatibleProfileHwModules(
1019 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1020}
1021
1022audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1023 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001024 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001025 // only retain flags that will drive the direct output profile selection
1026 // if explicitly requested
1027 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001028 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001029 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1030 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001031 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001032 return flags;
1033}
Eric Laurent861a6282015-05-18 15:40:16 -07001034
Dorin Drimusecc9f422022-03-09 17:57:40 +01001035sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1036 const HwModuleCollection& hwModules,
1037 const DeviceVector& devices,
1038 uint32_t samplingRate,
1039 audio_format_t format,
1040 audio_channel_mask_t channelMask,
1041 audio_output_flags_t flags,
1042 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001043 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001044 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001045 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001046 if (!curProfile->isCompatibleProfile(devices,
1047 samplingRate, NULL /*updatedSamplingRate*/,
1048 format, NULL /*updatedFormat*/,
1049 channelMask, NULL /*updatedChannelMask*/,
1050 flags)) {
1051 continue;
1052 }
1053 // reject profiles not corresponding to a device currently available
1054 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1055 continue;
1056 }
1057 // reject profiles if connected device does not support codec
1058 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1059 continue;
1060 }
1061 if (!directOnly) {
1062 return curProfile;
1063 }
1064
1065 // when searching for direct outputs, if several profiles are compatible, give priority
1066 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001067 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001068 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001069 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001070 }
1071 profile = curProfile;
1072 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1073 break;
1074 }
Eric Laurente552edb2014-03-10 17:42:56 -07001075 }
1076 }
Eric Laurent861a6282015-05-18 15:40:16 -07001077 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001078}
1079
Eric Laurentfa0f6742021-08-17 18:39:44 +02001080sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001081 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001082{
1083 for (const auto& hwModule : mHwModules) {
1084 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001085 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001086 continue;
1087 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001088 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001089 // reject profiles not corresponding to a device currently available
1090 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1091 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1092 continue;
1093 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001094 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1095 != devices.size()) {
1096 continue;
1097 }
1098 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001099 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1100 return curProfile;
1101 }
1102 }
1103 return nullptr;
1104}
1105
Eric Laurentf4e63452017-11-06 19:31:46 +00001106audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001107{
François Gaffiec005e562018-11-06 15:04:49 +01001108 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001109
1110 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1111 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1112 // format, flags, etc. This may result in some discrepancy for functions that utilize
1113 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1114 // and AudioSystem::getOutputSamplingRate().
1115
François Gaffie11d30102018-11-02 16:09:09 +01001116 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001117 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1118 if (stream == AUDIO_STREAM_MUSIC &&
1119 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1120 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1121 }
1122 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001123
François Gaffie11d30102018-11-02 16:09:09 +01001124 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1125 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001126 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001127}
1128
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001129status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1130 const audio_attributes_t *srcAttr,
1131 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001132{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001133 if (srcAttr != NULL) {
1134 if (!isValidAttributes(srcAttr)) {
1135 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1136 __func__,
1137 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1138 srcAttr->tags);
1139 return BAD_VALUE;
1140 }
1141 *dstAttr = *srcAttr;
1142 } else {
1143 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1144 ALOGE("%s: invalid stream type", __func__);
1145 return BAD_VALUE;
1146 }
François Gaffiec005e562018-11-06 15:04:49 +01001147 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001148 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001149
1150 // Only honor audibility enforced when required. The client will be
1151 // forced to reconnect if the forced usage changes.
1152 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001153 dstAttr->flags = static_cast<audio_flags_mask_t>(
1154 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001155 }
1156
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001157 return NO_ERROR;
1158}
1159
Kevin Rocard153f92d2018-12-18 18:33:28 -08001160status_t AudioPolicyManager::getOutputForAttrInt(
1161 audio_attributes_t *resultAttr,
1162 audio_io_handle_t *output,
1163 audio_session_t session,
1164 const audio_attributes_t *attr,
1165 audio_stream_type_t *stream,
1166 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001167 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001168 audio_output_flags_t *flags,
1169 audio_port_handle_t *selectedDeviceId,
1170 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001171 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001172 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001173 bool *isSpatialized,
1174 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001175{
François Gaffiec005e562018-11-06 15:04:49 +01001176 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001177 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001178 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001179 const sp<DeviceDescriptor> requestedDevice =
1180 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1181
Eric Laurent8a1095a2019-11-08 14:44:16 -08001182 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001183 *isSpatialized = false;
1184
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001185 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1186 if (status != NO_ERROR) {
1187 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001188 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001189 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001190 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001191 }
François Gaffiec005e562018-11-06 15:04:49 +01001192 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001193
François Gaffiec005e562018-11-06 15:04:49 +01001194 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1195 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001196
Oscar Azucena873d10f2023-01-12 18:34:42 -08001197 bool usePrimaryOutputFromPolicyMixes = false;
1198
Kevin Rocard153f92d2018-12-18 18:33:28 -08001199 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1200 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1201 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001202 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001203 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1204 .channel_mask = config->channel_mask,
1205 .format = config->format,
1206 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001207 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001208 mAvailableOutputDevices, requestedDevice, primaryMix,
1209 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001210 if (status != OK) {
1211 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001212 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001213
Kevin Rocard153f92d2018-12-18 18:33:28 -08001214 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001215 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1216 && !audio_is_linear_pcm(config->format)) {
1217 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001218 return BAD_VALUE;
1219 }
1220 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001221 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001222 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1223 primaryMix->mDeviceAddress,
1224 AUDIO_FORMAT_DEFAULT);
1225 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001226 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001227 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1228 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001229 // if a direct output can be opened to deliver the track's multi-channel content to the
1230 // output rather than being downmixed by the primary output, then use this direct
1231 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1232 // mix.
1233 bool tryDirectForChannelMask = policyDesc != nullptr
1234 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1235 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001236 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001237 audio_io_handle_t newOutput;
1238 status = openDirectOutput(
1239 *stream, session, config,
1240 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001241 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001242 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001243 policyDesc = mOutputs.valueFor(newOutput);
1244 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001245 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001246 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001247 policyDesc = nullptr;
1248 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001249 }
1250 if (policyDesc != nullptr) {
1251 policyDesc->mPolicyMix = primaryMix;
1252 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001253 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1254 : AUDIO_PORT_HANDLE_NONE;
1255 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1256 // Remove direct flag as it is not on a direct output.
1257 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1258 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001259
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001260 ALOGV("getOutputForAttr() returns output %d", *output);
1261 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1262 *outputType = API_OUT_MIX_PLAYBACK;
1263 } else {
1264 *outputType = API_OUTPUT_LEGACY;
1265 }
1266 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001267 } else {
1268 if (policyMixDevice != nullptr) {
1269 ALOGE("%s, try to use primary mix but no output found", __func__);
1270 return INVALID_OPERATION;
1271 }
1272 // Fallback to default engine selection as the selected primary mix device is not
1273 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001274 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001275 }
François Gaffiec005e562018-11-06 15:04:49 +01001276 // Virtual sources must always be dynamicaly or explicitly routed
1277 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1278 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1279 return BAD_VALUE;
1280 }
1281 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1282 // in order to let the choice of the order to future vendor engine
1283 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001284
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001285 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001286 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001287 }
1288
Nadav Barb2f18162018-07-18 13:01:53 +03001289 // Set incall music only if device was explicitly set, and fallback to the device which is
1290 // chosen by the engine if not.
1291 // FIXME: provide a more generic approach which is not device specific and move this back
1292 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001293 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001294 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001295 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001296 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001297 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001298 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001299 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001300 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001301 }
1302 }
1303
François Gaffiec005e562018-11-06 15:04:49 +01001304 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1305 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1306 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001307
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001308 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001309 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001310 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001311 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001312 ALOGV("%s() Using MSD devices %s instead of devices %s",
1313 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001314 } else {
1315 *output = AUDIO_IO_HANDLE_NONE;
1316 }
1317 }
1318 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001319 sp<PreferredMixerAttributesInfo> info = nullptr;
1320 if (outputDevices.size() == 1) {
1321 info = getPreferredMixerAttributesInfo(
1322 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001323 mEngine->getProductStrategyForAttributes(*resultAttr),
1324 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001325 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1326 // and it is currently active.
1327 if (info != nullptr && info->getUid() != uid &&
1328 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1329 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001330 info = nullptr;
1331 }
1332 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001333 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001334 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001335 // The client will be active if the client is currently preferred mixer owner and the
1336 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001337 *isBitPerfect = (info != nullptr
1338 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001339 && info->getUid() == uid
1340 && *output != AUDIO_IO_HANDLE_NONE
1341 // When bit-perfect output is selected for the preferred mixer attributes owner,
1342 // only need to consider the config matches.
1343 && mOutputs.valueFor(*output)->isConfigurationMatched(
1344 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001345 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001346 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001347 AudioProfileVector profiles;
1348 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1349 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001350 const auto channels = profiles[0]->getChannels();
1351 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1352 config->channel_mask = *channels.begin();
1353 }
1354 const auto sampleRates = profiles[0]->getSampleRates();
1355 if (!sampleRates.empty() &&
1356 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1357 config->sample_rate = *sampleRates.begin();
1358 }
jiabinf1c73972022-04-14 16:28:52 -07001359 config->format = profiles[0]->getFormat();
1360 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001361 return INVALID_OPERATION;
1362 }
Paul McLeanaa981192015-03-21 09:55:15 -07001363
François Gaffiec005e562018-11-06 15:04:49 +01001364 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001365 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001366 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001367 *selectedDeviceId = outputDevice->getId();
1368 break;
1369 }
1370 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001371
Eric Laurent8a1095a2019-11-08 14:44:16 -08001372 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1373 *outputType = API_OUTPUT_TELEPHONY_TX;
1374 } else {
1375 *outputType = API_OUTPUT_LEGACY;
1376 }
1377
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001378 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1379
1380 return NO_ERROR;
1381}
1382
1383status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1384 audio_io_handle_t *output,
1385 audio_session_t session,
1386 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001387 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001388 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001389 audio_output_flags_t *flags,
1390 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001391 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001392 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001393 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001394 bool *isSpatialized,
1395 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001396{
1397 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1398 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1399 return INVALID_OPERATION;
1400 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001401 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001402 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001403 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001404 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001405 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001406 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001407 const sp<DeviceDescriptor> requestedDevice =
1408 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1409
1410 // Prevent from storing invalid requested device id in clients
1411 const audio_port_handle_t sanitizedRequestedPortId =
1412 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1413 *selectedDeviceId = sanitizedRequestedPortId;
1414
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001415 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001416 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001417 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1418 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001419 if (status != NO_ERROR) {
1420 return status;
1421 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001422 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001423 if (secondaryOutputs != nullptr) {
1424 for (auto &secondaryMix : secondaryMixes) {
1425 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1426 if (outputDesc != nullptr &&
1427 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1428 secondaryOutputs->push_back(outputDesc->mIoHandle);
1429 weakSecondaryOutputDescs.push_back(outputDesc);
1430 }
1431 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001432 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001433
Eric Laurent8fc147b2018-07-22 19:13:55 -07001434 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001435 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001436 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001437 };
jiabin4ef93452019-09-10 14:29:54 -07001438 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001439
Eric Laurentc209fe42020-06-05 18:11:23 -07001440 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001441 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001442 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001443 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001444 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001445 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001446 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001447 std::move(weakSecondaryOutputDescs),
1448 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001449 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001450
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001451 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1452 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001453
Eric Laurente83b55d2014-11-14 10:06:21 -08001454 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001455}
1456
Eric Laurentc529cf62020-04-17 18:19:10 -07001457status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1458 audio_session_t session,
1459 const audio_config_t *config,
1460 audio_output_flags_t flags,
1461 const DeviceVector &devices,
1462 audio_io_handle_t *output) {
1463
1464 *output = AUDIO_IO_HANDLE_NONE;
1465
1466 // skip direct output selection if the request can obviously be attached to a mixed output
1467 // and not explicitly requested
1468 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1469 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1470 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1471 return NAME_NOT_FOUND;
1472 }
1473
1474 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1475 // This prevents creating an offloaded track and tearing it down immediately after start
1476 // when audioflinger detects there is an active non offloadable effect.
1477 // FIXME: We should check the audio session here but we do not have it in this context.
1478 // This may prevent offloading in rare situations where effects are left active by apps
1479 // in the background.
1480 sp<IOProfile> profile;
1481 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1482 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1483 profile = getProfileForOutput(
1484 devices, config->sample_rate, config->format, config->channel_mask,
1485 flags, true /* directOnly */);
1486 }
1487
1488 if (profile == nullptr) {
1489 return NAME_NOT_FOUND;
1490 }
1491
1492 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1493 for (size_t i = 0; i < mOutputs.size(); i++) {
1494 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1495 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1496 // reuse direct output if currently open by the same client
1497 // and configured with same parameters
1498 if ((config->sample_rate == desc->getSamplingRate()) &&
1499 (config->format == desc->getFormat()) &&
1500 (config->channel_mask == desc->getChannelMask()) &&
1501 (session == desc->mDirectClientSession)) {
1502 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001503 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001504 mOutputs.keyAt(i), session);
1505 *output = mOutputs.keyAt(i);
1506 return NO_ERROR;
1507 }
1508 }
1509 }
1510
1511 if (!profile->canOpenNewIo()) {
1512 return NAME_NOT_FOUND;
1513 }
1514
1515 sp<SwAudioOutputDescriptor> outputDesc =
1516 new SwAudioOutputDescriptor(profile, mpClientInterface);
1517
Michael Chan6fb34492020-12-08 15:44:49 +11001518 // An MSD patch may be using the only output stream that can service this request. Release
1519 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001520 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001521
Eric Laurentf1f22e72021-07-13 14:04:14 +02001522 status_t status =
1523 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001524
1525 // only accept an output with the requested parameters
1526 if (status != NO_ERROR ||
1527 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1528 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1529 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1530 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1531 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1532 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1533 config->channel_mask, outputDesc->getChannelMask());
1534 if (*output != AUDIO_IO_HANDLE_NONE) {
1535 outputDesc->close();
1536 }
1537 // fall back to mixer output if possible when the direct output could not be open
1538 if (audio_is_linear_pcm(config->format) &&
1539 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1540 return NAME_NOT_FOUND;
1541 }
1542 *output = AUDIO_IO_HANDLE_NONE;
1543 return BAD_VALUE;
1544 }
1545 outputDesc->mDirectOpenCount = 1;
1546 outputDesc->mDirectClientSession = session;
1547
1548 addOutput(*output, outputDesc);
1549 mPreviousOutputs = mOutputs;
1550 ALOGV("%s returns new direct output %d", __func__, *output);
1551 mpClientInterface->onAudioPortListUpdate();
1552 return NO_ERROR;
1553}
1554
François Gaffie11d30102018-11-02 16:09:09 +01001555audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1556 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001557 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001558 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001559 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001560 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001561 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001562 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001563 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001564{
Andy Hungc88b0642018-04-27 15:42:35 -07001565 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001566
jiabine375d412019-02-26 12:54:53 -08001567 // Discard haptic channel mask when forcing muting haptic channels.
1568 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001569 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1570 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001571
Eric Laurente552edb2014-03-10 17:42:56 -07001572 // open a direct output if required by specified parameters
1573 //force direct flag if offload flag is set: offloading implies a direct output stream
1574 // and all common behaviors are driven by checking only the direct flag
1575 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001576 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1577 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001578 }
Nadav Bar766fb022018-01-07 12:18:03 +02001579 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1580 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001581 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001582
1583 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1584
Eric Laurente83b55d2014-11-14 10:06:21 -08001585 // only allow deep buffering for music stream type
1586 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001587 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001588 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001589 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001590 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1591 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001592 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001593 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001594 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001595 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001596 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001597 audio_is_linear_pcm(config->format) &&
1598 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001599 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001600 AUDIO_OUTPUT_FLAG_DIRECT);
1601 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001602 }
Eric Laurente552edb2014-03-10 17:42:56 -07001603
Carter Hsua3abb402021-10-26 11:11:20 +08001604 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1605 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1606 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1607 }
1608
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001609 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001610 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001611 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001612 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001613 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001614 }
1615
Eric Laurentc529cf62020-04-17 18:19:10 -07001616 audio_config_t directConfig = *config;
1617 directConfig.channel_mask = channelMask;
1618 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1619 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001620 return output;
1621 }
1622
Eric Laurent14cbfca2016-03-17 09:42:16 -07001623 // A request for HW A/V sync cannot fallback to a mixed output because time
1624 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001625 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001626 return AUDIO_IO_HANDLE_NONE;
1627 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001628 // A request for Tuner cannot fallback to a mixed output
1629 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1630 return AUDIO_IO_HANDLE_NONE;
1631 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001632
Eric Laurente552edb2014-03-10 17:42:56 -07001633 // ignoring channel mask due to downmix capability in mixer
1634
1635 // open a non direct output
1636
1637 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001638 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001639 // get which output is suitable for the specified stream. The actual
1640 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001641 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001642 if (prefMixerConfigInfo != nullptr) {
1643 for (audio_io_handle_t outputHandle : outputs) {
1644 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1645 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1646 output = outputHandle;
1647 break;
1648 }
1649 }
1650 if (output == AUDIO_IO_HANDLE_NONE) {
1651 // No output open with the preferred profile. Open a new one.
1652 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1653 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1654 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1655 config.format = prefMixerConfigInfo->getConfigBase().format;
1656 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1657 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1658 &config, prefMixerConfigInfo->getFlags());
1659 if (preferredOutput == nullptr) {
1660 ALOGE("%s failed to open output with preferred mixer config", __func__);
1661 } else {
1662 output = preferredOutput->mIoHandle;
1663 }
1664 }
1665 } else {
1666 // at this stage we should ignore the DIRECT flag as no direct output could be
1667 // found earlier
1668 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1669 output = selectOutput(
1670 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1671 }
Eric Laurente552edb2014-03-10 17:42:56 -07001672 }
François Gaffie11d30102018-11-02 16:09:09 +01001673 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001674 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001675 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001676
Eric Laurente552edb2014-03-10 17:42:56 -07001677 return output;
1678}
1679
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001680sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001681 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1682 mAvailableInputDevices);
1683 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1684}
1685
1686DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1687 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1688 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001689}
1690
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001691const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001692 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001693 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1694 if (msdModule != 0) {
1695 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1696 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1697 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1698 const struct audio_port_config *source = &patch->mPatch.sources[j];
1699 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1700 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001701 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001702 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001703 }
1704 }
1705 }
1706 return msdPatches;
1707}
1708
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001709bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1710 ssize_t index = mAudioPatches.indexOfKey(handle);
1711 if (index < 0) {
1712 return false;
1713 }
1714 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1715 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1716 if (msdModule == nullptr) {
1717 return false;
1718 }
1719 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1720 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1721 return true;
1722 }
1723 index = getMsdOutputPatches().indexOfKey(handle);
1724 if (index < 0) {
1725 return false;
1726 }
1727 return true;
1728}
1729
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001730status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1731 const InputProfileCollection &inputProfiles,
1732 const OutputProfileCollection &outputProfiles,
1733 const sp<DeviceDescriptor> &sourceDevice,
1734 const sp<DeviceDescriptor> &sinkDevice,
1735 AudioProfileVector& sourceProfiles,
1736 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001737 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001738 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001739 return NO_INIT;
1740 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001741 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001742 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001743 return NO_INIT;
1744 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001745 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001746 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1747 inProfile->supportsDevice(sourceDevice)) {
1748 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001749 }
1750 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001751 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001752 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001753 outProfile->supportsDevice(sinkDevice)) {
1754 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001755 }
1756 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001757 return NO_ERROR;
1758}
1759
1760status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1761 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1762 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1763{
Dean Wheatley16809da2022-12-09 14:55:46 +11001764 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1765 static const std::vector<audio_format_t> formatsOrder = {{
1766 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001767 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1768 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001769 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1770 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1771 // preferred).
1772 std::vector<audio_channel_mask_t> masks = {{
1773 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1774 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1775 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1776 // insert index masks (higher counts most preferred) as preferred over position masks
1777 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1778 masks.insert(
1779 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1780 }
1781 return masks;
1782 }();
1783
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001784 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001785 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1786 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001787 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001788 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1789 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001790 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001791 }
1792 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1793 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1794 sinkConfig->format = bestSinkConfig.format;
1795 // For encoded streams force direct flag to prevent downstream mixing.
1796 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1797 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001798 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1799 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001800 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001801 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1802 // raw and IEC61937 framed streams.
1803 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1804 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1805 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001806 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1807 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001808 sourceConfig->channel_mask =
1809 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1810 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1811 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001812 sourceConfig->format = bestSinkConfig.format;
1813 // Copy input stream directly without any processing (e.g. resampling).
1814 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1815 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1816 if (hwAvSync) {
1817 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1818 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1819 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1820 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1821 }
1822 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1823 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1824 sinkConfig->config_mask |= config_mask;
1825 sourceConfig->config_mask |= config_mask;
1826 return NO_ERROR;
1827}
1828
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001829PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1830 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001831{
1832 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001833 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1834 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1835 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1836 if (deviceModule == nullptr) {
1837 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1838 return patchBuilder;
1839 }
1840 const InputProfileCollection inputProfiles = msdIsSource ?
1841 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1842 const OutputProfileCollection outputProfiles = msdIsSource ?
1843 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1844
1845 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1846 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1847 device : getMsdAudioOutDevices().itemAt(0);
1848 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1849
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001850 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1851 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001852 AudioProfileVector sourceProfiles;
1853 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001854 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1855 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001856 for (auto hwAvSync : { true, false }) {
1857 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1858 sourceProfiles, sinkProfiles) != NO_ERROR) {
1859 continue;
1860 }
1861 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1862 &sinkConfig) == NO_ERROR) {
1863 // Found a matching config. Re-create PatchBuilder with this config.
1864 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1865 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001866 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001867 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001868 " supporting PCM format conversion.", __func__);
1869 return patchBuilder;
1870}
1871
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001872status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001873 DeviceVector devices;
1874 if (outputDevices != nullptr && outputDevices->size() > 0) {
1875 devices.add(*outputDevices);
1876 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001877 // Use media strategy for unspecified output device. This should only
1878 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1879 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001880 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001881 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001882 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001883 }
Michael Chan6fb34492020-12-08 15:44:49 +11001884 std::vector<PatchBuilder> patchesToCreate;
1885 for (auto i = 0u; i < devices.size(); ++i) {
1886 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001887 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001888 }
1889 // Retain only the MSD patches associated with outputDevices request.
1890 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001891 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001892 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1893 auto retainedPatch = false;
1894 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1895 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1896 patchesToRemove.removeItemsAt(i);
1897 retainedPatch = true;
1898 break;
1899 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001900 }
Michael Chan6fb34492020-12-08 15:44:49 +11001901 if (retainedPatch) {
1902 it = patchesToCreate.erase(it);
1903 continue;
1904 }
1905 ++it;
1906 }
1907 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1908 return NO_ERROR;
1909 }
1910 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1911 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001912 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001913 }
Michael Chan6fb34492020-12-08 15:44:49 +11001914 status_t status = NO_ERROR;
1915 for (const auto &p : patchesToCreate) {
1916 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1917 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1918 char message[256];
1919 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1920 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1921 currStatus == NO_ERROR ? "Success" : "Error",
1922 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1923 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1924 if (currStatus == NO_ERROR) {
1925 ALOGD("%s", message);
1926 } else {
1927 ALOGE("%s", message);
1928 if (status == NO_ERROR) {
1929 status = currStatus;
1930 }
1931 }
1932 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001933 return status;
1934}
1935
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001936void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1937 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001938 for (size_t i = 0; i < msdPatches.size(); i++) {
1939 const auto& patch = msdPatches[i];
1940 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1941 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1942 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1943 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1944 releaseAudioPatch(patch->getHandle(), mUidCached);
1945 break;
1946 }
1947 }
1948 }
1949}
1950
Dorin Drimus94d94412022-02-02 09:05:02 +01001951bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001952 DeviceVector devicesToCheck =
1953 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001954 AudioPatchCollection msdPatches = getMsdOutputPatches();
1955 for (size_t i = 0; i < msdPatches.size(); i++) {
1956 const auto& patch = msdPatches[i];
1957 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1958 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1959 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1960 const auto& foundDevice = devicesToCheck.getDevice(
1961 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1962 if (foundDevice != nullptr) {
1963 devicesToCheck.remove(foundDevice);
1964 if (devicesToCheck.isEmpty()) {
1965 return true;
1966 }
1967 }
1968 }
1969 }
1970 }
1971 return false;
1972}
1973
Eric Laurente0720872014-03-11 09:30:41 -07001974audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001975 audio_output_flags_t flags,
1976 audio_format_t format,
1977 audio_channel_mask_t channelMask,
1978 uint32_t samplingRate,
1979 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001980{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001981 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1982 "%s called with format %#x", __func__, format);
1983
jiabinebb6af42020-06-09 17:31:17 -07001984 // Return the output that haptic-generating attached to when 1) session id is specified,
1985 // 2) haptic-generating effect exists for given session id and 3) the output that
1986 // haptic-generating effect attached to is in given outputs.
1987 if (sessionId != AUDIO_SESSION_NONE) {
1988 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1989 sessionId, FX_IID_HAPTICGENERATOR);
1990 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1991 return hapticGeneratingOutput;
1992 }
1993 }
1994
Eric Laurent16c66dd2019-05-01 17:54:10 -07001995 // Flags disqualifying an output: the match must happen before calling selectOutput()
1996 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1997 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1998
1999 // Flags expressing a functional request: must be honored in priority over
2000 // other criteria
2001 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2002 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002003 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2004 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002005 // Flags expressing a performance request: have lower priority than serving
2006 // requested sampling rate or channel mask
2007 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2008 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2009 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2010
2011 const audio_output_flags_t functionalFlags =
2012 (audio_output_flags_t)(flags & kFunctionalFlags);
2013 const audio_output_flags_t performanceFlags =
2014 (audio_output_flags_t)(flags & kPerformanceFlags);
2015
2016 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2017
Eric Laurente552edb2014-03-10 17:42:56 -07002018 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002019 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002020 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002021 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002022 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002023 // with tiebreak preferring the minimum number of extra functional flags
2024 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002025 // 3: the output supporting the exact channel mask
2026 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002027 // 5: the output with the highest sampling rate if the requested sample rate is
2028 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002029 // 6: the output with the highest number of requested performance flags
2030 // 7: the output with the bit depth the closest to the requested one
2031 // 8: the primary output
2032 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002033
Eric Laurent16c66dd2019-05-01 17:54:10 -07002034 // matching criteria values in priority order for best matching output so far
2035 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002036
Eric Laurent16c66dd2019-05-01 17:54:10 -07002037 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2038 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2039 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002040
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002041 for (audio_io_handle_t output : outputs) {
2042 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002043 // matching criteria values in priority order for current output
2044 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002045
Eric Laurent16c66dd2019-05-01 17:54:10 -07002046 if (outputDesc->isDuplicated()) {
2047 continue;
2048 }
2049 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2050 continue;
2051 }
Eric Laurent8838a382014-09-08 16:44:28 -07002052
Eric Laurent16c66dd2019-05-01 17:54:10 -07002053 // If haptic channel is specified, use the haptic output if present.
2054 // When using haptic output, same audio format and sample rate are required.
2055 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002056 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002057 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2058 continue;
2059 }
2060 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002061 && format == outputDesc->getFormat()
2062 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002063 currentMatchCriteria[0] = outputHapticChannelCount;
2064 }
2065
2066 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002067 const int matchingFunctionalFlags =
2068 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2069 const int totalFunctionalFlags =
2070 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2071 // Prefer matching functional flags, but subtract unnecessary functional flags.
2072 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002073
2074 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002075 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2076 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002077 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2078 channelCount <= outputChannelCount) {
2079 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002080 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2081 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002082 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002083 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002084 currentMatchCriteria[3] = outputChannelCount;
2085 }
2086
2087 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002088 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002089 int diff; // avoid unsigned integer overflow.
2090 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2091
2092 // prefer the closest output sampling rate greater than or equal to target
2093 // if none exists, prefer the closest output sampling rate less than target.
2094 //
2095 // criteria is offset to make non-negative.
2096 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002097 }
2098
2099 // performance flags match
2100 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2101
2102 // format match
2103 if (format != AUDIO_FORMAT_INVALID) {
2104 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002105 PolicyAudioPort::kFormatDistanceMax -
2106 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002107 }
2108
2109 // primary output match
2110 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2111
2112 // compare match criteria by priority then value
2113 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2114 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2115 bestMatchCriteria = currentMatchCriteria;
2116 bestOutput = output;
2117
2118 std::stringstream result;
2119 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2120 std::ostream_iterator<int>(result, " "));
2121 ALOGV("%s new bestOutput %d criteria %s",
2122 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002123 }
2124 }
2125
Eric Laurent16c66dd2019-05-01 17:54:10 -07002126 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002127}
2128
Eric Laurent8fc147b2018-07-22 19:13:55 -07002129status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002130{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002131 ALOGV("%s portId %d", __FUNCTION__, portId);
2132
2133 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2134 if (outputDesc == 0) {
2135 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002136 return BAD_VALUE;
2137 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002138 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002139
Eric Laurent8fc147b2018-07-22 19:13:55 -07002140 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002141 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002142
Eric Laurent733ce942017-12-07 12:18:25 -08002143 status_t status = outputDesc->start();
2144 if (status != NO_ERROR) {
2145 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002146 }
2147
Eric Laurent97ac8712018-07-27 18:59:02 -07002148 uint32_t delayMs;
2149 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002150
2151 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002152 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002153 if (status == DEAD_OBJECT) {
2154 sp<SwAudioOutputDescriptor> desc =
2155 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2156 if (desc == nullptr) {
2157 // This is not common, it may indicate something wrong with the HAL.
2158 ALOGE("%s unable to open output with default config", __func__);
2159 return status;
2160 }
2161 desc->mUsePreferredMixerAttributes = true;
2162 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002163 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002164 }
jiabina84c3d32022-12-02 18:59:55 +00002165
2166 // If the client is the first one active on preferred mixer parameters, reopen the output
2167 // if the current mixer parameters doesn't match the preferred one.
2168 if (outputDesc->devices().size() == 1) {
2169 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2170 outputDesc->devices()[0]->getId(), client->strategy());
2171 if (info != nullptr && info->getUid() == client->uid()) {
2172 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2173 info->getConfigBase(), info->getFlags())) {
2174 stopSource(outputDesc, client);
2175 outputDesc->stop();
2176 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2177 config.channel_mask = info->getConfigBase().channel_mask;
2178 config.sample_rate = info->getConfigBase().sample_rate;
2179 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002180 sp<SwAudioOutputDescriptor> desc =
2181 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2182 if (desc == nullptr) {
2183 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002184 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002185 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002186 // Intentionally return error to let the client side resending request for
2187 // creating and starting.
2188 return DEAD_OBJECT;
2189 }
2190 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002191 if (info->getActiveClientCount() == 1 &&
2192 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2193 // If it is first bit-perfect client, reroute all clients that will be routed to
2194 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2195 PortHandleVector clientsToInvalidate;
2196 for (size_t i = 0; i < mOutputs.size(); i++) {
2197 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002198 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002199 continue;
2200 }
2201 for (const auto& c : mOutputs[i]->getClientIterable()) {
2202 clientsToInvalidate.push_back(c->portId());
2203 }
2204 }
2205 if (!clientsToInvalidate.empty()) {
2206 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2207 __func__);
2208 mpClientInterface->invalidateTracks(clientsToInvalidate);
2209 }
2210 }
jiabina84c3d32022-12-02 18:59:55 +00002211 }
2212 }
2213
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002214 if (client->hasPreferredDevice()) {
2215 // playback activity with preferred device impacts routing occurred, inform upper layers
2216 mpClientInterface->onRoutingUpdated();
2217 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002218 if (delayMs != 0) {
2219 usleep(delayMs * 1000);
2220 }
2221
2222 return status;
2223}
2224
Eric Laurent96d1dda2022-03-14 17:14:19 +01002225bool AudioPolicyManager::isLeUnicastActive() const {
2226 if (isInCall()) {
2227 return true;
2228 }
2229 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2230}
2231
2232bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2233 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2234 return false;
2235 }
2236 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2237 ALOGV("%s active %d", __func__, active);
2238 return active;
2239}
2240
Eric Laurent97ac8712018-07-27 18:59:02 -07002241status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2242 const sp<TrackClientDescriptor>& client,
2243 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002244{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002245 // cannot start playback of STREAM_TTS if any other output is being used
2246 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002247
2248 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002249 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002250 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002251 auto clientStrategy = client->strategy();
2252 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002253 if (stream == AUDIO_STREAM_TTS) {
2254 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002255 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002256 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002257 return INVALID_OPERATION;
2258 } else {
2259 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2260 }
2261 } else {
2262 // some playback other than beacon starts
2263 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2264 }
2265
Eric Laurent77305a62016-07-25 16:39:22 -07002266 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002267 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002268 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002269
François Gaffie11d30102018-11-02 16:09:09 +01002270 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002271 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002272 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002273 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002274 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002275 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002276 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002277 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002278 } else {
2279 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002280 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002281 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2282 AUDIO_FORMAT_DEFAULT);
2283 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2284 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002285 }
2286
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002287 // requiresMuteCheck is false when we can bypass mute strategy.
2288 // It covers a common case when there is no materially active audio
2289 // and muting would result in unnecessary delay and dropped audio.
2290 const uint32_t outputLatencyMs = outputDesc->latency();
2291 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002292 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002293
Eric Laurente552edb2014-03-10 17:42:56 -07002294 // increment usage count for this stream on the requested output:
2295 // NOTE that the usage count is the same for duplicated output and hardware output which is
2296 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002297 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002298
2299 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002300 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002301 // Preferred device may be exclusive, use only if no other active clients on this output
2302 devices = DeviceVector(
2303 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2304 } else {
2305 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2306 }
François Gaffie11d30102018-11-02 16:09:09 +01002307 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002308 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002309 }
2310 }
Eric Laurente552edb2014-03-10 17:42:56 -07002311
François Gaffiec005e562018-11-06 15:04:49 +01002312 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002313 selectOutputForMusicEffects();
2314 }
2315
François Gaffie1c878552018-11-22 16:53:21 +01002316 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002317 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002318 if (devices.isEmpty()) {
2319 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002320 }
François Gaffiec005e562018-11-06 15:04:49 +01002321 bool shouldWait =
2322 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2323 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2324 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002325 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002326 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002327 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002328 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002329 // An output has a shared device if
2330 // - managed by the same hw module
2331 // - supports the currently selected device
2332 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002333 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002334
Eric Laurent77305a62016-07-25 16:39:22 -07002335 // force a device change if any other output is:
2336 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002337 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002338 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002339 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002340 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002341 // change the device currently selected by the other output.
2342 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002343 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002344 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002345 force = true;
2346 }
2347 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002348 // a notification so that audio focus effect can propagate, or that a mute/unmute
2349 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002350 const uint32_t latencyMs = desc->latency();
2351 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2352
2353 if (shouldWait && isActive && (waitMs < latencyMs)) {
2354 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002355 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002356
2357 // Require mute check if another output is on a shared device
2358 // and currently active to have proper drain and avoid pops.
2359 // Note restoring AudioTracks onto this output needs to invoke
2360 // a volume ramp if there is no mute.
2361 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002362 }
2363 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002364
jiabin3ff8d7d2022-12-13 06:27:44 +00002365 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2366 // If the output is open with preferred mixer attributes, but the routed device is
2367 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2368 // changed.
2369 return DEAD_OBJECT;
2370 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002371 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302372 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2373 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002374
Eric Laurente552edb2014-03-10 17:42:56 -07002375 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002376 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002377 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002378 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002379 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002380 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002381 outputDesc->useHwGain() /*force*/)) {
2382 // request AudioService to reinitialize the volume curves asynchronously
2383 ALOGE("checkAndSetVolume failed, requesting volume range init");
2384 mpClientInterface->onVolumeRangeInitRequest();
2385 };
Eric Laurente552edb2014-03-10 17:42:56 -07002386
2387 // update the outputs if starting an output with a stream that can affect notification
2388 // routing
2389 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002390
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002391 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002392 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002393 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002394 }
Eric Laurentdc462862016-07-19 12:29:53 -07002395
2396 if (waitMs > muteWaitMs) {
2397 *delayMs = waitMs - muteWaitMs;
2398 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002399
2400 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2401 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2402 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2403 // change occurs after the MixerThread starts and causes a stream volume
2404 // glitch.
2405 //
2406 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002407 }
Eric Laurentdc462862016-07-19 12:29:53 -07002408
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002409 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002410 mEngine->getForceUse(
2411 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002412 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002413 }
2414
Eric Laurent97ac8712018-07-27 18:59:02 -07002415 // Automatically enable the remote submix input when output is started on a re routing mix
2416 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002417 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2418 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002419 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2420 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2421 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002422 "remote-submix",
2423 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002424 }
2425
Eric Laurent96d1dda2022-03-14 17:14:19 +01002426 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2427
Eric Laurente552edb2014-03-10 17:42:56 -07002428 return NO_ERROR;
2429}
2430
Eric Laurent96d1dda2022-03-14 17:14:19 +01002431void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2432 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2433 bool isUnicastActive = isLeUnicastActive();
2434
2435 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002436 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002437 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2438 for (size_t i = 0; i < mOutputs.size(); i++) {
2439 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2440 if (desc != ignoredOutput && desc->isActive()
2441 && ((isUnicastActive &&
2442 !desc->devices().
2443 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2444 || (wasUnicastActive &&
2445 !desc->devices().getDevicesFromTypes(
2446 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2447 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2448 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002449 if (desc->mUsePreferredMixerAttributes && force) {
2450 // If the device is using preferred mixer attributes, the output need to reopen
2451 // with default configuration when the new selected devices are different from
2452 // current routing devices.
2453 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2454 continue;
2455 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302456 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002457 // re-apply device specific volume if not done by setOutputDevice()
2458 if (!force) {
2459 applyStreamVolumes(desc, newDevices.types(), delayMs);
2460 }
2461 }
2462 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002463 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002464 }
2465}
2466
Eric Laurent8fc147b2018-07-22 19:13:55 -07002467status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002468{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002469 ALOGV("%s portId %d", __FUNCTION__, portId);
2470
2471 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2472 if (outputDesc == 0) {
2473 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002474 return BAD_VALUE;
2475 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002476 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002477
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002478 if (client->hasPreferredDevice(true)) {
2479 // playback activity with preferred device impacts routing occurred, inform upper layers
2480 mpClientInterface->onRoutingUpdated();
2481 }
2482
Eric Laurent97ac8712018-07-27 18:59:02 -07002483 ALOGV("stopOutput() output %d, stream %d, session %d",
2484 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002485
Eric Laurent97ac8712018-07-27 18:59:02 -07002486 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002487
Eric Laurent733ce942017-12-07 12:18:25 -08002488 if (status == NO_ERROR ) {
2489 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002490 } else {
2491 return status;
2492 }
2493
2494 if (outputDesc->devices().size() == 1) {
2495 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2496 outputDesc->devices()[0]->getId(), client->strategy());
2497 if (info != nullptr && info->getUid() == client->uid()) {
2498 info->decreaseActiveClient();
2499 if (info->getActiveClientCount() == 0) {
2500 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2501 }
2502 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002503 }
2504 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002505}
2506
Eric Laurent97ac8712018-07-27 18:59:02 -07002507status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2508 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002509{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002510 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002511 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002512 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002513 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002514
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002515 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2516
François Gaffie1c878552018-11-22 16:53:21 +01002517 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2518 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002519 // Automatically disable the remote submix input when output is stopped on a
2520 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002521 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002522 if (isSingleDeviceType(
2523 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002524 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002525 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002526 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2527 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002528 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002529 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002530 }
2531 }
2532 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002533 if (client->hasPreferredDevice(true) &&
2534 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002535 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002536 forceDeviceUpdate = true;
2537 }
2538
Eric Laurente552edb2014-03-10 17:42:56 -07002539 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002540 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002541
Eric Laurente552edb2014-03-10 17:42:56 -07002542 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002543 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002544 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002545 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002546
2547 // If the routing does not change, if an output is routed on a device using HwGain
2548 // (aka setAudioPortConfig) and there are still active clients following different
2549 // volume group(s), force reapply volume
2550 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2551 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2552
Eric Laurente552edb2014-03-10 17:42:56 -07002553 // delay the device switch by twice the latency because stopOutput() is executed when
2554 // the track stop() command is received and at that time the audio track buffer can
2555 // still contain data that needs to be drained. The latency only covers the audio HAL
2556 // and kernel buffers. Also the latency does not always include additional delay in the
2557 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302558 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002559 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002560
2561 // force restoring the device selection on other active outputs if it differs from the
2562 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002563 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002564 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002565 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002566 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002567 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002568 desc->isActive() &&
2569 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002570 (newDevices != desc->devices())) {
2571 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2572 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002573
jiabin3ff8d7d2022-12-13 06:27:44 +00002574 if (desc->mUsePreferredMixerAttributes && force) {
2575 // If the device is using preferred mixer attributes, the output need to
2576 // reopen with default configuration when the new selected devices are
2577 // different from current routing devices.
2578 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2579 continue;
2580 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302581 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002582
Eric Laurent57de36c2016-09-28 16:59:11 -07002583 // re-apply device specific volume if not done by setOutputDevice()
2584 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002585 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002586 }
Eric Laurente552edb2014-03-10 17:42:56 -07002587 }
2588 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002589 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002590 // update the outputs if stopping one with a stream that can affect notification routing
2591 handleNotificationRoutingForStream(stream);
2592 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002593
2594 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2595 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002596 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002597 }
2598
François Gaffiec005e562018-11-06 15:04:49 +01002599 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002600 selectOutputForMusicEffects();
2601 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002602
2603 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2604
Eric Laurente552edb2014-03-10 17:42:56 -07002605 return NO_ERROR;
2606 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002607 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002608 return INVALID_OPERATION;
2609 }
2610}
2611
jiabinbce0c1d2020-10-05 11:20:18 -07002612bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002613{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002614 ALOGV("%s portId %d", __FUNCTION__, portId);
2615
2616 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2617 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002618 // If an output descriptor is closed due to a device routing change,
2619 // then there are race conditions with releaseOutput from tracks
2620 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2621 // destroyed shortly thereafter.
2622 //
2623 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002624 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002625 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002626 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002627
2628 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002629
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302630 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2631 if (outputDesc->isClientActive(client)) {
2632 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2633 stopOutput(portId);
2634 }
2635
Eric Laurent8fc147b2018-07-22 19:13:55 -07002636 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2637 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002638 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002639 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002640 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002641 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002642 if (--outputDesc->mDirectOpenCount == 0) {
2643 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002644 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002645 }
2646 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302647
Andy Hung39efb7a2018-09-26 15:39:28 -07002648 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002649 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2650 // The output is pending reopened to query dynamic profiles and
2651 // there is no active clients
2652 closeOutput(outputDesc->mIoHandle);
2653 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2654 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2655 if (newOutputDesc == nullptr) {
2656 ALOGE("%s failed to open output", __func__);
2657 }
2658 return true;
2659 }
2660 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002661}
2662
Eric Laurentcaf7f482014-11-25 17:50:47 -08002663status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2664 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002665 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002666 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002667 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002668 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002669 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002670 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002671 input_type_t *inputType,
2672 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002673{
François Gaffiec005e562018-11-06 15:04:49 +01002674 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002675 "flags %#x attributes=%s requested device ID %d",
2676 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2677 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002678
Eric Laurentad2e7b92017-09-14 20:06:42 -07002679 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002680 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002681 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002682 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002683 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002684 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002685 sp<RecordClientDescriptor> clientDesc;
2686 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002687 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002688 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002689
2690 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2691 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2692 return INVALID_OPERATION;
2693 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002694
Francois Gaffie716e1432019-01-14 16:58:59 +01002695 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2696 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002697 }
2698
Paul McLean466dc8e2015-04-17 13:15:36 -06002699 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002700 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002701 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002702
Eric Laurentad2e7b92017-09-14 20:06:42 -07002703 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2704 // possible
2705 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2706 *input != AUDIO_IO_HANDLE_NONE) {
2707 ssize_t index = mInputs.indexOfKey(*input);
2708 if (index < 0) {
2709 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2710 status = BAD_VALUE;
2711 goto error;
2712 }
2713 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002714 RecordClientVector clients = inputDesc->getClientsForSession(session);
2715 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002716 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2717 status = BAD_VALUE;
2718 goto error;
2719 }
2720 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2721 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002722 // corresponds to a new client and is only permitted from the same UID.
2723 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002724 if (clients.size() > 1) {
2725 for (const auto& client : clients) {
2726 // The client map is ordered by key values (portId) and portIds are allocated
2727 // incrementaly. So the first client in this list is the one opened by audio flinger
2728 // when the mmap stream is created and should be ignored as it does not correspond
2729 // to an actual client
2730 if (client == *clients.cbegin()) {
2731 continue;
2732 }
2733 if (uid != client->uid() && !client->isSilenced()) {
2734 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2735 uid, client->portId(), client->uid());
2736 status = INVALID_OPERATION;
2737 goto error;
2738 }
Eric Laurent331679c2018-04-16 17:03:16 -07002739 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002740 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002741 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002742 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002743
Eric Laurentfecbceb2021-02-09 14:46:43 +01002744 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002745 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002746 }
2747
2748 *input = AUDIO_IO_HANDLE_NONE;
2749 *inputType = API_INPUT_INVALID;
2750
Francois Gaffie716e1432019-01-14 16:58:59 +01002751 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002752 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002753 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002754 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002755 ALOGW("%s could not find input mix for attr %s",
2756 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002757 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002758 }
jiabinc1de2df2019-05-07 14:26:40 -07002759 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2760 String8(attr->tags + strlen("addr=")),
2761 AUDIO_FORMAT_DEFAULT);
2762 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002763 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002764 __func__, attributes.source, attributes.tags);
2765 status = BAD_VALUE;
2766 goto error;
2767 }
2768
Kevin Rocard25f9b052019-02-27 15:08:54 -08002769 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2770 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2771 } else {
2772 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2773 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002774 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002775 if (explicitRoutingDevice != nullptr) {
2776 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002777 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002778 // Prevent from storing invalid requested device id in clients
2779 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002780 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002781 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2782 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002783 }
François Gaffie11d30102018-11-02 16:09:09 +01002784 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002785 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002786 status = BAD_VALUE;
2787 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002788 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002789 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2790 *inputType = API_INPUT_MIX_CAPTURE;
2791 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002792 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2793 // there is an external policy, but this input is attached to a mix of recorders,
2794 // meaning it receives audio injected into the framework, so the recorder doesn't
2795 // know about it and is therefore considered "legacy"
2796 *inputType = API_INPUT_LEGACY;
2797 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002798 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002799 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002800 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002801 } else {
2802 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002803 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002804
Eric Laurent599c7582015-12-07 18:05:55 -08002805 }
2806
François Gaffiec005e562018-11-06 15:04:49 +01002807 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002808 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002809 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002810 AudioProfileVector profiles;
2811 status_t ret = getProfilesForDevices(
2812 DeviceVector(device), profiles, flags, true /*isInput*/);
2813 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002814 const auto channels = profiles[0]->getChannels();
2815 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2816 config->channel_mask = *channels.begin();
2817 }
2818 const auto sampleRates = profiles[0]->getSampleRates();
2819 if (!sampleRates.empty() &&
2820 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2821 config->sample_rate = *sampleRates.begin();
2822 }
jiabinf1c73972022-04-14 16:28:52 -07002823 config->format = profiles[0]->getFormat();
2824 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002825 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002826 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002827
Eric Laurent8f42ea12018-08-08 09:08:25 -07002828exit:
2829
François Gaffiec005e562018-11-06 15:04:49 +01002830 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2831 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002832
Francois Gaffie716e1432019-01-14 16:58:59 +01002833 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002834 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002835 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002836
Mikhail Naganov2996f672019-04-18 12:29:59 -07002837 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002838 requestedDeviceId, attributes.source, flags,
2839 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002840 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002841 // Move (if found) effect for the client session to its input
2842 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002843 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002844
2845 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2846 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002847
Eric Laurent599c7582015-12-07 18:05:55 -08002848 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002849
2850error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002851 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002852}
2853
2854
François Gaffie11d30102018-11-02 16:09:09 +01002855audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002856 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002857 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002858 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002859 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002860 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002861{
2862 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002863 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002864 bool isSoundTrigger = false;
2865
François Gaffiec005e562018-11-06 15:04:49 +01002866 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002867 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2868 if (index >= 0) {
2869 input = mSoundTriggerSessions.valueFor(session);
2870 isSoundTrigger = true;
2871 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2872 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2873 } else {
2874 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002875 }
François Gaffiec005e562018-11-06 15:04:49 +01002876 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002877 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002878 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002879 }
2880
Carter Hsua3abb402021-10-26 11:11:20 +08002881 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2882 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2883 }
2884
Eric Laurentfe231122017-11-17 17:48:06 -08002885 // sampling rate and flags may be updated by getInputProfile
2886 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2887 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002888 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002889 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002890 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002891 // find a compatible input profile (not necessarily identical in parameters)
2892 sp<IOProfile> profile = getInputProfile(
2893 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2894 if (profile == nullptr) {
2895 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002896 }
jiabin2fd710d2022-05-02 23:20:22 +00002897
Glenn Kasten05ddca52016-02-11 08:17:12 -08002898 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002899 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002900 if (samplingRate == 0) {
2901 samplingRate = profileSamplingRate;
2902 }
Eric Laurente552edb2014-03-10 17:42:56 -07002903
Eric Laurent322b4d22015-04-03 15:57:54 -07002904 if (profile->getModuleHandle() == 0) {
2905 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002906 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002907 }
2908
Eric Laurentec376dc2021-04-08 20:41:22 +02002909 // Reuse an already opened input if a client with the same session ID already exists
2910 // on that input
2911 for (size_t i = 0; i < mInputs.size(); i++) {
2912 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2913 if (desc->mProfile != profile) {
2914 continue;
2915 }
2916 RecordClientVector clients = desc->clientsList();
2917 for (const auto &client : clients) {
2918 if (session == client->session()) {
2919 return desc->mIoHandle;
2920 }
2921 }
2922 }
2923
Eric Laurent3974e3b2017-12-07 17:58:43 -08002924 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002925 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002926 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002927 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002928 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002929 continue;
2930 }
2931 // if sound trigger, reuse input if used by other sound trigger on same session
2932 // else
2933 // reuse input if active client app is not in IDLE state
2934 //
2935 RecordClientVector clients = desc->clientsList();
2936 bool doClose = false;
2937 for (const auto& client : clients) {
2938 if (isSoundTrigger != client->isSoundTrigger()) {
2939 continue;
2940 }
2941 if (client->isSoundTrigger()) {
2942 if (session == client->session()) {
2943 return desc->mIoHandle;
2944 }
2945 continue;
2946 }
2947 if (client->active() && client->appState() != APP_STATE_IDLE) {
2948 return desc->mIoHandle;
2949 }
2950 doClose = true;
2951 }
2952 if (doClose) {
2953 closeInput(desc->mIoHandle);
2954 } else {
2955 i++;
2956 }
2957 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002958 }
2959
Eric Laurentfe231122017-11-17 17:48:06 -08002960 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002961
Eric Laurentfe231122017-11-17 17:48:06 -08002962 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2963 lConfig.sample_rate = profileSamplingRate;
2964 lConfig.channel_mask = profileChannelMask;
2965 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002966
François Gaffie11d30102018-11-02 16:09:09 +01002967 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002968
2969 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002970 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002971 (profileSamplingRate != lConfig.sample_rate) ||
2972 !audio_formats_match(profileFormat, lConfig.format) ||
2973 (profileChannelMask != lConfig.channel_mask)) {
2974 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002975 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002976 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002977 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002978 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002979 }
Eric Laurent599c7582015-12-07 18:05:55 -08002980 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002981 }
2982
Eric Laurentc722f302014-12-10 11:21:49 -08002983 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002984
Eric Laurent599c7582015-12-07 18:05:55 -08002985 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002986 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002987
Eric Laurent599c7582015-12-07 18:05:55 -08002988 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002989}
2990
Eric Laurent4eb58f12018-12-07 16:41:02 -08002991status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002992{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002993 ALOGV("%s portId %d", __FUNCTION__, portId);
2994
2995 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2996 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002997 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002998 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002999 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003000 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003001 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003002 if (client->active()) {
3003 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3004 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003005 }
3006
Eric Laurent8f42ea12018-08-08 09:08:25 -07003007 audio_session_t session = client->session();
3008
Eric Laurent4eb58f12018-12-07 16:41:02 -08003009 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003010
Eric Laurent4eb58f12018-12-07 16:41:02 -08003011 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003012
Eric Laurent4eb58f12018-12-07 16:41:02 -08003013 status_t status = inputDesc->start();
3014 if (status != NO_ERROR) {
3015 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003016 }
Eric Laurente552edb2014-03-10 17:42:56 -07003017
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003018 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003019 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003020 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003021
Eric Laurent8f42ea12018-08-08 09:08:25 -07003022 // indicate active capture to sound trigger service if starting capture from a mic on
3023 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003024 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003025 if (device != nullptr) {
3026 status = setInputDevice(input, device, true /* force */);
3027 } else {
3028 ALOGW("%s no new input device can be found for descriptor %d",
3029 __FUNCTION__, inputDesc->getId());
3030 status = BAD_VALUE;
3031 }
Eric Laurente552edb2014-03-10 17:42:56 -07003032
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003033 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003034 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003035 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003036 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003037 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3038 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003039 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003040 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003041
François Gaffie11d30102018-11-02 16:09:09 +01003042 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3043 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003044 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003045 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003046 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003047
Eric Laurent8f42ea12018-08-08 09:08:25 -07003048 // automatically enable the remote submix output when input is started if not
3049 // used by a policy mix of type MIX_TYPE_RECORDERS
3050 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003051 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003052 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003053 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003054 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003055 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3056 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003057 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003058 if (address != "") {
3059 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3060 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003061 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003062 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003063 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003064 } else if (status != NO_ERROR) {
3065 // Restore client activity state.
3066 inputDesc->setClientActive(client, false);
3067 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003068 }
3069
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003070 ALOGV("%s input %d source = %d status = %d exit",
3071 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003072
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003073 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003074}
3075
Eric Laurent8fc147b2018-07-22 19:13:55 -07003076status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003077{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003078 ALOGV("%s portId %d", __FUNCTION__, portId);
3079
3080 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3081 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003082 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003083 return BAD_VALUE;
3084 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003085 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003086 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003087 if (!client->active()) {
3088 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003089 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003090 }
Carter Hsue6139d52021-07-08 10:30:20 +08003091 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003092 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003093
Eric Laurent8f42ea12018-08-08 09:08:25 -07003094 inputDesc->stop();
3095 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003096 auto current_source = inputDesc->source();
3097 setInputDevice(input, getNewInputDevice(inputDesc),
3098 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003099 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003100 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003101 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003102 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003103 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3104 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003105 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003106 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003107
3108 // automatically disable the remote submix output when input is stopped if not
3109 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003110 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003111 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003112 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003113 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003114 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3115 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003116 }
3117 if (address != "") {
3118 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3119 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003120 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003121 }
3122 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003123 resetInputDevice(input);
3124
3125 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3126 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003127 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3128 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003129 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003130 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003131 }
3132 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003133 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003134 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003135}
3136
Eric Laurent8fc147b2018-07-22 19:13:55 -07003137void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003138{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003139 ALOGV("%s portId %d", __FUNCTION__, portId);
3140
3141 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3142 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003143 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003144 return;
3145 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003146 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003147 audio_io_handle_t input = inputDesc->mIoHandle;
3148
Eric Laurent8f42ea12018-08-08 09:08:25 -07003149 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003150
Andy Hung39efb7a2018-09-26 15:39:28 -07003151 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003152 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003153 if (inputDesc->getClientCount() > 0) {
3154 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003155 return;
3156 }
3157
Eric Laurent05b90f82014-08-27 15:32:29 -07003158 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003159 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003160 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003161}
3162
Eric Laurent8f42ea12018-08-08 09:08:25 -07003163void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003164{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003165 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003166
3167 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003168 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003169 }
3170}
3171
Eric Laurent8f42ea12018-08-08 09:08:25 -07003172void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3173{
3174 stopInput(portId);
3175 releaseInput(portId);
3176}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003177
Eric Laurent0dd51852019-04-19 18:18:58 -07003178void AudioPolicyManager::checkCloseInputs() {
3179 // After connecting or disconnecting an input device, close input if:
3180 // - it has no client (was just opened to check profile) OR
3181 // - none of its supported devices are connected anymore OR
3182 // - one of its clients cannot be routed to one of its supported
3183 // devices anymore. Otherwise update device selection
3184 std::vector<audio_io_handle_t> inputsToClose;
3185 for (size_t i = 0; i < mInputs.size(); i++) {
3186 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3187 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003188 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003189 inputsToClose.push_back(mInputs.keyAt(i));
3190 } else {
3191 bool close = false;
3192 for (const auto& client : input->clientsList()) {
3193 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003194 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3195 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003196 if (!input->supportedDevices().contains(device)) {
3197 close = true;
3198 break;
3199 }
3200 }
3201 if (close) {
3202 inputsToClose.push_back(mInputs.keyAt(i));
3203 } else {
3204 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3205 }
3206 }
3207 }
3208
3209 for (const audio_io_handle_t handle : inputsToClose) {
3210 ALOGV("%s closing input %d", __func__, handle);
3211 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003212 }
Eric Laurentd4692962014-05-05 18:13:44 -07003213}
3214
François Gaffie251c7f02018-11-07 10:41:08 +01003215void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003216{
3217 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003218 if (indexMin < 0 || indexMax < 0) {
3219 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3220 return;
3221 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003222 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003223
3224 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003225 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3226 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003227 continue;
3228 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003229 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003230 }
Eric Laurente552edb2014-03-10 17:42:56 -07003231}
3232
Eric Laurente0720872014-03-11 09:30:41 -07003233status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003234 int index,
3235 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003236{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003237 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003238 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3239 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3240 return NO_ERROR;
3241 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003242 ALOGV("%s: stream %s attributes=%s", __func__,
3243 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003244 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003245}
3246
Eric Laurente0720872014-03-11 09:30:41 -07003247status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003248 int *index,
3249 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003250{
François Gaffiec005e562018-11-06 15:04:49 +01003251 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3252 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003253 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003254 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003255 deviceTypes = mEngine->getOutputDevicesForStream(
3256 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003257 }
jiabin9a3361e2019-10-01 09:38:30 -07003258 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003259}
3260
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003261status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003262 int index,
3263 audio_devices_t device)
3264{
3265 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003266 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3267 if (group == VOLUME_GROUP_NONE) {
3268 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003269 return BAD_VALUE;
3270 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003271 ALOGV("%s: group %d matching with %s index %d",
3272 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003273 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003274 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003275 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003276 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3277 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3278 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3279 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003280 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3281
3282 status = setVolumeCurveIndex(index, device, curves);
3283 if (status != NO_ERROR) {
3284 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3285 return status;
3286 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003287
jiabin9a3361e2019-10-01 09:38:30 -07003288 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003289 auto curCurvAttrs = curves.getAttributes();
3290 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3291 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003292 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003293 } else if (!curves.getStreamTypes().empty()) {
3294 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003295 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003296 } else {
3297 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3298 return BAD_VALUE;
3299 }
jiabin9a3361e2019-10-01 09:38:30 -07003300 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3301 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003302
François Gaffiecfe17322018-11-07 13:41:29 +01003303 // update volume on all outputs and streams matching the following:
3304 // - The requested stream (or a stream matching for volume control) is active on the output
3305 // - The device (or devices) selected by the engine for this stream includes
3306 // the requested device
3307 // - For non default requested device, currently selected device on the output is either the
3308 // requested device or one of the devices selected by the engine for this stream
3309 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3310 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003311 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003312 for (size_t i = 0; i < mOutputs.size(); i++) {
3313 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003314 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003315
jiabin9a3361e2019-10-01 09:38:30 -07003316 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3317 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003318 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003319
3320 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003321 continue;
3322 }
3323 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3324 curDevices.find(device) == curDevices.end()) {
3325 continue;
3326 }
3327 bool applyVolume = false;
3328 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3329 curSrcDevices.insert(device);
3330 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003331 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3332 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003333 } else {
3334 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3335 }
3336 if (!applyVolume) {
3337 continue; // next output
3338 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003339 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3340 // If a higher priority strategy is active, and the output is routed to a device with a
3341 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003342 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003343 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003344 // If the volume source is active with higher priority source, ensure at least Sw Muted
3345 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003346 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3347 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3348 false /*preferredDevice*/);
3349 if (activeClients.empty()) {
3350 continue;
3351 }
3352 bool isPreempted = false;
3353 bool isHigherPriority = productStrategy < strategy;
3354 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003355 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003356 ALOGV("%s: Strategy=%d (\nrequester:\n"
3357 " group %d, volumeGroup=%d attributes=%s)\n"
3358 " higher priority source active:\n"
3359 " volumeGroup=%d attributes=%s) \n"
3360 " on output %zu, bailing out", __func__, productStrategy,
3361 group, group, toString(attributes).c_str(),
3362 client->volumeSource(), toString(client->attributes()).c_str(), i);
3363 applyVolume = false;
3364 isPreempted = true;
3365 break;
3366 }
3367 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003368 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003369 applyVolume = true;
3370 }
3371 }
3372 if (isPreempted || applyVolume) {
3373 break;
3374 }
3375 }
3376 if (!applyVolume) {
3377 continue; // next output
3378 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003379 }
François Gaffieed91f582020-01-31 10:35:37 +01003380 //FIXME: workaround for truncated touch sounds
3381 // delayed volume change for system stream to be removed when the problem is
3382 // handled by system UI
3383 status_t volStatus = checkAndSetVolume(
3384 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003385 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003386 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3387 if (volStatus != NO_ERROR) {
3388 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003389 }
3390 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003391
3392 // update voice volume if the an active call route exists
3393 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3394 && (curSrcDevices.find(
3395 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3396 != curSrcDevices.end())) {
3397 bool isVoiceVolSrc;
3398 bool isBtScoVolSrc;
3399 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3400 isVoiceVolSrc, isBtScoVolSrc, __func__)
3401 && (isVoiceVolSrc || isBtScoVolSrc)) {
3402 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3403 }
3404 }
3405
François Gaffiecfe17322018-11-07 13:41:29 +01003406 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3407 return status;
3408}
3409
François Gaffieaaac0fd2018-11-22 17:56:39 +01003410status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003411 audio_devices_t device,
3412 IVolumeCurves &volumeCurves)
3413{
3414 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3415 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003416 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3417 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003418 (index > volumeCurves.getVolumeIndexMax())) {
3419 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3420 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3421 return BAD_VALUE;
3422 }
3423 if (!audio_is_output_device(device)) {
3424 return BAD_VALUE;
3425 }
3426
3427 // Force max volume if stream cannot be muted
3428 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3429
François Gaffieaaac0fd2018-11-22 17:56:39 +01003430 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003431 volumeCurves.addCurrentVolumeIndex(device, index);
3432 return NO_ERROR;
3433}
3434
3435status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3436 int &index,
3437 audio_devices_t device)
3438{
3439 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3440 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003441 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003442 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003443 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003444 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003445 }
jiabin9a3361e2019-10-01 09:38:30 -07003446 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003447}
3448
3449status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3450 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003451 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003452{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003453 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003454 return BAD_VALUE;
3455 }
jiabin9a3361e2019-10-01 09:38:30 -07003456 index = curves.getVolumeIndex(deviceTypes);
3457 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003458 return NO_ERROR;
3459}
3460
3461status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3462 int &index)
3463{
3464 index = getVolumeCurves(attr).getVolumeIndexMin();
3465 return NO_ERROR;
3466}
3467
3468status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3469 int &index)
3470{
3471 index = getVolumeCurves(attr).getVolumeIndexMax();
3472 return NO_ERROR;
3473}
3474
Eric Laurent36829f92017-04-07 19:04:42 -07003475audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003476{
3477 // select one output among several suitable for global effects.
3478 // The priority is as follows:
3479 // 1: An offloaded output. If the effect ends up not being offloadable,
3480 // AudioFlinger will invalidate the track and the offloaded output
3481 // will be closed causing the effect to be moved to a PCM output.
3482 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003483 // 3: The primary output
3484 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003485
François Gaffiec005e562018-11-06 15:04:49 +01003486 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3487 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003488 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003489
Eric Laurent36829f92017-04-07 19:04:42 -07003490 if (outputs.size() == 0) {
3491 return AUDIO_IO_HANDLE_NONE;
3492 }
Eric Laurente552edb2014-03-10 17:42:56 -07003493
Eric Laurent36829f92017-04-07 19:04:42 -07003494 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3495 bool activeOnly = true;
3496
3497 while (output == AUDIO_IO_HANDLE_NONE) {
3498 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3499 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3500 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3501
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003502 for (audio_io_handle_t output : outputs) {
3503 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003504 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003505 continue;
3506 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003507 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3508 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003509 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003510 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003511 }
3512 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003513 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003514 }
3515 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003516 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003517 }
3518 }
3519 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3520 output = outputOffloaded;
3521 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3522 output = outputDeepBuffer;
3523 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3524 output = outputPrimary;
3525 } else {
3526 output = outputs[0];
3527 }
3528 activeOnly = false;
3529 }
3530
3531 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003532 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3533 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003534 mMusicEffectOutput = output;
3535 }
3536
3537 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003538 return output;
3539}
3540
Eric Laurent36829f92017-04-07 19:04:42 -07003541audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3542{
3543 return selectOutputForMusicEffects();
3544}
3545
Eric Laurente0720872014-03-11 09:30:41 -07003546status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003547 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003548 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003549 int session,
3550 int id)
3551{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003552 if (session != AUDIO_SESSION_DEVICE) {
3553 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003554 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003555 index = mInputs.indexOfKey(io);
3556 if (index < 0) {
3557 ALOGW("registerEffect() unknown io %d", io);
3558 return INVALID_OPERATION;
3559 }
Eric Laurente552edb2014-03-10 17:42:56 -07003560 }
3561 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003562 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3563 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3564 || strategy == PRODUCT_STRATEGY_NONE));
3565 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003566}
3567
Eric Laurentc241b0d2018-11-28 09:08:49 -08003568status_t AudioPolicyManager::unregisterEffect(int id)
3569{
3570 if (mEffects.getEffect(id) == nullptr) {
3571 return INVALID_OPERATION;
3572 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003573 if (mEffects.isEffectEnabled(id)) {
3574 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3575 setEffectEnabled(id, false);
3576 }
3577 return mEffects.unregisterEffect(id);
3578}
3579
3580status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3581{
3582 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3583 if (effect == nullptr) {
3584 return INVALID_OPERATION;
3585 }
3586
3587 status_t status = mEffects.setEffectEnabled(id, enabled);
3588 if (status == NO_ERROR) {
3589 mInputs.trackEffectEnabled(effect, enabled);
3590 }
3591 return status;
3592}
3593
Eric Laurent6c796322019-04-09 14:13:17 -07003594
3595status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3596{
3597 mEffects.moveEffects(ids, io);
3598 return NO_ERROR;
3599}
3600
Eric Laurentc75307b2015-03-17 15:29:32 -07003601bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3602{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003603 auto vs = toVolumeSource(stream, false);
3604 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003605}
3606
3607bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3608{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003609 auto vs = toVolumeSource(stream, false);
3610 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003611}
3612
Eric Laurente0720872014-03-11 09:30:41 -07003613bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003614{
3615 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003616 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003617 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003618 return true;
3619 }
3620 }
3621 return false;
3622}
3623
Eric Laurent275e8e92014-11-30 15:14:47 -08003624// Register a list of custom mixes with their attributes and format.
3625// When a mix is registered, corresponding input and output profiles are
3626// added to the remote submix hw module. The profile contains only the
3627// parameters (sampling rate, format...) specified by the mix.
3628// The corresponding input remote submix device is also connected.
3629//
3630// When a remote submix device is connected, the address is checked to select the
3631// appropriate profile and the corresponding input or output stream is opened.
3632//
3633// When capture starts, getInputForAttr() will:
3634// - 1 look for a mix matching the address passed in attribtutes tags if any
3635// - 2 if none found, getDeviceForInputSource() will:
3636// - 2.1 look for a mix matching the attributes source
3637// - 2.2 if none found, default to device selection by policy rules
3638// At this time, the corresponding output remote submix device is also connected
3639// and active playback use cases can be transferred to this mix if needed when reconnecting
3640// after AudioTracks are invalidated
3641//
3642// When playback starts, getOutputForAttr() will:
3643// - 1 look for a mix matching the address passed in attribtutes tags if any
3644// - 2 if none found, look for a mix matching the attributes usage
3645// - 3 if none found, default to device and output selection by policy rules.
3646
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003647status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003648{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003649 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3650 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003651 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003652 sp<HwModule> rSubmixModule;
3653 // examine each mix's route type
3654 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003655 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003656 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3657 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3658 ALOGE("Unsupported Policy Mix %zu of %zu: "
3659 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3660 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003661 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003662 break;
3663 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003664 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3665 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003666 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003667 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3668 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003669 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003670 rSubmixModule = mHwModules.getModuleFromName(
3671 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3672 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003673 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003674 i);
3675 res = INVALID_OPERATION;
3676 break;
3677 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003678 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003679
Eric Laurent97ac8712018-07-27 18:59:02 -07003680 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003681 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003682 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003683 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003684 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3685 } else {
3686 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3687 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003688 }
François Gaffie036e1e92015-03-19 10:16:24 +01003689
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003690 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003691 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003692 res = INVALID_OPERATION;
3693 break;
3694 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003695 audio_config_t outputConfig = mix.mFormat;
3696 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003697 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3698 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003699 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3700 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003701 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003702 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3703 audio_is_linear_pcm(outputConfig.format)
3704 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003705 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003706 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3707 audio_is_linear_pcm(inputConfig.format)
3708 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003709
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003710 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003711 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003712 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003713 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003714 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003715 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003716 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003717 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3718 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003719 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003720 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003721 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003722
3723 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3724 mix.mDeviceType, mix.mDeviceAddress,
3725 String8(), AUDIO_FORMAT_DEFAULT);
3726 if (device == nullptr) {
3727 res = INVALID_OPERATION;
3728 break;
3729 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003730
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003731 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003732 // First try to find an already opened output supporting the device
3733 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003734 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003735
Eric Laurentc529cf62020-04-17 18:19:10 -07003736 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003737 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003738 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003739 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003740 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003741 } else {
3742 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003743 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003744 }
3745 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003746 // If no output found, try to find a direct output profile supporting the device
3747 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3748 sp<HwModule> module = mHwModules[i];
3749 for (size_t j = 0;
3750 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3751 j++) {
3752 sp<IOProfile> profile = module->getOutputProfiles()[j];
3753 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3754 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3755 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003756 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003757 res = INVALID_OPERATION;
3758 } else {
3759 foundOutput = true;
3760 }
3761 }
3762 }
3763 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003764 if (res != NO_ERROR) {
3765 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003766 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003767 res = INVALID_OPERATION;
3768 break;
3769 } else if (!foundOutput) {
3770 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003771 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003772 res = INVALID_OPERATION;
3773 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003774 } else {
3775 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003776 }
Eric Laurentc722f302014-12-10 11:21:49 -08003777 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003778 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003779 if (res != NO_ERROR) {
3780 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003781 } else if (checkOutputs) {
3782 checkForDeviceAndOutputChanges();
3783 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003784 }
3785 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003786}
3787
3788status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3789{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003790 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003791 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003792 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003793 sp<HwModule> rSubmixModule;
3794 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003795 for (const auto& mix : mixes) {
3796 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003797
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003798 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003799 rSubmixModule = mHwModules.getModuleFromName(
3800 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3801 if (rSubmixModule == 0) {
3802 res = INVALID_OPERATION;
3803 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003804 }
3805 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003806
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003807 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003808
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003809 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003810 res = INVALID_OPERATION;
3811 continue;
3812 }
3813
Kevin Rocard04ed0462019-05-02 17:53:24 -07003814 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003815 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003816 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3817 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003818 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003819 AUDIO_FORMAT_DEFAULT);
3820 if (res != OK) {
3821 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003822 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003823 }
3824 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003825 }
jiabin5740f082019-08-19 15:08:30 -07003826 rSubmixModule->removeOutputProfile(address.c_str());
3827 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003828
Kevin Rocard153f92d2018-12-18 18:33:28 -08003829 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003830 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003831 res = INVALID_OPERATION;
3832 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003833 } else {
3834 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003835 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003836 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003837 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003838 if (res == NO_ERROR && checkOutputs) {
3839 checkForDeviceAndOutputChanges();
3840 updateCallAndOutputRouting();
3841 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003842 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003843}
3844
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003845status_t AudioPolicyManager::updatePolicyMix(
3846 const AudioMix& mix,
3847 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3848 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3849 if (res == NO_ERROR) {
3850 checkForDeviceAndOutputChanges();
3851 updateCallAndOutputRouting();
3852 }
3853 return res;
3854}
3855
Mikhail Naganov100f0122018-11-29 11:22:16 -08003856void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3857{
3858 size_t i = 0;
3859 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3860 for (const auto& fmt : mManualSurroundFormats) {
3861 if (i++ != 0) dst->append(", ");
3862 std::string sfmt;
3863 FormatConverter::toString(fmt, sfmt);
3864 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3865 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3866 }
3867}
3868
Eric Laurentc529cf62020-04-17 18:19:10 -07003869// Returns true if all devices types match the predicate and are supported by one HW module
3870bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003871 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003872 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003873 const char *context,
3874 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003875 for (size_t i = 0; i < devices.size(); i++) {
3876 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003877 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003878 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003879 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003880 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003881 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003882 return false;
3883 }
3884 }
3885 return true;
3886}
3887
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003888void AudioPolicyManager::changeOutputDevicesMuteState(
3889 const AudioDeviceTypeAddrVector& devices) {
3890 ALOGVV("%s() num devices %zu", __func__, devices.size());
3891
3892 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3893 getSoftwareOutputsForDevices(devices);
3894
3895 for (size_t i = 0; i < outputs.size(); i++) {
3896 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3897 DeviceVector prevDevices = outputDesc->devices();
3898 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3899 }
3900}
3901
3902std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3903 const AudioDeviceTypeAddrVector& devices) const
3904{
3905 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3906 DeviceVector deviceDescriptors;
3907 for (size_t j = 0; j < devices.size(); j++) {
3908 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3909 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3910 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3911 ALOGE("%s: device type %#x address %s not supported or not an output device",
3912 __func__, devices[j].mType, devices[j].getAddress());
3913 continue;
3914 }
3915 deviceDescriptors.add(desc);
3916 }
3917 for (size_t i = 0; i < mOutputs.size(); i++) {
3918 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3919 continue;
3920 }
3921 outputs.push_back(mOutputs.valueAt(i));
3922 }
3923 return outputs;
3924}
3925
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003926status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003927 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003928 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003929 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3930 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003931 }
3932 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003933 if (res != NO_ERROR) {
3934 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3935 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003936 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003937
3938 checkForDeviceAndOutputChanges();
3939 updateCallAndOutputRouting();
3940
3941 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003942}
3943
3944status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3945 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003946 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3947 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003948 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003949 __FUNCTION__, uid);
3950 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003951 }
3952
Eric Laurentc529cf62020-04-17 18:19:10 -07003953 checkForDeviceAndOutputChanges();
3954 updateCallAndOutputRouting();
3955
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003956 return res;
3957}
3958
Eric Laurent2517af32020-11-25 15:31:27 +01003959
jiabin0a488932020-08-07 17:32:40 -07003960status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3961 device_role_t role,
3962 const AudioDeviceTypeAddrVector &devices) {
3963 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3964 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003965
Eric Laurentc529cf62020-04-17 18:19:10 -07003966 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003967 return BAD_VALUE;
3968 }
jiabin0a488932020-08-07 17:32:40 -07003969 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003970 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003971 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3972 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003973 return status;
3974 }
3975
3976 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003977
3978 bool forceVolumeReeval = false;
3979 // FIXME: workaround for truncated touch sounds
3980 // to be removed when the problem is handled by system UI
3981 uint32_t delayMs = 0;
3982 if (strategy == mCommunnicationStrategy) {
3983 forceVolumeReeval = true;
3984 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3985 updateInputRouting();
3986 }
3987 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003988
3989 return NO_ERROR;
3990}
3991
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003992void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3993 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003994{
3995 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003996 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003997 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003998 // Only apply special touch sound delay once
3999 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004000 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004001 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004002 for (size_t i = 0; i < mOutputs.size(); i++) {
4003 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4004 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004005 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4006 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004007 // As done in setDeviceConnectionState, we could also fix default device issue by
4008 // preventing the force re-routing in case of default dev that distinguishes on address.
4009 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004010 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004011 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4012 // If the device is using preferred mixer attributes, the output need to reopen
4013 // with default configuration when the new selected devices are different from
4014 // current routing devices.
4015 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4016 continue;
4017 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304018
4019 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4020 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004021 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004022 // Only apply special touch sound delay once
4023 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004024 }
4025 if (forceVolumeReeval && !newDevices.isEmpty()) {
4026 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4027 }
4028 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004029 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004030 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004031}
4032
Eric Laurent2517af32020-11-25 15:31:27 +01004033void AudioPolicyManager::updateInputRouting() {
4034 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304035 // Skip for hotword recording as the input device switch
4036 // is handled within sound trigger HAL
4037 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4038 continue;
4039 }
Eric Laurent2517af32020-11-25 15:31:27 +01004040 auto newDevice = getNewInputDevice(activeDesc);
4041 // Force new input selection if the new device can not be reached via current input
4042 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4043 setInputDevice(activeDesc->mIoHandle, newDevice);
4044 } else {
4045 closeInput(activeDesc->mIoHandle);
4046 }
4047 }
4048}
4049
Paul Wang5d7cdb52022-11-22 09:45:06 +00004050status_t
4051AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4052 device_role_t role,
4053 const AudioDeviceTypeAddrVector &devices) {
4054 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4055 dumpAudioDeviceTypeAddrVector(devices).c_str());
4056
Eric Laurent78fedbf2023-03-09 14:40:44 +01004057 if (!areAllDevicesSupported(
4058 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004059 return BAD_VALUE;
4060 }
4061 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4062 if (status != NO_ERROR) {
4063 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4064 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4065 return status;
4066 }
4067
4068 checkForDeviceAndOutputChanges();
4069
4070 bool forceVolumeReeval = false;
4071 // TODO(b/263479999): workaround for truncated touch sounds
4072 // to be removed when the problem is handled by system UI
4073 uint32_t delayMs = 0;
4074 if (strategy == mCommunnicationStrategy) {
4075 forceVolumeReeval = true;
4076 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4077 updateInputRouting();
4078 }
4079 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4080
4081 return NO_ERROR;
4082}
4083
4084status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4085 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004086{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004087 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004088
Paul Wang5d7cdb52022-11-22 09:45:06 +00004089 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004090 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004091 ALOGW_IF(status != NAME_NOT_FOUND,
4092 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004093 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004094 return status;
4095 }
4096
4097 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004098
4099 bool forceVolumeReeval = false;
4100 // FIXME: workaround for truncated touch sounds
4101 // to be removed when the problem is handled by system UI
4102 uint32_t delayMs = 0;
4103 if (strategy == mCommunnicationStrategy) {
4104 forceVolumeReeval = true;
4105 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4106 updateInputRouting();
4107 }
4108 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004109
4110 return NO_ERROR;
4111}
4112
jiabin0a488932020-08-07 17:32:40 -07004113status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4114 device_role_t role,
4115 AudioDeviceTypeAddrVector &devices) {
4116 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004117}
4118
Jiabin Huang3b98d322020-09-03 17:54:16 +00004119status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4120 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4121 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4122 dumpAudioDeviceTypeAddrVector(devices).c_str());
4123
Mikhail Naganov55773032020-10-01 15:08:13 -07004124 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004125 return BAD_VALUE;
4126 }
4127 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4128 ALOGW_IF(status != NO_ERROR,
4129 "Engine could not set preferred devices %s for audio source %d role %d",
4130 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4131
4132 return status;
4133}
4134
4135status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4136 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4137 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4138 dumpAudioDeviceTypeAddrVector(devices).c_str());
4139
Mikhail Naganov55773032020-10-01 15:08:13 -07004140 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004141 return BAD_VALUE;
4142 }
4143 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4144 ALOGW_IF(status != NO_ERROR,
4145 "Engine could not add preferred devices %s for audio source %d role %d",
4146 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4147
Eric Laurent2517af32020-11-25 15:31:27 +01004148 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004149 return status;
4150}
4151
4152status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4153 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4154{
4155 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4156 dumpAudioDeviceTypeAddrVector(devices).c_str());
4157
Eric Laurent78fedbf2023-03-09 14:40:44 +01004158 if (!areAllDevicesSupported(
4159 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004160 return BAD_VALUE;
4161 }
4162
4163 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4164 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004165 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004166 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004167 if (status == NO_ERROR) {
4168 updateInputRouting();
4169 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004170 return status;
4171}
4172
4173status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4174 device_role_t role) {
4175 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4176
4177 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004178 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004179 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004180 if (status == NO_ERROR) {
4181 updateInputRouting();
4182 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004183 return status;
4184}
4185
4186status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4187 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4188 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4189}
4190
Oscar Azucena90e77632019-11-27 17:12:28 -08004191status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004192 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004193 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004194 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4195 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004196 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004197 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4198 if (status != NO_ERROR) {
4199 ALOGE("%s() could not set device affinity for userId %d",
4200 __FUNCTION__, userId);
4201 return status;
4202 }
4203
4204 // reevaluate outputs for all devices
4205 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004206 changeOutputDevicesMuteState(devices);
4207 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4208 true /* skipDelays */);
4209 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004210
4211 return NO_ERROR;
4212}
4213
4214status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004215 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004216 AudioDeviceTypeAddrVector devices;
4217 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004218 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4219 if (status != NO_ERROR) {
4220 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4221 __FUNCTION__, userId);
4222 return status;
4223 }
4224
4225 // reevaluate outputs for all devices
4226 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004227 changeOutputDevicesMuteState(devices);
4228 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4229 true /* skipDelays */);
4230 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004231
4232 return NO_ERROR;
4233}
4234
Andy Hungc29d82b2018-10-05 12:23:17 -07004235void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004236{
Andy Hungc29d82b2018-10-05 12:23:17 -07004237 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004238 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004239 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004240 std::string stateLiteral;
4241 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004242 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004243 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4244 "communications", "media", "record", "dock", "system",
4245 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4246 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4247 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004248 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4249 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4250 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4251 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4252 dst->append(" (MANUAL: ");
4253 dumpManualSurroundFormats(dst);
4254 dst->append(")");
4255 }
4256 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004257 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004258 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4259 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004260 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004261 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004262
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004263 dst->append("\n");
4264 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4265 dst->append("\n");
4266 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004267 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004268 mOutputs.dump(dst);
4269 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004270 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004271 mAudioPatches.dump(dst);
4272 mPolicyMixes.dump(dst);
4273 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004274
Kevin Rocardb99cc752019-03-21 20:52:24 -07004275 dst->appendFormat(" AllowedCapturePolicies:\n");
4276 for (auto& policy : mAllowedCapturePolicies) {
4277 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4278 }
4279
jiabina84c3d32022-12-02 18:59:55 +00004280 dst->appendFormat(" Preferred mixer audio configuration:\n");
4281 for (const auto it : mPreferredMixerAttrInfos) {
4282 dst->appendFormat(" - device port id: %d\n", it.first);
4283 for (const auto preferredMixerInfoIt : it.second) {
4284 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4285 preferredMixerInfoIt.second->dump(dst);
4286 }
4287 }
4288
François Gaffiec005e562018-11-06 15:04:49 +01004289 dst->appendFormat("\nPolicy Engine dump:\n");
4290 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004291}
4292
4293status_t AudioPolicyManager::dump(int fd)
4294{
4295 String8 result;
4296 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004297 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004298 return NO_ERROR;
4299}
4300
Kevin Rocardb99cc752019-03-21 20:52:24 -07004301status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4302{
4303 mAllowedCapturePolicies[uid] = capturePolicy;
4304 return NO_ERROR;
4305}
4306
Eric Laurente552edb2014-03-10 17:42:56 -07004307// This function checks for the parameters which can be offloaded.
4308// This can be enhanced depending on the capability of the DSP and policy
4309// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004310audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004311{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004312 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004313 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004314 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004315 offloadInfo.format,
4316 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4317 offloadInfo.has_video);
4318
jiabin2b9d5a12021-12-10 01:06:29 +00004319 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004320 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004321 }
4322
4323 // See if there is a profile to support this.
4324 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004325 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004326 offloadInfo.sample_rate,
4327 offloadInfo.format,
4328 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004329 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4330 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004331 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4332 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4333 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004334 if (profile == nullptr) {
4335 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4336 }
4337 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4338 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4339 }
4340 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004341}
4342
Michael Chana94fbb22018-04-24 14:31:19 +10004343bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4344 const audio_attributes_t& attributes) {
4345 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004346 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004347 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4348 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004349 config.sample_rate,
4350 config.format,
4351 config.channel_mask,
4352 output_flags,
4353 true /* directOnly */);
4354 ALOGV("%s() profile %sfound with name: %s, "
4355 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4356 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004357 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004358 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004359
4360 // also try the MSD module if compatible profile not found
4361 if (profile == nullptr) {
4362 profile = getMsdProfileForOutput(outputDevices,
4363 config.sample_rate,
4364 config.format,
4365 config.channel_mask,
4366 output_flags,
4367 true /* directOnly */);
4368 ALOGV("%s() MSD profile %sfound with name: %s, "
4369 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4370 __FUNCTION__, profile != 0 ? "" : "NOT ",
4371 (profile != 0 ? profile->getTagName().c_str() : "null"),
4372 config.sample_rate, config.format, config.channel_mask, output_flags);
4373 }
4374 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004375}
4376
jiabin2b9d5a12021-12-10 01:06:29 +00004377bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4378 bool durationIgnored) {
4379 if (mMasterMono) {
4380 return false; // no offloading if mono is set.
4381 }
4382
4383 // Check if offload has been disabled
4384 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4385 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4386 return false;
4387 }
4388
4389 // Check if stream type is music, then only allow offload as of now.
4390 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4391 {
4392 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4393 return false;
4394 }
4395
4396 //TODO: enable audio offloading with video when ready
4397 const bool allowOffloadWithVideo =
4398 property_get_bool("audio.offload.video", false /* default_value */);
4399 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4400 ALOGV("%s: has_video == true, returning false", __func__);
4401 return false;
4402 }
4403
4404 //If duration is less than minimum value defined in property, return false
4405 const int min_duration_secs = property_get_int32(
4406 "audio.offload.min.duration.secs", -1 /* default_value */);
4407 if (!durationIgnored) {
4408 if (min_duration_secs >= 0) {
4409 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4410 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4411 __func__, min_duration_secs);
4412 return false;
4413 }
4414 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4415 ALOGV("%s: Offload denied by duration < default min(=%u)",
4416 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4417 return false;
4418 }
4419 }
4420
4421 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4422 // creating an offloaded track and tearing it down immediately after start when audioflinger
4423 // detects there is an active non offloadable effect.
4424 // FIXME: We should check the audio session here but we do not have it in this context.
4425 // This may prevent offloading in rare situations where effects are left active by apps
4426 // in the background.
4427 if (mEffects.isNonOffloadableEffectEnabled()) {
4428 return false;
4429 }
4430
4431 return true;
4432}
4433
4434audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4435 const audio_config_t *config) {
4436 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4437 offloadInfo.format = config->format;
4438 offloadInfo.sample_rate = config->sample_rate;
4439 offloadInfo.channel_mask = config->channel_mask;
4440 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4441 offloadInfo.has_video = false;
4442 offloadInfo.is_streaming = false;
4443 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4444
4445 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4446 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4447 audio_flags_to_audio_output_flags(attr->flags, &flags);
4448 // only retain flags that will drive compressed offload or passthrough
4449 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4450 if (offloadPossible) {
4451 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4452 }
4453 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4454
Dorin Drimusfae3c642022-03-17 18:36:30 +01004455 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004456 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004457 DeviceVector outputDevices = engineOutputDevices;
4458 // the MSD module checks for different conditions and output devices
4459 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4460 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4461 continue;
4462 }
4463 outputDevices = getMsdAudioOutDevices();
4464 }
jiabin2b9d5a12021-12-10 01:06:29 +00004465 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004466 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004467 config->sample_rate, nullptr /*updatedSamplingRate*/,
4468 config->format, nullptr /*updatedFormat*/,
4469 config->channel_mask, nullptr /*updatedChannelMask*/,
4470 flags)) {
4471 continue;
4472 }
4473 // reject profiles not corresponding to a device currently available
4474 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4475 continue;
4476 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004477 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4478 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004479 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004480 != AUDIO_DIRECT_NOT_SUPPORTED) {
4481 // Already reports offload gapless supported. No need to report offload support.
4482 continue;
4483 }
4484 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4485 != AUDIO_OUTPUT_FLAG_NONE) {
4486 // If offload gapless is reported, no need to report offload support.
4487 directMode = (audio_direct_mode_t) ((directMode &
4488 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4489 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4490 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004491 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004492 }
4493 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004494 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004495 }
4496 }
4497 }
4498 return directMode;
4499}
4500
Dorin Drimusf2196d82022-01-03 12:11:18 +01004501status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4502 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004503 if (mEffects.isNonOffloadableEffectEnabled()) {
4504 return OK;
4505 }
jiabinf1c73972022-04-14 16:28:52 -07004506 DeviceVector devices;
4507 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004508 if (status != OK) {
4509 return status;
4510 }
4511 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4512 if (devices.empty()) {
4513 return OK; // no output devices for the attributes
4514 }
jiabinf1c73972022-04-14 16:28:52 -07004515 return getProfilesForDevices(devices, audioProfilesVector,
4516 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004517}
4518
jiabina84c3d32022-12-02 18:59:55 +00004519status_t AudioPolicyManager::getSupportedMixerAttributes(
4520 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4521 ALOGV("%s, portId=%d", __func__, portId);
4522 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4523 if (deviceDescriptor == nullptr) {
4524 ALOGE("%s the requested device is currently unavailable", __func__);
4525 return BAD_VALUE;
4526 }
jiabin96daffc2023-05-11 17:51:55 +00004527 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4528 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4529 deviceDescriptor->type());
4530 return BAD_VALUE;
4531 }
jiabina84c3d32022-12-02 18:59:55 +00004532 for (const auto& hwModule : mHwModules) {
4533 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4534 if (curProfile->supportsDevice(deviceDescriptor)) {
4535 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4536 }
4537 }
4538 }
4539 return NO_ERROR;
4540}
4541
4542status_t AudioPolicyManager::setPreferredMixerAttributes(
4543 const audio_attributes_t *attr,
4544 audio_port_handle_t portId,
4545 uid_t uid,
4546 const audio_mixer_attributes_t *mixerAttributes) {
4547 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4548 "mixerBehavior=%d}, uid=%d, portId=%u",
4549 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4550 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4551 mixerAttributes->mixer_behavior, uid, portId);
4552 if (attr->usage != AUDIO_USAGE_MEDIA) {
4553 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4554 return BAD_VALUE;
4555 }
4556 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4557 if (deviceDescriptor == nullptr) {
4558 ALOGE("%s the requested device is currently unavailable", __func__);
4559 return BAD_VALUE;
4560 }
4561 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4562 ALOGE("%s(%d), type=%d, is not a usb output device",
4563 __func__, portId, deviceDescriptor->type());
4564 return BAD_VALUE;
4565 }
4566
4567 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4568 audio_flags_to_audio_output_flags(attr->flags, &flags);
4569 flags = (audio_output_flags_t) (flags |
4570 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4571 sp<IOProfile> profile = nullptr;
4572 DeviceVector devices(deviceDescriptor);
4573 for (const auto& hwModule : mHwModules) {
4574 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4575 if (curProfile->hasDynamicAudioProfile()
4576 && curProfile->isCompatibleProfile(devices,
4577 mixerAttributes->config.sample_rate,
4578 nullptr /*updatedSamplingRate*/,
4579 mixerAttributes->config.format,
4580 nullptr /*updatedFormat*/,
4581 mixerAttributes->config.channel_mask,
4582 nullptr /*updatedChannelMask*/,
4583 flags,
4584 false /*exactMatchRequiredForInputFlags*/)) {
4585 profile = curProfile;
4586 break;
4587 }
4588 }
4589 }
4590 if (profile == nullptr) {
4591 ALOGE("%s, there is no compatible profile found", __func__);
4592 return BAD_VALUE;
4593 }
4594
4595 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4596 sp<PreferredMixerAttributesInfo>::make(
4597 uid, portId, profile, flags, *mixerAttributes);
4598 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4599 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4600
4601 // If 1) there is any client from the preferred mixer configuration owner that is currently
4602 // active and matches the strategy and 2) current output is on the preferred device and the
4603 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4604 // configuration.
4605 std::vector<audio_io_handle_t> outputsToReopen;
4606 for (size_t i = 0; i < mOutputs.size(); i++) {
4607 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004608 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4609 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4610 output->mUsePreferredMixerAttributes = true;
4611 } else {
4612 for (const auto &client: output->getActiveClients()) {
4613 if (client->uid() == uid && client->strategy() == strategy) {
4614 client->setIsInvalid();
4615 outputsToReopen.push_back(output->mIoHandle);
4616 }
jiabina84c3d32022-12-02 18:59:55 +00004617 }
4618 }
4619 }
4620 }
4621 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4622 config.sample_rate = mixerAttributes->config.sample_rate;
4623 config.channel_mask = mixerAttributes->config.channel_mask;
4624 config.format = mixerAttributes->config.format;
4625 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004626 sp<SwAudioOutputDescriptor> desc =
4627 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4628 if (desc == nullptr) {
4629 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4630 continue;
4631 }
4632 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004633 }
4634
4635 return NO_ERROR;
4636}
4637
4638sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004639 audio_port_handle_t devicePortId,
4640 product_strategy_t strategy,
4641 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004642 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4643 if (it == mPreferredMixerAttrInfos.end()) {
4644 return nullptr;
4645 }
jiabind9a58d32023-06-01 17:57:30 +00004646 if (activeBitPerfectPreferred) {
4647 for (auto [strategy, info] : it->second) {
4648 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4649 && info->getActiveClientCount() != 0) {
4650 return info;
4651 }
4652 }
jiabina84c3d32022-12-02 18:59:55 +00004653 }
jiabind9a58d32023-06-01 17:57:30 +00004654 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4655 return strategyMatchedMixerAttrInfoIt == it->second.end()
4656 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004657}
4658
4659status_t AudioPolicyManager::getPreferredMixerAttributes(
4660 const audio_attributes_t *attr,
4661 audio_port_handle_t portId,
4662 audio_mixer_attributes_t* mixerAttributes) {
4663 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4664 portId, mEngine->getProductStrategyForAttributes(*attr));
4665 if (info == nullptr) {
4666 return NAME_NOT_FOUND;
4667 }
4668 *mixerAttributes = info->getMixerAttributes();
4669 return NO_ERROR;
4670}
4671
4672status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4673 audio_port_handle_t portId,
4674 uid_t uid) {
4675 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4676 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4677 if (preferredMixerAttrInfo == nullptr) {
4678 return NAME_NOT_FOUND;
4679 }
4680 if (preferredMixerAttrInfo->getUid() != uid) {
4681 ALOGE("%s, requested uid=%d, owned uid=%d",
4682 __func__, uid, preferredMixerAttrInfo->getUid());
4683 return PERMISSION_DENIED;
4684 }
4685 mPreferredMixerAttrInfos[portId].erase(strategy);
4686 if (mPreferredMixerAttrInfos[portId].empty()) {
4687 mPreferredMixerAttrInfos.erase(portId);
4688 }
4689
4690 // Reconfig existing output
4691 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4692 for (size_t i = 0; i < mOutputs.size(); i++) {
4693 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4694 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4695 }
4696 }
4697 for (const auto output : potentialOutputsToReopen) {
4698 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4699 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4700 preferredMixerAttrInfo->getFlags())) {
4701 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4702 }
4703 }
4704 return NO_ERROR;
4705}
4706
Eric Laurent6a94d692014-05-20 11:18:06 -07004707status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4708 audio_port_type_t type,
4709 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004710 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004711 unsigned int *generation)
4712{
jiabin19cdba52020-11-24 11:28:58 -08004713 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4714 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004715 return BAD_VALUE;
4716 }
4717 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004718 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004719 *num_ports = 0;
4720 }
4721
4722 size_t portsWritten = 0;
4723 size_t portsMax = *num_ports;
4724 *num_ports = 0;
4725 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004726 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4727 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004728 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004729 for (const auto& dev : mAvailableOutputDevices) {
4730 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004731 continue;
4732 }
4733 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004734 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004735 }
4736 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004737 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004738 }
4739 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004740 for (const auto& dev : mAvailableInputDevices) {
4741 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004742 continue;
4743 }
4744 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004745 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004746 }
4747 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004748 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004749 }
4750 }
4751 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4752 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4753 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4754 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4755 }
4756 *num_ports += mInputs.size();
4757 }
4758 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004759 size_t numOutputs = 0;
4760 for (size_t i = 0; i < mOutputs.size(); i++) {
4761 if (!mOutputs[i]->isDuplicated()) {
4762 numOutputs++;
4763 if (portsWritten < portsMax) {
4764 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4765 }
4766 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004767 }
Eric Laurent84c70242014-06-23 08:46:27 -07004768 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004769 }
4770 }
jiabina84c3d32022-12-02 18:59:55 +00004771
Eric Laurent6a94d692014-05-20 11:18:06 -07004772 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004773 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004774 return NO_ERROR;
4775}
4776
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004777status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4778 std::vector<media::AudioPortFw>* _aidl_return) {
4779 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4780 audio_port_v7 port;
4781 dev->toAudioPort(&port);
4782 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4783 _aidl_return->push_back(std::move(aidlPort));
4784 return OK;
4785 };
4786
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004787 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004788 for (const auto& dev : module->getDeclaredDevices()) {
4789 if (role == media::AudioPortRole::NONE ||
4790 ((role == media::AudioPortRole::SOURCE)
4791 == audio_is_input_device(dev->type()))) {
4792 RETURN_STATUS_IF_ERROR(pushPort(dev));
4793 }
4794 }
4795 }
4796 return OK;
4797}
4798
jiabin19cdba52020-11-24 11:28:58 -08004799status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004800{
Eric Laurent99fcae42018-05-17 16:59:18 -07004801 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4802 return BAD_VALUE;
4803 }
4804 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4805 if (dev != 0) {
4806 dev->toAudioPort(port);
4807 return NO_ERROR;
4808 }
4809 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4810 if (dev != 0) {
4811 dev->toAudioPort(port);
4812 return NO_ERROR;
4813 }
4814 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4815 if (out != 0) {
4816 out->toAudioPort(port);
4817 return NO_ERROR;
4818 }
4819 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4820 if (in != 0) {
4821 in->toAudioPort(port);
4822 return NO_ERROR;
4823 }
4824 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004825}
4826
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004827status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4828 audio_patch_handle_t *handle,
4829 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004830{
François Gaffieafd4cea2019-11-18 15:50:22 +01004831 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004832 if (handle == NULL || patch == NULL) {
4833 return BAD_VALUE;
4834 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004835 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004836 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004837 return BAD_VALUE;
4838 }
4839 // only one source per audio patch supported for now
4840 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004841 return INVALID_OPERATION;
4842 }
Eric Laurent874c42872014-08-08 15:13:39 -07004843 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004844 return INVALID_OPERATION;
4845 }
Eric Laurent874c42872014-08-08 15:13:39 -07004846 for (size_t i = 0; i < patch->num_sinks; i++) {
4847 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4848 return INVALID_OPERATION;
4849 }
4850 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004851
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004852 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4853 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4854 if (srcDevice == nullptr || sinkDevice == nullptr) {
4855 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4856 return BAD_VALUE;
4857 }
4858 ALOGV("%s between source %s and sink %s", __func__,
4859 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4860 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4861 // Default attributes, default volume priority, not to infer with non raw audio patches.
4862 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4863 const struct audio_port_config *source = &patch->sources[0];
4864 sp<SourceClientDescriptor> sourceDesc =
4865 new InternalSourceClientDescriptor(
4866 portId, uid, attributes, *source, srcDevice, sinkDevice,
4867 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4868
4869 status_t status =
4870 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4871
4872 if (status != NO_ERROR) {
4873 return INVALID_OPERATION;
4874 }
4875 mAudioSources.add(portId, sourceDesc);
4876 return NO_ERROR;
4877}
4878
4879status_t AudioPolicyManager::connectAudioSourceToSink(
4880 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4881 const struct audio_patch *patch,
4882 audio_patch_handle_t &handle,
4883 uid_t uid, uint32_t delayMs)
4884{
4885 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4886 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4887 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4888 return INVALID_OPERATION;
4889 }
4890 sourceDesc->connect(handle, sinkDevice);
4891 if (isMsdPatch(handle)) {
4892 return NO_ERROR;
4893 }
4894 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4895 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4896 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4897 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4898 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4899 goto FailurePatchAdded;
4900 }
4901 status = swOutput->start();
4902 if (status != NO_ERROR) {
4903 goto FailureSourceAdded;
4904 }
4905 swOutput->addClient(sourceDesc);
4906 status = startSource(swOutput, sourceDesc, &delayMs);
4907 if (status != NO_ERROR) {
4908 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4909 goto FailureSourceActive;
4910 }
4911 if (delayMs != 0) {
4912 usleep(delayMs * 1000);
4913 }
4914 return NO_ERROR;
4915
4916FailureSourceActive:
4917 swOutput->stop();
4918 releaseOutput(sourceDesc->portId());
4919FailureSourceAdded:
4920 sourceDesc->setSwOutput(nullptr);
4921FailurePatchAdded:
4922 releaseAudioPatchInternal(handle);
4923 return INVALID_OPERATION;
4924}
4925
4926status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4927 audio_patch_handle_t *handle,
4928 uid_t uid, uint32_t delayMs,
4929 const sp<SourceClientDescriptor>& sourceDesc)
4930{
4931 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004932 sp<AudioPatch> patchDesc;
4933 ssize_t index = mAudioPatches.indexOfKey(*handle);
4934
François Gaffieafd4cea2019-11-18 15:50:22 +01004935 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4936 patch->sources[0].role,
4937 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004938#if LOG_NDEBUG == 0
4939 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004940 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4941 patch->sinks[i].role,
4942 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004943 }
4944#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004945
4946 if (index >= 0) {
4947 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004948 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4949 __func__, mUidCached, patchDesc->getUid(), uid);
4950 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004951 return INVALID_OPERATION;
4952 }
4953 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004954 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004955 }
4956
4957 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004958 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004959 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004960 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 return BAD_VALUE;
4962 }
Eric Laurent84c70242014-06-23 08:46:27 -07004963 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4964 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004965 if (patchDesc != 0) {
4966 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004967 ALOGV("%s source id differs for patch current id %d new id %d",
4968 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004969 return BAD_VALUE;
4970 }
4971 }
Eric Laurent874c42872014-08-08 15:13:39 -07004972 DeviceVector devices;
4973 for (size_t i = 0; i < patch->num_sinks; i++) {
4974 // Only support mix to devices connection
4975 // TODO add support for mix to mix connection
4976 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004977 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004978 return INVALID_OPERATION;
4979 }
4980 sp<DeviceDescriptor> devDesc =
4981 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4982 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004983 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004984 return BAD_VALUE;
4985 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004986
François Gaffie11d30102018-11-02 16:09:09 +01004987 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004988 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004989 NULL, // updatedSamplingRate
4990 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004991 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004992 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004993 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004994 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004995 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004996 return INVALID_OPERATION;
4997 }
4998 devices.add(devDesc);
4999 }
5000 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005001 return INVALID_OPERATION;
5002 }
Eric Laurent874c42872014-08-08 15:13:39 -07005003
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005005 ALOGV("%s setting device %s on output %d",
5006 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305007 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005008 index = mAudioPatches.indexOfKey(*handle);
5009 if (index >= 0) {
5010 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005011 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005012 }
5013 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005014 patchDesc->setUid(uid);
5015 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005017 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005018 return INVALID_OPERATION;
5019 }
5020 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5021 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5022 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005023 // only one sink supported when connecting an input device to a mix
5024 if (patch->num_sinks > 1) {
5025 return INVALID_OPERATION;
5026 }
François Gaffie53615e22015-03-19 09:24:12 +01005027 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005028 if (inputDesc == NULL) {
5029 return BAD_VALUE;
5030 }
5031 if (patchDesc != 0) {
5032 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5033 return BAD_VALUE;
5034 }
5035 }
François Gaffie11d30102018-11-02 16:09:09 +01005036 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005037 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005038 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005039 return BAD_VALUE;
5040 }
5041
François Gaffie11d30102018-11-02 16:09:09 +01005042 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005043 patch->sinks[0].sample_rate,
5044 NULL, /*updatedSampleRate*/
5045 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005046 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005047 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005048 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005049 // FIXME for the parameter type,
5050 // and the NONE
5051 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005052 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005053 return INVALID_OPERATION;
5054 }
5055 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005056 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005057 device->toString().c_str(), inputDesc->mIoHandle);
5058 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005059 index = mAudioPatches.indexOfKey(*handle);
5060 if (index >= 0) {
5061 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005062 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005063 }
5064 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005065 patchDesc->setUid(uid);
5066 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005067 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005068 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005069 return INVALID_OPERATION;
5070 }
5071 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5072 // device to device connection
5073 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005074 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005075 return BAD_VALUE;
5076 }
5077 }
François Gaffie11d30102018-11-02 16:09:09 +01005078 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005079 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005080 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005081 return BAD_VALUE;
5082 }
Eric Laurent874c42872014-08-08 15:13:39 -07005083
Eric Laurent6a94d692014-05-20 11:18:06 -07005084 //update source and sink with our own data as the data passed in the patch may
5085 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005086 PatchBuilder patchBuilder;
5087 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005088
5089 // if first sink is to MSD, establish single MSD patch
5090 if (getMsdAudioOutDevices().contains(
5091 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5092 ALOGV("%s patching to MSD", __FUNCTION__);
5093 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5094 goto installPatch;
5095 }
5096
François Gaffieafd4cea2019-11-18 15:50:22 +01005097 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5098 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005099
Eric Laurent874c42872014-08-08 15:13:39 -07005100 for (size_t i = 0; i < patch->num_sinks; i++) {
5101 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005102 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005103 return INVALID_OPERATION;
5104 }
François Gaffie11d30102018-11-02 16:09:09 +01005105 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005106 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005107 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005108 return BAD_VALUE;
5109 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005110 audio_port_config sinkPortConfig = {};
5111 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5112 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005113
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005114 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5115 // volume management purpose (tracking activity)
5116 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5117 // in config XML to reach the sink so that is can be declared as available.
5118 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005119 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005120 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005121 // take care of dynamic routing for SwOutput selection,
5122 audio_attributes_t attributes = sourceDesc->attributes();
5123 audio_stream_type_t stream = sourceDesc->stream();
5124 audio_attributes_t resultAttr;
5125 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5126 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005127 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5128 config.channel_mask =
5129 (audio_channel_mask_get_representation(sourceMask)
5130 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5131 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005132 config.format = sourceDesc->config().format;
5133 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5134 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5135 bool isRequestedDeviceForExclusiveUse = false;
5136 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005137 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005138 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005139 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5140 &stream, sourceDesc->uid(), &config, &flags,
5141 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005142 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005143 if (output == AUDIO_IO_HANDLE_NONE) {
5144 ALOGV("%s no output for device %s",
5145 __FUNCTION__, sinkDevice->toString().c_str());
5146 return INVALID_OPERATION;
5147 }
5148 outputDesc = mOutputs.valueFor(output);
5149 if (outputDesc->isDuplicated()) {
5150 ALOGE("%s output is duplicated", __func__);
5151 return INVALID_OPERATION;
5152 }
François Gaffie7e39df22022-04-26 12:48:49 +02005153 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5154 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005155 } else {
5156 // Same for "raw patches" aka created from createAudioPatch API
5157 SortedVector<audio_io_handle_t> outputs =
5158 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5159 // if the sink device is reachable via an opened output stream, request to
5160 // go via this output stream by adding a second source to the patch
5161 // description
5162 output = selectOutput(outputs);
5163 if (output == AUDIO_IO_HANDLE_NONE) {
5164 ALOGE("%s no output available for internal patch sink", __func__);
5165 return INVALID_OPERATION;
5166 }
5167 outputDesc = mOutputs.valueFor(output);
5168 if (outputDesc->isDuplicated()) {
5169 ALOGV("%s output for device %s is duplicated",
5170 __func__, sinkDevice->toString().c_str());
5171 return INVALID_OPERATION;
5172 }
François Gaffie7e39df22022-04-26 12:48:49 +02005173 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005174 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005175 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005176 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005177 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005178 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005179 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5180 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005181 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5182 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005183 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005184 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005185 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005186 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005187 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005188 return INVALID_OPERATION;
5189 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005190 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005191 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005192 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005193 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005194 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005195 srcMixPortConfig.ext.mix.usecase.stream =
5196 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005197 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5198 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005199 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005200 }
Eric Laurent83b88082014-06-20 18:31:16 -07005201 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005202 }
5203 // TODO: check from routing capabilities in config file and other conflicting patches
5204
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005205installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005206 status_t status = installPatch(
5207 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005208 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005209 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005210 return INVALID_OPERATION;
5211 }
5212 } else {
5213 return BAD_VALUE;
5214 }
5215 } else {
5216 return BAD_VALUE;
5217 }
5218 return NO_ERROR;
5219}
5220
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005221status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005222{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005223 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005224 ssize_t index = mAudioPatches.indexOfKey(handle);
5225
5226 if (index < 0) {
5227 return BAD_VALUE;
5228 }
5229 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005230 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5231 __func__, mUidCached, patchDesc->getUid(), uid);
5232 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005233 return INVALID_OPERATION;
5234 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005235 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5236 for (size_t i = 0; i < mAudioSources.size(); i++) {
5237 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5238 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5239 portId = sourceDesc->portId();
5240 break;
5241 }
5242 }
5243 return portId != AUDIO_PORT_HANDLE_NONE ?
5244 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005245}
Eric Laurent6a94d692014-05-20 11:18:06 -07005246
François Gaffieafd4cea2019-11-18 15:50:22 +01005247status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005248 uint32_t delayMs,
5249 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005250{
5251 ALOGV("%s patch %d", __func__, handle);
5252 if (mAudioPatches.indexOfKey(handle) < 0) {
5253 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5254 return BAD_VALUE;
5255 }
5256 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005257 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005258 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005259 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005260 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005261 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005262 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 return BAD_VALUE;
5264 }
5265
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305266 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005267 getNewOutputDevices(outputDesc, true /*fromCache*/),
5268 true,
5269 0,
5270 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5272 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005273 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005274 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005275 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005276 return BAD_VALUE;
5277 }
5278 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005279 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 true,
5281 NULL);
5282 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005283 status_t status =
5284 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5285 ALOGV("%s patch panel returned %d patchHandle %d",
5286 __func__, status, patchDesc->getAfHandle());
5287 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005289 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005290 // SW or HW Bridge
5291 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5292 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005293 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005294 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5295 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5296 outputDesc = sourceDesc->swOutput().promote();
5297 }
5298 if (outputDesc == nullptr) {
5299 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5300 // releaseOutput has already called closeOutput in case of direct output
5301 return NO_ERROR;
5302 }
François Gaffie7e39df22022-04-26 12:48:49 +02005303 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005304 // While using a HwBridge, force reconsidering device only if not reusing an existing
5305 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005306 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005307 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5308 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5309 // Reconsider device only for cases:
5310 // 1 / Active Output
5311 // 2 / Inactive Output previously hosting HwBridge
5312 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5313 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5314 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305315 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005316 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5317 outputDesc->devices(),
5318 force,
5319 0,
5320 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 } else {
5322 return BAD_VALUE;
5323 }
5324 } else {
5325 return BAD_VALUE;
5326 }
5327 return NO_ERROR;
5328}
5329
5330status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5331 struct audio_patch *patches,
5332 unsigned int *generation)
5333{
François Gaffie53615e22015-03-19 09:24:12 +01005334 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005335 return BAD_VALUE;
5336 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005337 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005338 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005339}
5340
Eric Laurente1715a42014-05-20 11:30:42 -07005341status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005342{
Eric Laurente1715a42014-05-20 11:30:42 -07005343 ALOGV("setAudioPortConfig()");
5344
5345 if (config == NULL) {
5346 return BAD_VALUE;
5347 }
5348 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5349 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005350 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5351 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005352 }
5353
Eric Laurenta121f902014-06-03 13:32:54 -07005354 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005355 if (config->type == AUDIO_PORT_TYPE_MIX) {
5356 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005357 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005358 if (outputDesc == NULL) {
5359 return BAD_VALUE;
5360 }
Eric Laurent84c70242014-06-23 08:46:27 -07005361 ALOG_ASSERT(!outputDesc->isDuplicated(),
5362 "setAudioPortConfig() called on duplicated output %d",
5363 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005364 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005365 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005366 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005367 if (inputDesc == NULL) {
5368 return BAD_VALUE;
5369 }
Eric Laurenta121f902014-06-03 13:32:54 -07005370 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005371 } else {
5372 return BAD_VALUE;
5373 }
5374 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5375 sp<DeviceDescriptor> deviceDesc;
5376 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5377 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5378 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5379 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5380 } else {
5381 return BAD_VALUE;
5382 }
5383 if (deviceDesc == NULL) {
5384 return BAD_VALUE;
5385 }
Eric Laurenta121f902014-06-03 13:32:54 -07005386 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005387 } else {
5388 return BAD_VALUE;
5389 }
5390
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005391 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005392 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5393 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005394 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005395 audioPortConfig->toAudioPortConfig(&newConfig, config);
5396 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005397 }
Eric Laurenta121f902014-06-03 13:32:54 -07005398 if (status != NO_ERROR) {
5399 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005400 }
Eric Laurente1715a42014-05-20 11:30:42 -07005401
5402 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005403}
5404
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005405void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5406{
Eric Laurentd60560a2015-04-10 11:31:20 -07005407 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005408 clearAudioPatches(uid);
5409 clearSessionRoutes(uid);
5410}
5411
Eric Laurent6a94d692014-05-20 11:18:06 -07005412void AudioPolicyManager::clearAudioPatches(uid_t uid)
5413{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005414 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005415 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005416 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005417 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005418 }
5419 }
5420}
5421
François Gaffiec005e562018-11-06 15:04:49 +01005422void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005423{
François Gaffiec005e562018-11-06 15:04:49 +01005424 // Take the first attributes following the product strategy as it is used to retrieve the routed
5425 // device. All attributes wihin a strategy follows the same "routing strategy"
5426 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5427 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005428 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005429 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005430 for (size_t j = 0; j < mOutputs.size(); j++) {
5431 if (mOutputs.keyAt(j) == ouptutToSkip) {
5432 continue;
5433 }
5434 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005435 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005436 continue;
5437 }
5438 // If the default device for this strategy is on another output mix,
5439 // invalidate all tracks in this strategy to force re connection.
5440 // Otherwise select new device on the output mix.
5441 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005442 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005443 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005444 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5445 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5446 // If the device is using preferred mixer attributes, the output need to reopen
5447 // with default configuration when the new selected devices are different from
5448 // current routing devices.
5449 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5450 continue;
5451 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305452 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005453 }
5454 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005455 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005456}
5457
5458void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5459{
5460 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005461 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005462 for (size_t i = 0; i < mOutputs.size(); i++) {
5463 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005464 for (const auto& client : outputDesc->getClientIterable()) {
5465 if (client->hasPreferredDevice() && client->uid() == uid) {
5466 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005467 auto clientStrategy = client->strategy();
5468 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5469 end(affectedStrategies)) {
5470 continue;
5471 }
5472 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005473 }
5474 }
5475 }
5476 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005477 for (const auto& strategy : affectedStrategies) {
5478 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005479 }
5480
5481 // remove input routes associated with this uid
5482 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005483 for (size_t i = 0; i < mInputs.size(); i++) {
5484 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005485 for (const auto& client : inputDesc->getClientIterable()) {
5486 if (client->hasPreferredDevice() && client->uid() == uid) {
5487 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5488 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005489 }
5490 }
5491 }
5492 // reroute inputs if necessary
5493 SortedVector<audio_io_handle_t> inputsToClose;
5494 for (size_t i = 0; i < mInputs.size(); i++) {
5495 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005496 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005497 inputsToClose.add(inputDesc->mIoHandle);
5498 }
5499 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005500 for (const auto& input : inputsToClose) {
5501 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005502 }
5503}
5504
Eric Laurentd60560a2015-04-10 11:31:20 -07005505void AudioPolicyManager::clearAudioSources(uid_t uid)
5506{
5507 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005508 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5509 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005510 stopAudioSource(mAudioSources.keyAt(i));
5511 }
5512 }
5513}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005514
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005515status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5516 audio_io_handle_t *ioHandle,
5517 audio_devices_t *device)
5518{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005519 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5520 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005521 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005522 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5523 if (deviceDesc == nullptr) {
5524 return INVALID_OPERATION;
5525 }
5526 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005527
François Gaffiedf372692015-03-19 10:43:27 +01005528 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005529}
5530
Eric Laurentd60560a2015-04-10 11:31:20 -07005531status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005532 const audio_attributes_t *attributes,
5533 audio_port_handle_t *portId,
5534 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005535{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005536 ALOGV("%s", __FUNCTION__);
5537 *portId = AUDIO_PORT_HANDLE_NONE;
5538
5539 if (source == NULL || attributes == NULL || portId == NULL) {
5540 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5541 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005542 return BAD_VALUE;
5543 }
5544
Eric Laurentd60560a2015-04-10 11:31:20 -07005545 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5546 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005547 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5548 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005549 return INVALID_OPERATION;
5550 }
5551
François Gaffie11d30102018-11-02 16:09:09 +01005552 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005553 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005554 String8(source->ext.device.address),
5555 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005556 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005557 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005558 return BAD_VALUE;
5559 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005560
jiabin4ef93452019-09-10 14:29:54 -07005561 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005562
François Gaffieaaac0fd2018-11-22 17:56:39 +01005563 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005564 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005565 mEngine->getStreamTypeForAttributes(*attributes),
5566 mEngine->getProductStrategyForAttributes(*attributes),
5567 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005568
5569 status_t status = connectAudioSource(sourceDesc);
5570 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005571 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005572 }
5573 return status;
5574}
5575
Francois Gaffie601801d2021-06-22 13:27:39 +02005576sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5577 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5578{
5579 ALOGV("%s", __FUNCTION__);
5580 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5581
5582 status_t status = startAudioSource(source, attributes, &portId, uid);
5583 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5584 return mAudioSources.valueFor(portId);
5585}
5586
5587
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005588status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005589{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005590 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005591
5592 // make sure we only have one patch per source.
5593 disconnectAudioSource(sourceDesc);
5594
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005595 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005596 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5597 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5598 sourceDesc->srcDevice()->type(),
5599 String8(sourceDesc->srcDevice()->address().c_str()),
5600 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005601 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005602 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005603 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005604 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005605 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5606 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5607 return INVALID_OPERATION;
5608 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005609 PatchBuilder patchBuilder;
5610 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5611 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005612
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005613 return connectAudioSourceToSink(
5614 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005615}
5616
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005617status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005618{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005619 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5620 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005621 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005622 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005623 return BAD_VALUE;
5624 }
5625 status_t status = disconnectAudioSource(sourceDesc);
5626
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005627 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005628 return status;
5629}
5630
Andy Hung2ddee192015-12-18 17:34:44 -08005631status_t AudioPolicyManager::setMasterMono(bool mono)
5632{
5633 if (mMasterMono == mono) {
5634 return NO_ERROR;
5635 }
5636 mMasterMono = mono;
5637 // if enabling mono we close all offloaded devices, which will invalidate the
5638 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5639 // for recreating the new AudioTrack as non-offloaded PCM.
5640 //
5641 // If disabling mono, we leave all tracks as is: we don't know which clients
5642 // and tracks are able to be recreated as offloaded. The next "song" should
5643 // play back offloaded.
5644 if (mMasterMono) {
5645 Vector<audio_io_handle_t> offloaded;
5646 for (size_t i = 0; i < mOutputs.size(); ++i) {
5647 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5648 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5649 offloaded.push(desc->mIoHandle);
5650 }
5651 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005652 for (const auto& handle : offloaded) {
5653 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005654 }
5655 }
5656 // update master mono for all remaining outputs
5657 for (size_t i = 0; i < mOutputs.size(); ++i) {
5658 updateMono(mOutputs.keyAt(i));
5659 }
5660 return NO_ERROR;
5661}
5662
5663status_t AudioPolicyManager::getMasterMono(bool *mono)
5664{
5665 *mono = mMasterMono;
5666 return NO_ERROR;
5667}
5668
Eric Laurentac9cef52017-06-09 15:46:26 -07005669float AudioPolicyManager::getStreamVolumeDB(
5670 audio_stream_type_t stream, int index, audio_devices_t device)
5671{
jiabin9a3361e2019-10-01 09:38:30 -07005672 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005673}
5674
jiabin81772902018-04-02 17:52:27 -07005675status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5676 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005677 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005678{
Kriti Dang6537def2021-03-02 13:46:59 +01005679 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5680 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005681 return BAD_VALUE;
5682 }
Kriti Dang6537def2021-03-02 13:46:59 +01005683 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5684 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005685
5686 size_t formatsWritten = 0;
5687 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005688
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005689 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005690 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5691 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005692 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005693 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005694 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005695 bool formatEnabled = true;
5696 switch (forceUse) {
5697 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005698 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005699 break;
5700 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5701 formatEnabled = false;
5702 break;
5703 default: // AUTO or ALWAYS => true
5704 break;
jiabin81772902018-04-02 17:52:27 -07005705 }
5706 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5707 }
jiabin81772902018-04-02 17:52:27 -07005708 }
5709 return NO_ERROR;
5710}
5711
Kriti Dang6537def2021-03-02 13:46:59 +01005712status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5713 audio_format_t *surroundFormats) {
5714 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5715 return BAD_VALUE;
5716 }
5717 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5718 __func__, *numSurroundFormats, surroundFormats);
5719
5720 size_t formatsWritten = 0;
5721 size_t formatsMax = *numSurroundFormats;
5722 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5723
5724 // Return formats from all device profiles that have already been resolved by
5725 // checkOutputsForDevice().
5726 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5727 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5728 audio_devices_t deviceType = device->type();
5729 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5730 // returns formats reported by HDMI devices.
5731 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5732 continue;
5733 }
5734 // Formats reported by sink devices
5735 std::unordered_set<audio_format_t> formatset;
5736 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5737 formatset.insert(it->second.begin(), it->second.end());
5738 }
5739
5740 // Formats hard-coded in the in policy configuration file (if any).
5741 FormatVector encodedFormats = device->encodedFormats();
5742 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5743 // Filter the formats which are supported by the vendor hardware.
5744 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005745 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005746 formats.insert(*it);
5747 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005748 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005749 if (pair.second.count(*it) != 0) {
5750 formats.insert(pair.first);
5751 break;
5752 }
5753 }
5754 }
5755 }
5756 }
5757 *numSurroundFormats = formats.size();
5758 for (const auto& format: formats) {
5759 if (formatsWritten < formatsMax) {
5760 surroundFormats[formatsWritten++] = format;
5761 }
5762 }
5763 return NO_ERROR;
5764}
5765
jiabin81772902018-04-02 17:52:27 -07005766status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5767{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005768 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005769 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5770 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005771 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005772 return BAD_VALUE;
5773 }
5774
Mikhail Naganov100f0122018-11-29 11:22:16 -08005775 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5776 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005777 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005778 return INVALID_OPERATION;
5779 }
5780
Mikhail Naganov100f0122018-11-29 11:22:16 -08005781 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005782 return NO_ERROR;
5783 }
5784
Mikhail Naganov100f0122018-11-29 11:22:16 -08005785 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005786 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005787 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005788 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005789 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005790 }
5791 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005792 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005793 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005794 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005795 }
5796 }
5797
5798 sp<SwAudioOutputDescriptor> outputDesc;
5799 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005800 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5801 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005802 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5803 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005804 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005805 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005806 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5807 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5808 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005809 name.c_str(),
5810 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005811 if (status != NO_ERROR) {
5812 continue;
5813 }
5814 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5815 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5816 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005817 name.c_str(),
5818 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005819 profileUpdated |= (status == NO_ERROR);
5820 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005821 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005822 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005823 AUDIO_DEVICE_IN_HDMI);
5824 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5825 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005826 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005827 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005828 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5829 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5830 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005831 name.c_str(),
5832 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005833 if (status != NO_ERROR) {
5834 continue;
5835 }
5836 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5837 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5838 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005839 name.c_str(),
5840 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005841 profileUpdated |= (status == NO_ERROR);
5842 }
5843
jiabin81772902018-04-02 17:52:27 -07005844 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005845 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005846 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005847 }
5848
5849 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5850}
5851
Eric Laurent5ada82e2019-08-29 17:53:54 -07005852void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005853{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005854 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005855 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005856 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005857 }
5858}
5859
jiabin6012f912018-11-02 17:06:30 -07005860bool AudioPolicyManager::isHapticPlaybackSupported()
5861{
5862 for (const auto& hwModule : mHwModules) {
5863 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5864 for (const auto &outProfile : outputProfiles) {
5865 struct audio_port audioPort;
5866 outProfile->toAudioPort(&audioPort);
5867 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5868 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5869 return true;
5870 }
5871 }
5872 }
5873 }
5874 return false;
5875}
5876
Carter Hsu325a8eb2022-01-19 19:56:51 +08005877bool AudioPolicyManager::isUltrasoundSupported()
5878{
5879 bool hasUltrasoundOutput = false;
5880 bool hasUltrasoundInput = false;
5881 for (const auto& hwModule : mHwModules) {
5882 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5883 if (!hasUltrasoundOutput) {
5884 for (const auto &outProfile : outputProfiles) {
5885 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5886 hasUltrasoundOutput = true;
5887 break;
5888 }
5889 }
5890 }
5891
5892 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5893 if (!hasUltrasoundInput) {
5894 for (const auto &inputProfile : inputProfiles) {
5895 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5896 hasUltrasoundInput = true;
5897 break;
5898 }
5899 }
5900 }
5901
5902 if (hasUltrasoundOutput && hasUltrasoundInput)
5903 return true;
5904 }
5905 return false;
5906}
5907
Atneya Nair698f5ef2022-12-15 16:15:09 -08005908bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5909{
5910 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5911 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5912 for (const auto& hwModule : mHwModules) {
5913 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5914 for (const auto &inputProfile : inputProfiles) {
5915 if ((inputProfile->getFlags() & mask) == mask) {
5916 return true;
5917 }
5918 }
5919 }
5920 return false;
5921}
5922
Eric Laurent8340e672019-11-06 11:01:08 -08005923bool AudioPolicyManager::isCallScreenModeSupported()
5924{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005925 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005926}
5927
5928
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005929status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005930{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005931 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005932 if (!sourceDesc->isConnected()) {
5933 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5934 return NO_ERROR;
5935 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005936 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5937 if (swOutput != 0) {
5938 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005939 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005940 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005941 }
jiabinbce0c1d2020-10-05 11:20:18 -07005942 if (releaseOutput(sourceDesc->portId())) {
5943 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5944 // no need to release audio patch here but just return NO_ERROR.
5945 return NO_ERROR;
5946 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005947 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005948 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005949 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005950 // close Hwoutput and remove from mHwOutputs
5951 } else {
5952 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5953 }
5954 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005955 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005956 sourceDesc->disconnect();
5957 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005958}
5959
François Gaffiec005e562018-11-06 15:04:49 +01005960sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5961 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005962{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005963 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005964 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005965 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005966 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005967 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5968 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005969 source = sourceDesc;
5970 break;
5971 }
5972 }
5973 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005974}
5975
Eric Laurentb4f42a92022-01-17 17:37:31 +01005976bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005977 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005978 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005979{
5980 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5981 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005982 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005983 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005984 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5985 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5986 return false;
5987 }
5988 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5989 return false;
5990 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005991 }
5992
Eric Laurentd332bc82023-08-04 11:45:23 +02005993 // The caller can have the audio config criteria ignored by either passing a null ptr or
5994 // the AUDIO_CONFIG_INITIALIZER value.
5995 // If an audio config is specified, current policy is to only allow spatialization for
5996 // some positional channel masks and PCM format
5997
5998 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5999 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
6000 return false;
6001 }
6002 if (!audio_is_linear_pcm(config->format)) {
6003 return false;
6004 }
6005 }
6006
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006007 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006008 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006009 if (profile == nullptr) {
6010 return false;
6011 }
6012
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006013 return true;
6014}
6015
6016void AudioPolicyManager::checkVirtualizerClientRoutes() {
6017 std::set<audio_stream_type_t> streamsToInvalidate;
6018 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006019 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6020 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006021 audio_attributes_t attr = client->attributes();
6022 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6023 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6024 audio_config_base_t clientConfig = client->config();
6025 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006026 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006027 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006028 streamsToInvalidate.insert(client->stream());
6029 }
6030 }
6031 }
6032
jiabinc44b3462022-12-08 12:52:31 -08006033 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006034}
6035
Eric Laurente191d1b2022-04-15 11:59:25 +02006036
6037bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6038 const sp<SwAudioOutputDescriptor>& outputDesc) {
6039 if (outputDesc->isDuplicated()) {
6040 return false;
6041 }
6042 DeviceVector devices = outputDesc->supportedDevices();
6043 for (size_t i = 0; i < mOutputs.size(); i++) {
6044 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6045 if (desc == outputDesc || desc->isDuplicated()) {
6046 continue;
6047 }
6048 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6049 if (!sharedDevices.isEmpty()
6050 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6051 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6052 return false;
6053 }
6054 }
6055 return true;
6056}
6057
6058
Eric Laurentfa0f6742021-08-17 18:39:44 +02006059status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006060 const audio_attributes_t *attr,
6061 audio_io_handle_t *output) {
6062 *output = AUDIO_IO_HANDLE_NONE;
6063
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006064 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6065 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6066 audio_config_t *configPtr = nullptr;
6067 audio_config_t config;
6068 if (mixerConfig != nullptr) {
6069 config = audio_config_initializer(mixerConfig);
6070 configPtr = &config;
6071 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006072 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006073 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006074 return BAD_VALUE;
6075 }
6076
6077 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006078 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006079 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006080 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006081 return BAD_VALUE;
6082 }
6083
Eric Laurente191d1b2022-04-15 11:59:25 +02006084 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006085 for (size_t i = 0; i < mOutputs.size(); i++) {
6086 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006087 if (!desc->isDuplicated()
6088 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6089 spatializerOutputs.push_back(desc);
6090 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006091 }
6092 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006093 mSpatializerOutput.clear();
6094 bool outputsChanged = false;
6095 for (const auto& desc : spatializerOutputs) {
6096 if (desc->mProfile == profile
6097 && (configPtr == nullptr
6098 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6099 mSpatializerOutput = desc;
6100 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6101 } else {
6102 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6103 " and devices %s", __func__, desc->mIoHandle,
6104 configPtr != nullptr ? configPtr->channel_mask : 0,
6105 devices.toString().c_str());
6106 closeOutput(desc->mIoHandle);
6107 outputsChanged = true;
6108 }
Eric Laurent39095982021-08-24 18:29:27 +02006109 }
6110
Eric Laurente191d1b2022-04-15 11:59:25 +02006111 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006112 sp<SwAudioOutputDescriptor> desc =
6113 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006114 if (desc != nullptr) {
6115 mSpatializerOutput = desc;
6116 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006117 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006118 }
6119
6120 checkVirtualizerClientRoutes();
6121
Eric Laurente191d1b2022-04-15 11:59:25 +02006122 if (outputsChanged) {
6123 mPreviousOutputs = mOutputs;
6124 mpClientInterface->onAudioPortListUpdate();
6125 }
6126
6127 if (mSpatializerOutput == nullptr) {
6128 ALOGV("%s could not open spatializer output with requested config", __func__);
6129 return BAD_VALUE;
6130 }
Eric Laurent39095982021-08-24 18:29:27 +02006131 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006132 ALOGV("%s returning new spatializer output %d", __func__, *output);
6133 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006134}
6135
Eric Laurentfa0f6742021-08-17 18:39:44 +02006136status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6137 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006138 return INVALID_OPERATION;
6139 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006140 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006141 return BAD_VALUE;
6142 }
Eric Laurent39095982021-08-24 18:29:27 +02006143
Eric Laurente191d1b2022-04-15 11:59:25 +02006144 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6145 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6146 closeOutput(mSpatializerOutput->mIoHandle);
6147 //from now on mSpatializerOutput is null
6148 checkVirtualizerClientRoutes();
6149 }
Eric Laurent39095982021-08-24 18:29:27 +02006150
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006151 return NO_ERROR;
6152}
6153
Eric Laurente552edb2014-03-10 17:42:56 -07006154// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006155// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006156// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006157uint32_t AudioPolicyManager::nextAudioPortGeneration()
6158{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006159 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006160}
6161
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006162AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006163 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006164 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006165 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006166 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006167 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006168 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006169 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006170 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006171 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006172 mAudioPortGeneration(1),
6173 mBeaconMuteRefCount(0),
6174 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006175 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006176 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006177 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006178 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006179{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006180}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006181
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006182status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006183 if (mEngine == nullptr) {
6184 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006185 }
6186 mEngine->setObserver(this);
6187 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006188 if (status != NO_ERROR) {
6189 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6190 return status;
6191 }
François Gaffie2110e042015-03-24 08:41:51 +01006192
jiabin29230182023-04-04 21:02:36 +00006193 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6194 // at the end of this function.
6195 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006196 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6197 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6198
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006199 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006200 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006201 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006202
Eric Laurent3a4311c2014-03-17 12:00:47 -07006203 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006204 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6205 defaultOutputDevice == nullptr ||
6206 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6207 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6208 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006209 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006210 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006211 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006212
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006213 // Silence ALOGV statements
6214 property_set("log.tag." LOG_TAG, "D");
6215
Eric Laurente552edb2014-03-10 17:42:56 -07006216 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006217 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006218}
6219
Eric Laurente0720872014-03-11 09:30:41 -07006220AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006221{
Eric Laurente552edb2014-03-10 17:42:56 -07006222 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006223 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006224 }
6225 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006226 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006227 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006228 mAvailableOutputDevices.clear();
6229 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006230 mOutputs.clear();
6231 mInputs.clear();
6232 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006233 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006234 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006235}
6236
Eric Laurente0720872014-03-11 09:30:41 -07006237status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006238{
Eric Laurent87ffa392015-05-22 10:32:38 -07006239 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006240}
6241
Eric Laurente552edb2014-03-10 17:42:56 -07006242// ---
6243
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006244void AudioPolicyManager::onNewAudioModulesAvailable()
6245{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006246 DeviceVector newDevices;
6247 onNewAudioModulesAvailableInt(&newDevices);
6248 if (!newDevices.empty()) {
6249 nextAudioPortGeneration();
6250 mpClientInterface->onAudioPortListUpdate();
6251 }
6252}
6253
6254void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6255{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006256 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006257 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6258 continue;
6259 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006260 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006261 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6262 handle != AUDIO_MODULE_HANDLE_NONE) {
6263 hwModule->setHandle(handle);
6264 } else {
6265 ALOGW("could not load HW module %s", hwModule->getName());
6266 continue;
6267 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006268 }
6269 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006270 // open all output streams needed to access attached devices.
6271 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006272 // This also validates mAvailableOutputDevices list
6273 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6274 if (!outProfile->canOpenNewIo()) {
6275 ALOGE("Invalid Output profile max open count %u for profile %s",
6276 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6277 continue;
6278 }
6279 if (!outProfile->hasSupportedDevices()) {
6280 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6281 continue;
6282 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006283 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6284 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006285 mTtsOutputAvailable = true;
6286 }
6287
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006288 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006289 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006290 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006291 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6292 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006293 } else {
6294 // choose first device present in profile's SupportedDevices also part of
6295 // mAvailableOutputDevices.
6296 if (availProfileDevices.isEmpty()) {
6297 continue;
6298 }
6299 supportedDevice = availProfileDevices.itemAt(0);
6300 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006301 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006302 continue;
6303 }
6304 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6305 mpClientInterface);
6306 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006307 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6308 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006309 AUDIO_STREAM_DEFAULT,
6310 AUDIO_OUTPUT_FLAG_NONE, &output);
6311 if (status != NO_ERROR) {
6312 ALOGW("Cannot open output stream for devices %s on hw module %s",
6313 supportedDevice->toString().c_str(), hwModule->getName());
6314 continue;
6315 }
6316 for (const auto &device : availProfileDevices) {
6317 // give a valid ID to an attached device once confirmed it is reachable
6318 if (!device->isAttached()) {
6319 device->attach(hwModule);
6320 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006321 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006322 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006323 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6324 }
6325 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006326 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006327 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6328 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006329 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006330 }
Eric Laurent39095982021-08-24 18:29:27 +02006331 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006332 outputDesc->close();
6333 } else {
6334 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306335 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006336 DeviceVector(supportedDevice),
6337 true,
6338 0,
6339 NULL);
6340 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006341 }
6342 // open input streams needed to access attached devices to validate
6343 // mAvailableInputDevices list
6344 for (const auto& inProfile : hwModule->getInputProfiles()) {
6345 if (!inProfile->canOpenNewIo()) {
6346 ALOGE("Invalid Input profile max open count %u for profile %s",
6347 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6348 continue;
6349 }
6350 if (!inProfile->hasSupportedDevices()) {
6351 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6352 continue;
6353 }
6354 // chose first device present in profile's SupportedDevices also part of
6355 // available input devices
6356 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006357 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006358 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006359 ALOGV("%s: Input device list is empty! for profile %s",
6360 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006361 continue;
6362 }
6363 sp<AudioInputDescriptor> inputDesc =
6364 new AudioInputDescriptor(inProfile, mpClientInterface);
6365
6366 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6367 status_t status = inputDesc->open(nullptr,
6368 availProfileDevices.itemAt(0),
6369 AUDIO_SOURCE_MIC,
6370 AUDIO_INPUT_FLAG_NONE,
6371 &input);
6372 if (status != NO_ERROR) {
6373 ALOGW("Cannot open input stream for device %s on hw module %s",
6374 availProfileDevices.toString().c_str(),
6375 hwModule->getName());
6376 continue;
6377 }
6378 for (const auto &device : availProfileDevices) {
6379 // give a valid ID to an attached device once confirmed it is reachable
6380 if (!device->isAttached()) {
6381 device->attach(hwModule);
6382 device->importAudioPortAndPickAudioProfile(inProfile, true);
6383 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006384 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006385 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6386 }
6387 }
6388 inputDesc->close();
6389 }
6390 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006391
6392 // Check if spatializer outputs can be closed until used.
6393 // mOutputs vector never contains duplicated outputs at this point.
6394 std::vector<audio_io_handle_t> outputsClosed;
6395 for (size_t i = 0; i < mOutputs.size(); i++) {
6396 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6397 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6398 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6399 outputsClosed.push_back(desc->mIoHandle);
6400 desc->close();
6401 }
6402 }
6403 for (auto output : outputsClosed) {
6404 removeOutput(output);
6405 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006406}
6407
Eric Laurent98e38192018-02-15 18:31:53 -08006408void AudioPolicyManager::addOutput(audio_io_handle_t output,
6409 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006410{
Eric Laurent1c333e22014-05-20 10:48:17 -07006411 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006412 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006413 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006414 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006415 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006416}
6417
François Gaffie53615e22015-03-19 09:24:12 +01006418void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6419{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006420 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6421 ALOGV("%s: removing primary output", __func__);
6422 mPrimaryOutput = nullptr;
6423 }
François Gaffie53615e22015-03-19 09:24:12 +01006424 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006425 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006426}
6427
Eric Laurent98e38192018-02-15 18:31:53 -08006428void AudioPolicyManager::addInput(audio_io_handle_t input,
6429 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006430{
Eric Laurent1c333e22014-05-20 10:48:17 -07006431 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006432 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006433}
Eric Laurente552edb2014-03-10 17:42:56 -07006434
François Gaffie11d30102018-11-02 16:09:09 +01006435status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006436 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006437 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006438{
François Gaffie11d30102018-11-02 16:09:09 +01006439 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006440 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006441 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006442
François Gaffie11d30102018-11-02 16:09:09 +01006443 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006444 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006445 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006446 }
Eric Laurente552edb2014-03-10 17:42:56 -07006447
Eric Laurent3b73df72014-03-11 09:06:29 -07006448 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006449 // first call getAudioPort to get the supported attributes from the HAL
6450 struct audio_port_v7 port = {};
6451 device->toAudioPort(&port);
6452 status_t status = mpClientInterface->getAudioPort(&port);
6453 if (status == NO_ERROR) {
6454 device->importAudioPort(port);
6455 }
6456
6457 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006458 for (size_t i = 0; i < mOutputs.size(); i++) {
6459 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006460 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006461 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006462 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6463 mOutputs.keyAt(i), device->toString().c_str());
6464 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006465 }
6466 }
6467 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006468 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006469 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006470 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6471 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006472 if (profile->supportsDevice(device)) {
6473 profiles.add(profile);
6474 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6475 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006476 }
6477 }
6478 }
6479
Eric Laurent7b279bb2015-12-14 10:18:23 -08006480 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006481
Eric Laurente552edb2014-03-10 17:42:56 -07006482 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006483 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006484 return BAD_VALUE;
6485 }
6486
6487 // open outputs for matching profiles if needed. Direct outputs are also opened to
6488 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6489 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006490 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006491
6492 // nothing to do if one output is already opened for this profile
6493 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006494 for (j = 0; j < outputs.size(); j++) {
6495 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006496 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006497 // matching profile: save the sample rates, format and channel masks supported
6498 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006499 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006500 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006501 }
Eric Laurente552edb2014-03-10 17:42:56 -07006502 break;
6503 }
6504 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006505 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006506 continue;
6507 }
6508
Eric Laurent3974e3b2017-12-07 17:58:43 -08006509 if (!profile->canOpenNewIo()) {
6510 ALOGW("Max Output number %u already opened for this profile %s",
6511 profile->maxOpenCount, profile->getTagName().c_str());
6512 continue;
6513 }
6514
Eric Laurent83efe1c2017-07-09 16:51:08 -07006515 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006516 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006517 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6518 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006519 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006520 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006521 profiles.removeAt(profile_index);
6522 profile_index--;
6523 } else {
6524 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006525 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006526 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006527 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6528 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006529 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006530 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006531
François Gaffie11d30102018-11-02 16:09:09 +01006532 if (device_distinguishes_on_address(deviceType)) {
6533 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6534 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306535 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6536 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006537 }
Eric Laurente552edb2014-03-10 17:42:56 -07006538 ALOGV("checkOutputsForDevice(): adding output %d", output);
6539 }
6540 }
6541
6542 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006543 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006544 return BAD_VALUE;
6545 }
Eric Laurentd4692962014-05-05 18:13:44 -07006546 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006547 // check if one opened output is not needed any more after disconnecting one device
6548 for (size_t i = 0; i < mOutputs.size(); i++) {
6549 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006550 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006551 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006552 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006553 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006554 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006555 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006556 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6557 mOutputs.keyAt(i));
6558 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006559 }
Eric Laurente552edb2014-03-10 17:42:56 -07006560 }
6561 }
Eric Laurentd4692962014-05-05 18:13:44 -07006562 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006563 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006564 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6565 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006566 if (!profile->supportsDevice(device)) {
6567 continue;
6568 }
6569 ALOGV("checkOutputsForDevice(): "
6570 "clearing direct output profile %zu on module %s",
6571 j, hwModule->getName());
6572 profile->clearAudioProfiles();
6573 if (!profile->hasDynamicAudioProfile()) {
6574 continue;
6575 }
6576 // When a device is disconnected, if there is an IOProfile that contains dynamic
6577 // profiles and supports the disconnected device, call getAudioPort to repopulate
6578 // the capabilities of the devices that is supported by the IOProfile.
6579 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6580 if (supportedDevice == device ||
6581 !mAvailableOutputDevices.contains(supportedDevice)) {
6582 continue;
6583 }
6584 struct audio_port_v7 port;
6585 supportedDevice->toAudioPort(&port);
6586 status_t status = mpClientInterface->getAudioPort(&port);
6587 if (status == NO_ERROR) {
6588 supportedDevice->importAudioPort(port);
6589 }
Eric Laurente552edb2014-03-10 17:42:56 -07006590 }
6591 }
6592 }
6593 }
6594 return NO_ERROR;
6595}
6596
François Gaffie11d30102018-11-02 16:09:09 +01006597status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006598 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006599{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006600 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006601
François Gaffie11d30102018-11-02 16:09:09 +01006602 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006603 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006604 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006605 }
6606
Eric Laurentd4692962014-05-05 18:13:44 -07006607 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006608 // first call getAudioPort to get the supported attributes from the HAL
6609 struct audio_port_v7 port = {};
6610 device->toAudioPort(&port);
6611 status_t status = mpClientInterface->getAudioPort(&port);
6612 if (status == NO_ERROR) {
6613 device->importAudioPort(port);
6614 }
6615
Eric Laurent0dd51852019-04-19 18:18:58 -07006616 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006617 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006618 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006619 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006620 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006621 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006622 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006623
François Gaffie11d30102018-11-02 16:09:09 +01006624 if (profile->supportsDevice(device)) {
6625 profiles.add(profile);
6626 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6627 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006628 }
6629 }
6630 }
6631
Eric Laurent0dd51852019-04-19 18:18:58 -07006632 if (profiles.isEmpty()) {
6633 ALOGW("%s: No input profile available for device %s",
6634 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006635 return BAD_VALUE;
6636 }
6637
6638 // open inputs for matching profiles if needed. Direct inputs are also opened to
6639 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6640 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6641
Eric Laurent1c333e22014-05-20 10:48:17 -07006642 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006643
Eric Laurentd4692962014-05-05 18:13:44 -07006644 // nothing to do if one input is already opened for this profile
6645 size_t input_index;
6646 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6647 desc = mInputs.valueAt(input_index);
6648 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006649 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006650 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006651 }
Eric Laurentd4692962014-05-05 18:13:44 -07006652 break;
6653 }
6654 }
6655 if (input_index != mInputs.size()) {
6656 continue;
6657 }
6658
Eric Laurent3974e3b2017-12-07 17:58:43 -08006659 if (!profile->canOpenNewIo()) {
6660 ALOGW("Max Input number %u already opened for this profile %s",
6661 profile->maxOpenCount, profile->getTagName().c_str());
6662 continue;
6663 }
6664
Eric Laurentfe231122017-11-17 17:48:06 -08006665 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006666 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006667 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006668
Eric Laurentcf2c0212014-07-25 16:20:43 -07006669 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006670 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006671 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006672 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006673 mpClientInterface->setParameters(input, String8(param));
6674 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006675 }
jiabin12537fc2023-10-12 17:56:08 +00006676 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006677 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006678 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006679 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006680 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006681 }
6682
Eric Laurent0dd51852019-04-19 18:18:58 -07006683 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006684 addInput(input, desc);
6685 }
6686 } // endif input != 0
6687
Eric Laurentcf2c0212014-07-25 16:20:43 -07006688 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006689 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006690 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006691 profiles.removeAt(profile_index);
6692 profile_index--;
6693 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006694 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006695 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006696 }
Eric Laurentd4692962014-05-05 18:13:44 -07006697 ALOGV("checkInputsForDevice(): adding input %d", input);
6698 }
6699 } // end scan profiles
6700
6701 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006702 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006703 return BAD_VALUE;
6704 }
6705 } else {
6706 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006707 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006708 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006709 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006710 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006711 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006712 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006713 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006714 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6715 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006716 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006717 }
6718 }
6719 }
6720 } // end disconnect
6721
6722 return NO_ERROR;
6723}
6724
6725
Eric Laurente0720872014-03-11 09:30:41 -07006726void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006727{
6728 ALOGV("closeOutput(%d)", output);
6729
François Gaffie1c878552018-11-22 16:53:21 +01006730 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6731 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006732 ALOGW("closeOutput() unknown output %d", output);
6733 return;
6734 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006735 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006736 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006737
Eric Laurente552edb2014-03-10 17:42:56 -07006738 // look for duplicated outputs connected to the output being removed.
6739 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006740 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6741 if (dupOutput->isDuplicated() &&
6742 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6743 sp<SwAudioOutputDescriptor> remainingOutput =
6744 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006745 // As all active tracks on duplicated output will be deleted,
6746 // and as they were also referenced on the other output, the reference
6747 // count for their stream type must be adjusted accordingly on
6748 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006749 const bool wasActive = remainingOutput->isActive();
6750 // Note: no-op on the closing output where all clients has already been set inactive
6751 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006752 // stop() will be a no op if the output is still active but is needed in case all
6753 // active streams refcounts where cleared above
6754 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006755 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006756 }
Eric Laurente552edb2014-03-10 17:42:56 -07006757 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6758 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6759
6760 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006761 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006762 }
6763 }
6764
Eric Laurent05b90f82014-08-27 15:32:29 -07006765 nextAudioPortGeneration();
6766
François Gaffie1c878552018-11-22 16:53:21 +01006767 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006768 if (index >= 0) {
6769 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006770 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6771 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006772 mAudioPatches.removeItemsAt(index);
6773 mpClientInterface->onAudioPatchListUpdate();
6774 }
6775
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006776 if (closingOutputWasActive) {
6777 closingOutput->stop();
6778 }
François Gaffie1c878552018-11-22 16:53:21 +01006779 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006780
François Gaffie53615e22015-03-19 09:24:12 +01006781 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006782 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006783 if (closingOutput == mSpatializerOutput) {
6784 mSpatializerOutput.clear();
6785 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006786
6787 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6788 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006789 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006790 bool directOutputOpen = false;
6791 for (size_t i = 0; i < mOutputs.size(); i++) {
6792 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6793 directOutputOpen = true;
6794 break;
6795 }
6796 }
6797 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006798 ALOGV("no direct outputs open, reset MSD patches");
6799 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6800 // how output devices for patching are resolved. Avoid by caching and reusing the
6801 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6802 // devices to patch to. This may be complicated by the fact that devices may become
6803 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006804 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006805 }
6806 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006807}
6808
6809void AudioPolicyManager::closeInput(audio_io_handle_t input)
6810{
6811 ALOGV("closeInput(%d)", input);
6812
6813 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6814 if (inputDesc == NULL) {
6815 ALOGW("closeInput() unknown input %d", input);
6816 return;
6817 }
6818
Eric Laurent6a94d692014-05-20 11:18:06 -07006819 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006820
François Gaffie11d30102018-11-02 16:09:09 +01006821 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006822 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006823 if (index >= 0) {
6824 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006825 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6826 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006827 mAudioPatches.removeItemsAt(index);
6828 mpClientInterface->onAudioPatchListUpdate();
6829 }
6830
François Gaffie6ebbce02023-07-19 13:27:53 +02006831 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006832 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006833 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006834
François Gaffie11d30102018-11-02 16:09:09 +01006835 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6836 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006837 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006838 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006839 }
Eric Laurente552edb2014-03-10 17:42:56 -07006840}
6841
François Gaffie11d30102018-11-02 16:09:09 +01006842SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6843 const DeviceVector &devices,
6844 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006845{
6846 SortedVector<audio_io_handle_t> outputs;
6847
François Gaffie11d30102018-11-02 16:09:09 +01006848 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006849 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006850 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006851 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006852 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006853 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006854 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006855 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006856 outputs.add(openOutputs.keyAt(i));
6857 }
6858 }
6859 return outputs;
6860}
6861
Mikhail Naganov37977152018-07-11 15:54:44 -07006862void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6863{
6864 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6865 // output is suspended before any tracks are moved to it
6866 checkA2dpSuspend();
6867 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006868 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006869 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006870 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006871 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006872 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6873 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6874 // configuration changes will ultimately be rerouted correctly. We can still avoid
6875 // unnecessary rerouting by caching and reusing the arguments to
6876 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6877 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006878 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006879 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006880 // an event that changed routing likely occurred, inform upper layers
6881 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006882}
6883
François Gaffiec005e562018-11-06 15:04:49 +01006884bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6885 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006886{
François Gaffiec005e562018-11-06 15:04:49 +01006887 return mEngine->getProductStrategyForAttributes(lAttr) ==
6888 mEngine->getProductStrategyForAttributes(rAttr);
6889}
6890
Francois Gaffieff1eb522020-05-06 18:37:04 +02006891void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6892{
6893 for (size_t i = 0; i < mAudioSources.size(); i++) {
6894 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6895 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006896 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006897 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006898 connectAudioSource(sourceDesc);
6899 }
6900 }
6901}
6902
6903void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6904{
6905 for (size_t i = 0; i < mAudioSources.size(); i++) {
6906 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6907 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6908 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6909 disconnectAudioSource(sourceDesc);
6910 }
6911 }
6912}
6913
François Gaffiec005e562018-11-06 15:04:49 +01006914void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6915{
6916 auto psId = mEngine->getProductStrategyForAttributes(attr);
6917
6918 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6919 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006920
François Gaffie11d30102018-11-02 16:09:09 +01006921 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6922 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006923
Eric Laurentc209fe42020-06-05 18:11:23 -07006924 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006925 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006926 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006927 // take into account dynamic audio policies related changes: if a client is now associated
6928 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006929 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006930 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6931 if (desc->isDuplicated()) {
6932 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006933 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006934 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6935 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6936 continue;
6937 }
6938 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006939 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006940 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6941 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6942 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006943 if (status != OK) {
6944 continue;
6945 }
yucliuf4de36d2020-09-14 14:57:56 -07006946 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006947 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006948 maxLatency = desc->latency();
6949 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006950 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006951 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006952 }
6953 }
6954
Eric Laurent56ed8842022-11-15 16:04:41 +01006955 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006956 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6957 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006958 for (audio_io_handle_t srcOut : srcOutputs) {
6959 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006960 if (desc == nullptr) continue;
6961
6962 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006963 maxLatency = desc->latency();
6964 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006965
Eric Laurent56ed8842022-11-15 16:04:41 +01006966 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006967 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006968 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006969 // a client on a non direct outputs has necessarily a linear PCM format
6970 // so we can call selectOutput() safely
6971 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6972 client->flags(),
6973 client->config().format,
6974 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006975 client->config().sample_rate,
6976 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006977 if (newOutput != srcOut) {
6978 invalidate = true;
6979 break;
6980 }
6981 } else {
6982 sp<IOProfile> profile = getProfileForOutput(newDevices,
6983 client->config().sample_rate,
6984 client->config().format,
6985 client->config().channel_mask,
6986 client->flags(),
6987 true /* directOnly */);
6988 if (profile != desc->mProfile) {
6989 invalidate = true;
6990 break;
6991 }
6992 }
6993 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006994 // mute strategy while moving tracks from one output to another
6995 if (invalidate) {
6996 invalidatedOutputs.push_back(desc);
6997 if (desc->isStrategyActive(psId)) {
6998 setStrategyMute(psId, true, desc);
6999 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7000 newDevices.types());
7001 }
Eric Laurente552edb2014-03-10 17:42:56 -07007002 }
François Gaffiec005e562018-11-06 15:04:49 +01007003 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007004 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007005 connectAudioSource(source);
7006 }
Eric Laurente552edb2014-03-10 17:42:56 -07007007 }
7008
Eric Laurent56ed8842022-11-15 16:04:41 +01007009 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7010 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7011 std::to_string(srcOutputs[0]).c_str(),
7012 std::to_string(dstOutputs[0]).c_str());
7013
François Gaffiec005e562018-11-06 15:04:49 +01007014 // Move effects associated to this stream from previous output to new output
7015 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007016 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007017 }
François Gaffiec005e562018-11-06 15:04:49 +01007018 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007019 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007020 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007021 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007022 desc->setTracksInvalidatedStatusByStrategy(psId);
7023 }
Eric Laurente552edb2014-03-10 17:42:56 -07007024 }
7025 }
7026}
7027
Eric Laurente0720872014-03-11 09:30:41 -07007028void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007029{
François Gaffiec005e562018-11-06 15:04:49 +01007030 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7031 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7032 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007033 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007034 }
Eric Laurente552edb2014-03-10 17:42:56 -07007035}
7036
Kevin Rocard153f92d2018-12-18 18:33:28 -08007037void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007038 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007039 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007040 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007041 for (size_t i = 0; i < mOutputs.size(); i++) {
7042 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7043 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007044 sp<AudioPolicyMix> primaryMix;
7045 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007046 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007047 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7048 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7049 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007050 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7051 for (auto &secondaryMix : secondaryMixes) {
7052 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7053 if (outputDesc != nullptr &&
7054 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7055 secondaryDescs.push_back(outputDesc);
7056 }
7057 }
7058
jiabinc44b3462022-12-08 12:52:31 -08007059 if (status != OK &&
7060 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7061 // When it failed to query secondary output, only invalidate the client that is not
7062 // MMAP. The reason is that MMAP stream will not support secondary output.
7063 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007064 } else if (!std::equal(
7065 client->getSecondaryOutputs().begin(),
7066 client->getSecondaryOutputs().end(),
7067 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007068 if (!audio_is_linear_pcm(client->config().format)) {
7069 // If the format is not PCM, the tracks should be invalidated to get correct
7070 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007071 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007072 } else {
7073 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7074 std::vector<audio_io_handle_t> secondaryOutputIds;
7075 for (const auto &secondaryDesc: secondaryDescs) {
7076 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7077 weakSecondaryDescs.push_back(secondaryDesc);
7078 }
7079 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7080 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007081 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007082 }
7083 }
7084 }
jiabin10a03f12021-05-07 23:46:28 +00007085 if (!trackSecondaryOutputs.empty()) {
7086 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7087 }
jiabinc44b3462022-12-08 12:52:31 -08007088 if (!clientsToInvalidate.empty()) {
7089 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7090 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007091 }
7092}
7093
Eric Laurent2517af32020-11-25 15:31:27 +01007094bool AudioPolicyManager::isScoRequestedForComm() const {
7095 AudioDeviceTypeAddrVector devices;
7096 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7097 for (const auto &device : devices) {
7098 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7099 return true;
7100 }
7101 }
7102 return false;
7103}
7104
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007105bool AudioPolicyManager::isHearingAidUsedForComm() const {
7106 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7107 true /*fromCache*/);
7108 for (const auto &device : devices) {
7109 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7110 return true;
7111 }
7112 }
7113 return false;
7114}
7115
7116
Eric Laurente0720872014-03-11 09:30:41 -07007117void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007118{
François Gaffie53615e22015-03-19 09:24:12 +01007119 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007120 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007121 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007122 return;
7123 }
7124
Eric Laurent3a4311c2014-03-17 12:00:47 -07007125 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007126 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7127 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007128 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007129
7130 // if suspended, restore A2DP output if:
7131 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007132 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007133 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007134 //
Eric Laurentf732e072016-08-03 19:30:28 -07007135 // if not suspended, suspend A2DP output if:
7136 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007137 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007138 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007139 //
7140 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007141 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007142 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007143 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007144 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007145
7146 mpClientInterface->restoreOutput(a2dpOutput);
7147 mA2dpSuspended = false;
7148 }
7149 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007150 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007151 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007152 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007153 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007154
7155 mpClientInterface->suspendOutput(a2dpOutput);
7156 mA2dpSuspended = true;
7157 }
7158 }
7159}
7160
François Gaffie11d30102018-11-02 16:09:09 +01007161DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7162 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007163{
François Gaffiedb1755b2023-09-01 11:50:35 +02007164 if (outputDesc == nullptr) {
7165 return DeviceVector{};
7166 }
François Gaffie11d30102018-11-02 16:09:09 +01007167
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007168 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007169 if (index >= 0) {
7170 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007171 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007172 ALOGV("%s device %s forced by patch %d", __func__,
7173 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7174 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007175 }
7176 }
7177
Dean Wheatley514b4312020-06-17 21:45:00 +10007178 // Do not retrieve engine device for outputs through MSD
7179 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7180 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7181 return outputDesc->devices();
7182 }
7183
Eric Laurent97ac8712018-07-27 18:59:02 -07007184 // Honor explicit routing requests only if no client using default routing is active on this
7185 // input: a specific app can not force routing for other apps by setting a preferred device.
7186 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007187 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007188 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007189 if (device != nullptr) {
7190 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007191 }
7192
François Gaffiea807ef92018-11-05 10:44:33 +01007193 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7194 // of setForceUse / Default Bus device here
7195 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7196 if (device != nullptr) {
7197 return DeviceVector(device);
7198 }
7199
François Gaffiedb1755b2023-09-01 11:50:35 +02007200 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007201 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7202 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307203 auto hasStreamActive = [&](auto stream) {
7204 return hasStream(streams, stream) && isStreamActive(stream, 0);
7205 };
Eric Laurent484e9272018-06-07 17:29:23 -07007206
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307207 auto doGetOutputDevicesForVoice = [&]() {
7208 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007209 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307210 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007211 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7212 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307213 };
7214
7215 // With low-latency playing on speaker, music on WFD, when the first low-latency
7216 // output is stopped, getNewOutputDevices checks for a product strategy
7217 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007218 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307219 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7220 // stream is associated to the output descriptor.
7221 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7222 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7223 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7224 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007225 // Retrieval of devices for voice DL is done on primary output profile, cannot
7226 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007227 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007228 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7229 break;
7230 }
Eric Laurente552edb2014-03-10 17:42:56 -07007231 }
François Gaffiec005e562018-11-06 15:04:49 +01007232 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007233 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007234}
7235
François Gaffie11d30102018-11-02 16:09:09 +01007236sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7237 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007238{
François Gaffie11d30102018-11-02 16:09:09 +01007239 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007240
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007241 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007242 if (index >= 0) {
7243 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007244 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007245 ALOGV("getNewInputDevice() device %s forced by patch %d",
7246 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7247 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007248 }
7249 }
7250
Eric Laurent97ac8712018-07-27 18:59:02 -07007251 // Honor explicit routing requests only if no client using default routing is active on this
7252 // input: a specific app can not force routing for other apps by setting a preferred device.
7253 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007254 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7255 if (device != nullptr) {
7256 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007257 }
7258
Eric Laurentdc95a252018-04-12 12:46:56 -07007259 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007260 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007261 audio_attributes_t attributes;
7262 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007263 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007264 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7265 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007266 attributes = topClient->attributes();
7267 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007268 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007269 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007270 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7271 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007272 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007273 }
7274
Francois Gaffie716e1432019-01-14 16:58:59 +01007275 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7276 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007277 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007278 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007279 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007280 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007281
Eric Laurente552edb2014-03-10 17:42:56 -07007282 return device;
7283}
7284
Eric Laurent794fde22016-03-11 09:50:45 -08007285bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7286 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007287 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007288}
7289
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007290status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007291 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007292 if (devices == nullptr) {
7293 return BAD_VALUE;
7294 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007295
Andy Hung6d23c0f2022-02-16 09:37:15 -08007296 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007297 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7298 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007299 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007300 for (const auto& device : curDevices) {
7301 devices->push_back(device->getDeviceTypeAddr());
7302 }
7303 return NO_ERROR;
7304}
7305
Eric Laurente0720872014-03-11 09:30:41 -07007306void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007307 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007308 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007309 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007310 updateDevicesAndOutputs();
7311 break;
7312 default:
7313 break;
7314 }
7315}
7316
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007317uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007318
7319 // skip beacon mute management if a dedicated TTS output is available
7320 if (mTtsOutputAvailable) {
7321 return 0;
7322 }
7323
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007324 switch(event) {
7325 case STARTING_OUTPUT:
7326 mBeaconMuteRefCount++;
7327 break;
7328 case STOPPING_OUTPUT:
7329 if (mBeaconMuteRefCount > 0) {
7330 mBeaconMuteRefCount--;
7331 }
7332 break;
7333 case STARTING_BEACON:
7334 mBeaconPlayingRefCount++;
7335 break;
7336 case STOPPING_BEACON:
7337 if (mBeaconPlayingRefCount > 0) {
7338 mBeaconPlayingRefCount--;
7339 }
7340 break;
7341 }
7342
7343 if (mBeaconMuteRefCount > 0) {
7344 // any playback causes beacon to be muted
7345 return setBeaconMute(true);
7346 } else {
7347 // no other playback: unmute when beacon starts playing, mute when it stops
7348 return setBeaconMute(mBeaconPlayingRefCount == 0);
7349 }
7350}
7351
7352uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7353 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7354 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7355 // keep track of muted state to avoid repeating mute/unmute operations
7356 if (mBeaconMuted != mute) {
7357 // mute/unmute AUDIO_STREAM_TTS on all outputs
7358 ALOGV("\t muting %d", mute);
7359 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007360 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7361 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7362 ALOGV("\t no tts volume source available");
7363 return 0;
7364 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007365 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007366 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007367 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007368 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007369 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007370 maxLatency = latency;
7371 }
7372 }
7373 mBeaconMuted = mute;
7374 return maxLatency;
7375 }
7376 return 0;
7377}
7378
Eric Laurente0720872014-03-11 09:30:41 -07007379void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007380{
François Gaffiec005e562018-11-06 15:04:49 +01007381 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007382 mPreviousOutputs = mOutputs;
7383}
7384
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007385uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007386 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007387 uint32_t delayMs)
7388{
7389 // mute/unmute strategies using an incompatible device combination
7390 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7391 // if unmuting, unmute only after the specified delay
7392 if (outputDesc->isDuplicated()) {
7393 return 0;
7394 }
7395
7396 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007397 DeviceVector devices = outputDesc->devices();
7398 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007399
François Gaffiec005e562018-11-06 15:04:49 +01007400 auto productStrategies = mEngine->getOrderedProductStrategies();
7401 for (const auto &productStrategy : productStrategies) {
7402 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7403 DeviceVector curDevices =
7404 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7405 curDevices = curDevices.filter(outputDesc->supportedDevices());
7406 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007407 bool doMute = false;
7408
François Gaffiec005e562018-11-06 15:04:49 +01007409 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007410 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007411 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7412 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007413 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007414 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007415 }
Eric Laurent99401132014-05-07 19:48:15 -07007416 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007417 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007418 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007419 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007420 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007421 continue;
7422 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307423 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007424 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7425 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7426 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007427 if (mute) {
7428 // FIXME: should not need to double latency if volume could be applied
7429 // immediately by the audioflinger mixer. We must account for the delay
7430 // between now and the next time the audioflinger thread for this output
7431 // will process a buffer (which corresponds to one buffer size,
7432 // usually 1/2 or 1/4 of the latency).
7433 if (muteWaitMs < desc->latency() * 2) {
7434 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007435 }
7436 }
7437 }
7438 }
7439 }
7440 }
7441
Eric Laurent99401132014-05-07 19:48:15 -07007442 // temporary mute output if device selection changes to avoid volume bursts due to
7443 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007444 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007445 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007446
Eric Laurentdc462862016-07-19 12:29:53 -07007447 if (muteWaitMs < tempMuteWaitMs) {
7448 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007449 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007450
7451 // If recommended duration is defined, replace temporary mute duration to avoid
7452 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7453 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7454 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7455 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7456 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7457
François Gaffieaaac0fd2018-11-22 17:56:39 +01007458 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7459 // make sure that we do not start the temporary mute period too early in case of
7460 // delayed device change
7461 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7462 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007463 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007464 }
7465 }
7466
Eric Laurente552edb2014-03-10 17:42:56 -07007467 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7468 if (muteWaitMs > delayMs) {
7469 muteWaitMs -= delayMs;
7470 usleep(muteWaitMs * 1000);
7471 return muteWaitMs;
7472 }
7473 return 0;
7474}
7475
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307476uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7477 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007478 const DeviceVector &devices,
7479 bool force,
7480 int delayMs,
7481 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007482 bool requiresMuteCheck, bool requiresVolumeCheck,
7483 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007484{
jiabin3ff8d7d2022-12-13 06:27:44 +00007485 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307486 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7487 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7488 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007489 uint32_t muteWaitMs;
7490
7491 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307492 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007493 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307494 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007495 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007496 return muteWaitMs;
7497 }
Eric Laurente552edb2014-03-10 17:42:56 -07007498
7499 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007500 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007501 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007502 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007503
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307504 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7505 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007506
7507 if (!filteredDevices.isEmpty()) {
7508 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007509 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007510
7511 // if the outputs are not materially active, there is no need to mute.
7512 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007513 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007514 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307515 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7516 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007517 muteWaitMs = 0;
7518 }
Eric Laurente552edb2014-03-10 17:42:56 -07007519
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007520 bool outputRouted = outputDesc->isRouted();
7521
Eric Laurent79ea9582020-06-11 18:49:24 -07007522 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7523 // output profile or if new device is not supported AND previous device(s) is(are) still
7524 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007525 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307526 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7527 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007528 // restore previous device after evaluating strategy mute state
7529 outputDesc->setDevices(prevDevices);
7530 return muteWaitMs;
7531 }
7532
Eric Laurente552edb2014-03-10 17:42:56 -07007533 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007534 // the requested device is AUDIO_DEVICE_NONE
7535 // OR the requested device is the same as current device
7536 // AND force is not specified
7537 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007538 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007539 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307540 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7541 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7542 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007543 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307544 ALOGV("%s %s setting same device on routed output, force apply volumes",
7545 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007546 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7547 }
Eric Laurente552edb2014-03-10 17:42:56 -07007548 return muteWaitMs;
7549 }
7550
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307551 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7552 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007553
Eric Laurente552edb2014-03-10 17:42:56 -07007554 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007555 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007556 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007557 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007558 PatchBuilder patchBuilder;
7559 patchBuilder.addSource(outputDesc);
7560 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7561 for (const auto &filteredDevice : filteredDevices) {
7562 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007563 }
7564
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007565 // Add half reported latency to delayMs when muteWaitMs is null in order
7566 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007567 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7568 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7569 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007570 }
Eric Laurente552edb2014-03-10 17:42:56 -07007571
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007572 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7573 if (!skipMuteDelay) {
7574 // update stream volumes according to new device
7575 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7576 }
Eric Laurente552edb2014-03-10 17:42:56 -07007577
7578 return muteWaitMs;
7579}
7580
Eric Laurentc75307b2015-03-17 15:29:32 -07007581status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007582 int delayMs,
7583 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007584{
Eric Laurent6a94d692014-05-20 11:18:06 -07007585 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007586 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7587 return INVALID_OPERATION;
7588 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007589 if (patchHandle) {
7590 index = mAudioPatches.indexOfKey(*patchHandle);
7591 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007592 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007593 }
7594 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007595 return INVALID_OPERATION;
7596 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007597 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007598 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007599 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007600 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007601 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007602 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007603 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007604 return status;
7605}
7606
7607status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007608 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007609 bool force,
7610 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007611{
7612 status_t status = NO_ERROR;
7613
Eric Laurent1f2f2232014-06-02 12:01:23 -07007614 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007615 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7616 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007617
François Gaffie11d30102018-11-02 16:09:09 +01007618 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007619 PatchBuilder patchBuilder;
7620 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007621 // AUDIO_SOURCE_HOTWORD is for internal use only:
7622 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007623 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7624 auto result = usecase;
7625 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7626 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7627 }
7628 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007629 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007630 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007631 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007632 }
7633 }
7634 return status;
7635}
7636
Eric Laurent6a94d692014-05-20 11:18:06 -07007637status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7638 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007639{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007640 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007641 ssize_t index;
7642 if (patchHandle) {
7643 index = mAudioPatches.indexOfKey(*patchHandle);
7644 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007645 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007646 }
7647 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007648 return INVALID_OPERATION;
7649 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007650 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007651 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007652 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007653 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007654 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007655 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007656 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007657 return status;
7658}
7659
François Gaffie11d30102018-11-02 16:09:09 +01007660sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007661 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007662 audio_format_t& format,
7663 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007664 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007665{
7666 // Choose an input profile based on the requested capture parameters: select the first available
7667 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007668 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007669 //
7670 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7671 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007672
Atneya Nair0f0a8032022-12-12 16:20:12 -08007673 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7674 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7675 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7676
7677 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007678
jiabin2fd710d2022-05-02 23:20:22 +00007679 for (;;) {
7680 sp<IOProfile> firstInexact = nullptr;
7681 uint32_t updatedSamplingRate = 0;
7682 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7683 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7684 for (const auto& hwModule : mHwModules) {
7685 for (const auto& profile : hwModule->getInputProfiles()) {
7686 // profile->log();
7687 //updatedFormat = format;
7688 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7689 &samplingRate /*updatedSamplingRate*/,
7690 format,
7691 &format, /*updatedFormat*/
7692 channelMask,
7693 &channelMask /*updatedChannelMask*/,
7694 // FIXME ugly cast
7695 (audio_output_flags_t) flags,
7696 true /*exactMatchRequiredForInputFlags*/)) {
7697 return profile;
7698 }
7699 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7700 samplingRate,
7701 &updatedSamplingRate,
7702 format,
7703 &updatedFormat,
7704 channelMask,
7705 &updatedChannelMask,
7706 // FIXME ugly cast
7707 (audio_output_flags_t) flags,
7708 false /*exactMatchRequiredForInputFlags*/)) {
7709 firstInexact = profile;
7710 }
7711 }
7712 }
7713
7714 if (firstInexact != nullptr) {
7715 samplingRate = updatedSamplingRate;
7716 format = updatedFormat;
7717 channelMask = updatedChannelMask;
7718 return firstInexact;
7719 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7720 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7721 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7722 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7723 flags = AUDIO_INPUT_FLAG_NONE;
7724 } else { // fail
7725 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7726 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7727 samplingRate, format, channelMask, oriFlags);
7728 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007729 }
7730 }
jiabin2fd710d2022-05-02 23:20:22 +00007731
7732 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007733}
7734
François Gaffieaaac0fd2018-11-22 17:56:39 +01007735float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7736 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007737 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007738 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007739{
jiabin9a3361e2019-10-01 09:38:30 -07007740 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007741
7742 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7743 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7744 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7745 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007746 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7747 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7748 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7749 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7750 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena5300db62023-08-30 18:45:18 -07007751 // Verify that the current volume source is not the ringer volume to prevent recursively
7752 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7753 // to the same volume group.
7754 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007755 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7756 mOutputs.isActive(ringVolumeSrc, 0)) {
7757 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007758 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007759 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007760 }
7761
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007762 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007763 if ((volumeSource != callVolumeSrc && (isInCall() ||
7764 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007765 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007766 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7767 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007768 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7769 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7770 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007771 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007772 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007773 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007774 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007775 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007776 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007777 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7778 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7779 // programmatically muted.
7780 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7781 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7782 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007783 bool exemptFromCapping =
7784 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7785 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007786 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7787 volumeSource, volumeDb);
7788 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007789 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7790 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7791 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007792 }
7793 }
Eric Laurente552edb2014-03-10 17:42:56 -07007794 // if a headset is connected, apply the following rules to ring tones and notifications
7795 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007796 // - always attenuate notifications volume by 6dB
7797 // - attenuate ring tones volume by 6dB unless music is not playing and
7798 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007799 // - if music is playing, always limit the volume to current music volume,
7800 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007801 if (!Intersection(deviceTypes,
7802 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7803 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007804 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7805 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007806 ((volumeSource == alarmVolumeSrc ||
7807 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007808 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7809 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7810 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007811 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7812 curves.canBeMuted()) {
7813
Eric Laurente552edb2014-03-10 17:42:56 -07007814 // when the phone is ringing we must consider that music could have been paused just before
7815 // by the music application and behave as if music was active if the last music track was
7816 // just stopped
Oscar Azucena5300db62023-08-30 18:45:18 -07007817 // Verify that the current volume source is not the music volume to prevent recursively
7818 // calling to compute volume. This could happen in cases where music and
7819 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7820 if (volumeSource != musicVolumeSrc &&
7821 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7822 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007823 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007824 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007825 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7826 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007827 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007828 float musicVolDb = computeVolume(musicCurves,
7829 musicVolumeSrc,
7830 musicCurves.getVolumeIndex(musicDevice),
7831 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007832 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7833 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7834 if (volumeDb > minVolDb) {
7835 volumeDb = minVolDb;
7836 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007837 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007838 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7839 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7840 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007841 // on A2DP, also ensure notification volume is not too low compared to media when
7842 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007843 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007844 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007845 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7846 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007847 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7848 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007849 }
7850 }
jiabin9a3361e2019-10-01 09:38:30 -07007851 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007852 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007853 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007854 }
7855 }
7856
François Gaffie43c73442018-11-08 08:21:55 +01007857 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007858}
7859
Eric Laurent3839bc02018-07-10 18:33:34 -07007860int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007861 VolumeSource fromVolumeSource,
7862 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007863{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007864 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007865 return srcIndex;
7866 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007867 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7868 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007869 float minSrc = (float)srcCurves.getVolumeIndexMin();
7870 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7871 float minDst = (float)dstCurves.getVolumeIndexMin();
7872 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007873
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007874 // preserve mute request or correct range
7875 if (srcIndex < minSrc) {
7876 if (srcIndex == 0) {
7877 return 0;
7878 }
7879 srcIndex = minSrc;
7880 } else if (srcIndex > maxSrc) {
7881 srcIndex = maxSrc;
7882 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007883 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7884}
7885
François Gaffieaaac0fd2018-11-22 17:56:39 +01007886status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7887 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007888 int index,
7889 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007890 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007891 int delayMs,
7892 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007893{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007894 // do not change actual attributes volume if the attributes is muted
7895 if (outputDesc->isMuted(volumeSource)) {
7896 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7897 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007898 return NO_ERROR;
7899 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007900
Eric Laurent5baf07c2024-01-11 16:57:27 +00007901 bool isVoiceVolSrc;
7902 bool isBtScoVolSrc;
7903 if (!isVolumeConsistentForCalls(
7904 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07007905 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00007906 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07007907 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007908 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00007909
jiabin9a3361e2019-10-01 09:38:30 -07007910 if (deviceTypes.empty()) {
7911 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007912 index = curves.getVolumeIndex(deviceTypes);
7913 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7914 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007915 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007916
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007917 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7918 ALOGE("invalid volume index range");
7919 return BAD_VALUE;
7920 }
7921
jiabin9a3361e2019-10-01 09:38:30 -07007922 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7923 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007924 // Force VoIP volume to max for bluetooth SCO device except if muted
7925 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007926 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007927 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007928 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007929 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007930 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7931 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007932
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007933 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00007934 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007935 }
Eric Laurente552edb2014-03-10 17:42:56 -07007936 return NO_ERROR;
7937}
7938
Eric Laurent5baf07c2024-01-11 16:57:27 +00007939void AudioPolicyManager::setVoiceVolume(
7940 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
7941 float voiceVolume;
7942 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
7943 // by the headset
7944 if (isVoiceVolSrc) {
7945 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
7946 } else {
7947 voiceVolume = index == 0 ? 0.0 : 1.0;
7948 }
7949 if (voiceVolume != mLastVoiceVolume) {
7950 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7951 mLastVoiceVolume = voiceVolume;
7952 }
7953}
7954
7955bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
7956 const DeviceTypeSet& deviceTypes,
7957 bool& isVoiceVolSrc,
7958 bool& isBtScoVolSrc,
7959 const char* caller) {
7960 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7961 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7962 const bool isScoRequested = isScoRequestedForComm();
7963 const bool isHAUsed = isHearingAidUsedForComm();
7964
7965 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7966 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
7967
7968 if ((callVolSrc != btScoVolSrc) &&
7969 ((isVoiceVolSrc && isScoRequested) ||
7970 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7971 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
7972 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
7973 volumeSource, isScoRequested ? " " : " not ");
7974 return false;
7975 }
7976 return true;
7977}
7978
Eric Laurentc75307b2015-03-17 15:29:32 -07007979void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007980 const DeviceTypeSet& deviceTypes,
7981 int delayMs,
7982 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007983{
jiabincd510522020-01-22 09:40:55 -08007984 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007985 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7986 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7987 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007988 curves.getVolumeIndex(deviceTypes),
7989 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007990 }
7991}
7992
François Gaffiec005e562018-11-06 15:04:49 +01007993void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7994 bool on,
7995 const sp<AudioOutputDescriptor>& outputDesc,
7996 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007997 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007998{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007999 std::vector<VolumeSource> sourcesToMute;
8000 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8001 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8002 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008003 VolumeSource source = toVolumeSource(attributes, false);
8004 if ((source != VOLUME_SOURCE_NONE) &&
8005 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8006 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008007 sourcesToMute.push_back(source);
8008 }
Eric Laurente552edb2014-03-10 17:42:56 -07008009 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008010 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008011 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008012 }
8013
Eric Laurente552edb2014-03-10 17:42:56 -07008014}
8015
François Gaffieaaac0fd2018-11-22 17:56:39 +01008016void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8017 bool on,
8018 const sp<AudioOutputDescriptor>& outputDesc,
8019 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008020 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008021{
jiabin9a3361e2019-10-01 09:38:30 -07008022 if (deviceTypes.empty()) {
8023 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008024 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008025 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008026 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008027 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008028 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008029 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008030 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8031 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008032 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008033 }
8034 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008035 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8036 // ignored
8037 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008038 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008039 if (!outputDesc->isMuted(volumeSource)) {
8040 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008041 return;
8042 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008043 if (outputDesc->decMuteCount(volumeSource) == 0) {
8044 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008045 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008046 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008047 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008048 delayMs);
8049 }
8050 }
8051}
8052
François Gaffie53615e22015-03-19 09:24:12 +01008053bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8054{
François Gaffiec005e562018-11-06 15:04:49 +01008055 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008056 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8057 return true;
8058 }
8059
8060 // has known usage?
8061 switch (paa->usage) {
8062 case AUDIO_USAGE_UNKNOWN:
8063 case AUDIO_USAGE_MEDIA:
8064 case AUDIO_USAGE_VOICE_COMMUNICATION:
8065 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8066 case AUDIO_USAGE_ALARM:
8067 case AUDIO_USAGE_NOTIFICATION:
8068 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8069 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8070 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8071 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8072 case AUDIO_USAGE_NOTIFICATION_EVENT:
8073 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8074 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8075 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8076 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008077 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008078 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008079 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008080 case AUDIO_USAGE_EMERGENCY:
8081 case AUDIO_USAGE_SAFETY:
8082 case AUDIO_USAGE_VEHICLE_STATUS:
8083 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008084 break;
8085 default:
8086 return false;
8087 }
8088 return true;
8089}
8090
François Gaffie2110e042015-03-24 08:41:51 +01008091audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8092{
8093 return mEngine->getForceUse(usage);
8094}
8095
Eric Laurent96d1dda2022-03-14 17:14:19 +01008096bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008097 return isStateInCall(mEngine->getPhoneState());
8098}
8099
Eric Laurent96d1dda2022-03-14 17:14:19 +01008100bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008101 return is_state_in_call(state);
8102}
8103
Eric Laurentf9cccec2022-11-16 19:12:00 +01008104bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008105 audio_mode_t mode = mEngine->getPhoneState();
8106 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008107 || (mode == AUDIO_MODE_CALL_SCREEN)
8108 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008109}
8110
Eric Laurentf9cccec2022-11-16 19:12:00 +01008111bool AudioPolicyManager::isInCallOrScreening() const {
8112 audio_mode_t mode = mEngine->getPhoneState();
8113 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8114}
8115
Eric Laurentd60560a2015-04-10 11:31:20 -07008116void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8117{
8118 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008119 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008120 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008121 sourceDesc->sinkDevice()->equals(deviceDesc))
8122 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008123 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008124 }
8125 }
8126
8127 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8128 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8129 bool release = false;
8130 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8131 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8132 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8133 source->ext.device.type == deviceDesc->type()) {
8134 release = true;
8135 }
8136 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008137 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008138 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8139 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8140 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008141 sink->ext.device.type == deviceDesc->type() &&
8142 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8143 || strncmp(sink->ext.device.address, address,
8144 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008145 release = true;
8146 }
8147 }
8148 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008149 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8150 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008151 }
8152 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008153
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008154 mInputs.clearSessionRoutesForDevice(deviceDesc);
8155
Francois Gaffie716e1432019-01-14 16:58:59 +01008156 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008157}
8158
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008159void AudioPolicyManager::modifySurroundFormats(
8160 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008161 std::unordered_set<audio_format_t> enforcedSurround(
8162 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008163 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008164 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008165 allSurround.insert(pair.first);
8166 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8167 }
Phil Burk09bc4612016-02-24 15:58:15 -08008168
8169 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8170 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008171 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008172 // This is the resulting set of formats depending on the surround mode:
8173 // 'all surround' = allSurround
8174 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8175 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8176 // 'manual surround' = mManualSurroundFormats
8177 // AUTO: formats v 'enforced surround'
8178 // ALWAYS: formats v 'all surround' v 'enforced surround'
8179 // NEVER: formats ^ 'non-surround'
8180 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008181
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008182 std::unordered_set<audio_format_t> formatSet;
8183 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8184 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008185 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008186 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008187 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008188 formatSet.insert(*formatIter);
8189 }
8190 }
8191 } else {
8192 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8193 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008194 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008195
jiabin81772902018-04-02 17:52:27 -07008196 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008197 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008198 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8199 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8200 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008201 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008202 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8203 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8204 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008205 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008206 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008207 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008208 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008209 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008210 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008211}
8212
jiabin06e4bab2019-07-29 10:13:34 -07008213void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8214 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008215 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8216 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8217
8218 // If NEVER, then remove support for channelMasks > stereo.
8219 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008220 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8221 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008222 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008223 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008224 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008225 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008226 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008227 }
8228 }
jiabin81772902018-04-02 17:52:27 -07008229 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8230 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8231 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008232 bool supports5dot1 = false;
8233 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008234 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008235 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8236 supports5dot1 = true;
8237 break;
8238 }
8239 }
8240 // If not then add 5.1 support.
8241 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008242 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008243 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008244 }
Phil Burk09bc4612016-02-24 15:58:15 -08008245 }
8246}
8247
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008248void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008249 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008250 const sp<IOProfile>& profile) {
8251 if (!profile->hasDynamicAudioProfile()) {
8252 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008253 }
François Gaffie112b0af2015-11-19 16:13:25 +01008254
jiabin12537fc2023-10-12 17:56:08 +00008255 audio_port_v7 devicePort;
8256 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008257
jiabin12537fc2023-10-12 17:56:08 +00008258 audio_port_v7 mixPort;
8259 profile->toAudioPort(&mixPort);
8260 mixPort.ext.mix.handle = ioHandle;
8261
8262 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8263 if (status != NO_ERROR) {
8264 ALOGE("%s failed to query the attributes of the mix port", __func__);
8265 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008266 }
jiabin12537fc2023-10-12 17:56:08 +00008267
8268 std::set<audio_format_t> supportedFormats;
8269 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8270 supportedFormats.insert(mixPort.audio_profiles[i].format);
8271 }
8272 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8273 mReportedFormatsMap[devDesc] = formats;
8274
8275 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8276 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8277 modifySurroundFormats(devDesc, &formats);
8278 size_t modifiedNumProfiles = 0;
8279 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8280 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8281 formats.end()) {
8282 // Skip the format that is not present after modifying surround formats.
8283 continue;
8284 }
8285 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8286 sizeof(struct audio_profile));
8287 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8288 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8289 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8290 modifySurroundChannelMasks(&channels);
8291 std::copy(channels.begin(), channels.end(),
8292 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8293 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8294 }
8295 mixPort.num_audio_profiles = modifiedNumProfiles;
8296 }
8297 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008298}
Eric Laurentd60560a2015-04-10 11:31:20 -07008299
Mikhail Naganovdc769682018-05-04 15:34:08 -07008300status_t AudioPolicyManager::installPatch(const char *caller,
8301 audio_patch_handle_t *patchHandle,
8302 AudioIODescriptorInterface *ioDescriptor,
8303 const struct audio_patch *patch,
8304 int delayMs)
8305{
8306 ssize_t index = mAudioPatches.indexOfKey(
8307 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8308 *patchHandle : ioDescriptor->getPatchHandle());
8309 sp<AudioPatch> patchDesc;
8310 status_t status = installPatch(
8311 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8312 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008313 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008314 }
8315 return status;
8316}
8317
8318status_t AudioPolicyManager::installPatch(const char *caller,
8319 ssize_t index,
8320 audio_patch_handle_t *patchHandle,
8321 const struct audio_patch *patch,
8322 int delayMs,
8323 uid_t uid,
8324 sp<AudioPatch> *patchDescPtr)
8325{
8326 sp<AudioPatch> patchDesc;
8327 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8328 if (index >= 0) {
8329 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008330 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008331 }
8332
8333 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8334 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8335 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8336 if (status == NO_ERROR) {
8337 if (index < 0) {
8338 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008339 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008340 } else {
8341 patchDesc->mPatch = *patch;
8342 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008343 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008344 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008345 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008346 }
8347 nextAudioPortGeneration();
8348 mpClientInterface->onAudioPatchListUpdate();
8349 }
8350 if (patchDescPtr) *patchDescPtr = patchDesc;
8351 return status;
8352}
8353
jiabinbce0c1d2020-10-05 11:20:18 -07008354bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8355{
8356 const TrackClientVector activeClients = output->getActiveClients();
8357 if (activeClients.empty()) {
8358 return true;
8359 }
8360 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8361 if (index < 0) {
8362 ALOGE("%s, no audio patch found while there are active clients on output %d",
8363 __func__, output->getId());
8364 return false;
8365 }
8366 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8367 DeviceVector routedDevices;
8368 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8369 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8370 patchDesc->mPatch.sinks[i].id);
8371 if (device == nullptr) {
8372 ALOGE("%s, no audio device found with id(%d)",
8373 __func__, patchDesc->mPatch.sinks[i].id);
8374 return false;
8375 }
8376 routedDevices.add(device);
8377 }
8378 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008379 if (client->isInvalid()) {
8380 // No need to take care about invalidated clients.
8381 continue;
8382 }
jiabinbce0c1d2020-10-05 11:20:18 -07008383 sp<DeviceDescriptor> preferredDevice =
8384 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8385 if (mEngine->getOutputDevicesForAttributes(
8386 client->attributes(), preferredDevice, false) == routedDevices) {
8387 return false;
8388 }
8389 }
8390 return true;
8391}
8392
8393sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008394 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008395 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8396 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008397{
8398 for (const auto& device : devices) {
8399 // TODO: This should be checking if the profile supports the device combo.
8400 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008401 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8402 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008403 return nullptr;
8404 }
8405 }
8406 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8407 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008408 status_t status = desc->open(halConfig, mixerConfig, devices,
8409 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008410 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008411 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008412 return nullptr;
8413 }
8414
8415 // Here is where the out_set_parameters() for card & device gets called
8416 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8417 const audio_devices_t deviceType = device->type();
8418 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008419 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008420 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8421 mpClientInterface->setParameters(output, String8(param));
8422 free(param);
8423 }
jiabin12537fc2023-10-12 17:56:08 +00008424 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008425 if (!profile->hasValidAudioProfile()) {
8426 ALOGW("%s() missing param", __func__);
8427 desc->close();
8428 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008429 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8430 // Reopen the output with the best audio profile picked by APM when the profile supports
8431 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008432 desc->close();
8433 output = AUDIO_IO_HANDLE_NONE;
8434 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8435 profile->pickAudioProfile(
8436 config.sample_rate, config.channel_mask, config.format);
8437 config.offload_info.sample_rate = config.sample_rate;
8438 config.offload_info.channel_mask = config.channel_mask;
8439 config.offload_info.format = config.format;
8440
jiabina84c3d32022-12-02 18:59:55 +00008441 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008442 if (status != NO_ERROR) {
8443 return nullptr;
8444 }
8445 }
8446
8447 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008448
baek.kim -61c20122022-07-27 10:05:32 +00008449 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8450 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8451
jiabinbce0c1d2020-10-05 11:20:18 -07008452 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8453 sp<AudioPolicyMix> policyMix;
8454 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8455 policyMix->setOutput(desc);
8456 desc->mPolicyMix = policyMix;
8457 } else {
8458 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008459 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008460 }
8461
baek.kim -61c20122022-07-27 10:05:32 +00008462 } else if (hasPrimaryOutput() && speaker != nullptr
8463 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008464 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8465 // no duplicated output for:
8466 // - direct outputs
8467 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008468 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008469 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8470
8471 //TODO: configure audio effect output stage here
8472
8473 // open a duplicating output thread for the new output and the primary output
8474 sp<SwAudioOutputDescriptor> dupOutputDesc =
8475 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8476 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8477 if (status == NO_ERROR) {
8478 // add duplicated output descriptor
8479 addOutput(duplicatedOutput, dupOutputDesc);
8480 } else {
8481 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8482 mPrimaryOutput->mIoHandle, output);
8483 desc->close();
8484 removeOutput(output);
8485 nextAudioPortGeneration();
8486 return nullptr;
8487 }
8488 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008489 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8490 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8491 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008492 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008493 }
jiabinbce0c1d2020-10-05 11:20:18 -07008494 return desc;
8495}
8496
jiabinf1c73972022-04-14 16:28:52 -07008497status_t AudioPolicyManager::getDevicesForAttributes(
8498 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8499 // Devices are determined in the following precedence:
8500 //
8501 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8502 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8503 //
8504 // If no such dynamic policy then
8505 // 2) Devices containing an active client using setPreferredDevice
8506 // with same strategy as the attributes.
8507 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8508 //
8509 // If no corresponding active client with setPreferredDevice then
8510 // 3) Devices associated with the strategy determined by the attributes
8511 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8512 //
8513 // See related getOutputForAttrInt().
8514
8515 // check dynamic policies but only for primary descriptors (secondary not used for audible
8516 // audio routing, only used for duplication for playback capture)
8517 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008518 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008519 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008520 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8521 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8522 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008523 if (status != OK) {
8524 return status;
8525 }
8526
8527 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8528 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8529 // as they are unaffected by device/stream volume
8530 // (per SwAudioOutputDescriptor::isFixedVolume()).
8531 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8532 ) {
8533 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8534 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8535 devices.add(deviceDesc);
8536 } else {
8537 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8538 // which selects setPreferredDevice if active. This means forVolume call
8539 // will take an active setPreferredDevice, if such exists.
8540
8541 devices = mEngine->getOutputDevicesForAttributes(
8542 attr, nullptr /* preferredDevice */, false /* fromCache */);
8543 }
8544
8545 if (forVolume) {
8546 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8547 // for single volume control in AudioService (such relationship should exist if
8548 // SPEAKER_SAFE is present).
8549 //
8550 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8551 DeviceVector speakerSafeDevices =
8552 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8553 if (!speakerSafeDevices.isEmpty()) {
8554 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8555 devices.remove(speakerSafeDevices);
8556 }
8557 }
8558
8559 return NO_ERROR;
8560}
8561
8562status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8563 AudioProfileVector& audioProfiles,
8564 uint32_t flags,
8565 bool isInput) {
8566 for (const auto& hwModule : mHwModules) {
8567 // the MSD module checks for different conditions
8568 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8569 continue;
8570 }
8571 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8572 : hwModule->getOutputProfiles();
8573 for (const auto& profile : ioProfiles) {
8574 if (!profile->areAllDevicesSupported(devices) ||
8575 !profile->isCompatibleProfileForFlags(
8576 flags, false /*exactMatchRequiredForInputFlags*/)) {
8577 continue;
8578 }
8579 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8580 }
8581 }
8582
8583 if (!isInput) {
8584 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8585 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8586 if (msdModule != nullptr) {
8587 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8588 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8589 for (const auto &profile: msdModule->getOutputProfiles()) {
8590 if (!profile->asAudioPort()->isDirectOutput()) {
8591 continue;
8592 }
8593 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8594 }
8595 } else {
8596 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8597 }
8598 }
8599 }
8600
8601 return NO_ERROR;
8602}
8603
jiabin3ff8d7d2022-12-13 06:27:44 +00008604sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8605 const audio_config_t *config,
8606 audio_output_flags_t flags,
8607 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008608 closeOutput(outputDesc->mIoHandle);
8609 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8610 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8611 if (preferredOutput == nullptr) {
8612 ALOGE("%s failed to reopen output device=%d, caller=%s",
8613 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008614 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008615 return preferredOutput;
8616}
8617
8618void AudioPolicyManager::reopenOutputsWithDevices(
8619 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8620 for (const auto& [output, devices] : outputsToReopen) {
8621 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8622 closeOutput(output);
8623 openOutputWithProfileAndDevice(desc->mProfile, devices);
8624 }
jiabina84c3d32022-12-02 18:59:55 +00008625}
8626
jiabinc44b3462022-12-08 12:52:31 -08008627PortHandleVector AudioPolicyManager::getClientsForStream(
8628 audio_stream_type_t streamType) const {
8629 PortHandleVector clients;
8630 for (size_t i = 0; i < mOutputs.size(); ++i) {
8631 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8632 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8633 }
8634 return clients;
8635}
8636
8637void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8638 PortHandleVector clients;
8639 for (auto stream : streams) {
8640 PortHandleVector clientsForStream = getClientsForStream(stream);
8641 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8642 }
8643 mpClientInterface->invalidateTracks(clients);
8644}
8645
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008646} // namespace android