blob: fad748f947a072048ea8abca048dfc75acdbb3ac [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
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080037#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110038#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070039
40#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010041#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070042#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070044#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070045#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070046#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070047#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070048#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070049#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <utils/Log.h>
51
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010053#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010057using android::media::audio::common::AudioDevice;
58using android::media::audio::common::AudioDeviceAddress;
59using android::media::audio::common::AudioPortDeviceExt;
60using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000061using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070062
Eric Laurentdc462862016-07-19 12:29:53 -070063//FIXME: workaround for truncated touch sounds
64// to be removed when the problem is handled by system UI
65#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070066
67// Largest difference in dB on earpiece in call between the voice volume and another
68// media / notification / system volume.
69constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
70
Mikhail Naganov15be9d22017-11-08 14:18:13 +110071// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110072static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
73 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110074 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
75// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110076static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110077 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
78 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
79 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
80
jiabin06e4bab2019-07-29 10:13:34 -070081template <typename T>
82bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
83{
84 if (left.size() != right.size()) {
85 return false;
86 }
87 for (size_t index = 0; index < right.size(); index++) {
88 if (left[index] != right[index]) {
89 return false;
90 }
91 }
92 return true;
93}
94
95template <typename T>
96bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
97{
98 return !(left == right);
99}
100
Eric Laurente552edb2014-03-10 17:42:56 -0700101// ----------------------------------------------------------------------------
102// AudioPolicyInterface implementation
103// ----------------------------------------------------------------------------
104
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100105status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
106 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
107 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800108 nextAudioPortGeneration();
109 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110}
111
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100112status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
113 audio_policy_dev_state_t state,
114 const char* device_address,
115 const char* device_name,
116 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800117 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100118 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
119 status == OK) {
120 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
121 } else {
122 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
123 return status;
124 }
125}
126
François Gaffie11d30102018-11-02 16:09:09 +0100127void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
128 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200129{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000130 audio_port_v7 devicePort;
131 device->toAudioPort(&devicePort);
132 if (status_t status = mpClientInterface->setDeviceConnectedState(
133 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
134 status != OK) {
135 ALOGE("Error %d while setting connected state for device %s", status,
136 device->getDeviceTypeAddr().toString(false).c_str());
137 }
François Gaffie44481e72016-04-20 07:49:57 +0200138}
139
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100140status_t AudioPolicyManager::setDeviceConnectionStateInt(
141 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
142 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100143 if (port.ext.getTag() != AudioPortExt::device) {
144 return BAD_VALUE;
145 }
146 audio_devices_t device_type;
147 std::string device_address;
148 if (status_t status = aidl2legacy_AudioDevice_audio_device(
149 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
150 status != OK) {
151 return status;
152 };
153 const char* device_name = port.name.c_str();
154 // connect/disconnect only 1 device at a time
155 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
156 return BAD_VALUE;
157
158 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
159 device_type, device_address.c_str(), device_name, encodedFormat,
160 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000161 if (device == nullptr) {
162 return INVALID_OPERATION;
163 }
164 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
165 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
166 }
167 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100168}
169
François Gaffie11d30102018-11-02 16:09:09 +0100170status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800171 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100172 const char* device_address,
173 const char* device_name,
174 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800175 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100176 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
177 status == OK) {
178 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
179 } else {
180 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
181 return status;
182 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183}
Paul McLeane743a472015-01-28 11:07:31 -0800184
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700185status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
186 audio_policy_dev_state_t state)
187{
Eric Laurente552edb2014-03-10 17:42:56 -0700188 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700189 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700190 SortedVector <audio_io_handle_t> outputs;
191
François Gaffie11d30102018-11-02 16:09:09 +0100192 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700193
Eric Laurente552edb2014-03-10 17:42:56 -0700194 // save a copy of the opened output descriptors before any output is opened or closed
195 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
196 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100197
198 bool wasLeUnicastActive = isLeUnicastActive();
199
Eric Laurente552edb2014-03-10 17:42:56 -0700200 switch (state)
201 {
202 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800203 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700204 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100205 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700206 return INVALID_OPERATION;
207 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800208 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700209 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700210
Eric Laurente552edb2014-03-10 17:42:56 -0700211 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200212 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700213 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700214 }
215
François Gaffie44481e72016-04-20 07:49:57 +0200216 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
217 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100218 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200219
François Gaffie11d30102018-11-02 16:09:09 +0100220 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
221 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200222
Francois Gaffie716e1432019-01-14 16:58:59 +0100223 mHwModules.cleanUpForDevice(device);
224
François Gaffie11d30102018-11-02 16:09:09 +0100225 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700226 return INVALID_OPERATION;
227 }
François Gaffie2110e042015-03-24 08:41:51 +0100228
jiabin1c4794b2020-05-05 10:08:05 -0700229 // Populate encapsulation information when a output device is connected.
230 device->setEncapsulationInfoFromHal(mpClientInterface);
231
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700232 // outputs should never be empty here
233 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
234 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100235 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800236
Eric Laurent3ae5f312015-02-03 17:12:08 -0800237 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700238 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700239 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700240 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100241 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700242 return INVALID_OPERATION;
243 }
244
François Gaffie11d30102018-11-02 16:09:09 +0100245 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700246
Paul McLeane743a472015-01-28 11:07:31 -0800247 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100248 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700249
Eric Laurente552edb2014-03-10 17:42:56 -0700250 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100251 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700252
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100253 mOutputs.clearSessionRoutesForDevice(device);
254
François Gaffie11d30102018-11-02 16:09:09 +0100255 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100256
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800257 // Reset active device codec
258 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
259
Kriti Dangef6be8f2020-11-05 11:58:19 +0100260 // remove device from mReportedFormatsMap cache
261 mReportedFormatsMap.erase(device);
262
jiabina84c3d32022-12-02 18:59:55 +0000263 // remove preferred mixer configurations
264 mPreferredMixerAttrInfos.erase(device->getId());
265
Eric Laurente552edb2014-03-10 17:42:56 -0700266 } break;
267
268 default:
François Gaffie11d30102018-11-02 16:09:09 +0100269 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700270 return BAD_VALUE;
271 }
272
Eric Laurent736a1022019-03-27 18:28:46 -0700273 // Propagate device availability to Engine
274 setEngineDeviceConnectionState(device, state);
275
Eric Laurentae970022019-01-29 14:25:04 -0800276 // No need to evaluate playback routing when connecting a remote submix
277 // output device used by a dynamic policy of type recorder as no
278 // playback use case is affected.
279 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700280 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800281 for (audio_io_handle_t output : outputs) {
282 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800283 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
284 if (policyMix != nullptr
285 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700286 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800287 doCheckForDeviceAndOutputChanges = false;
288 break;
289 }
290 }
291 }
292
293 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700294 // outputs must be closed after checkOutputForAllStrategies() is executed
295 if (!outputs.isEmpty()) {
296 for (audio_io_handle_t output : outputs) {
297 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100298 // close unused outputs after device disconnection or direct outputs that have
299 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200300 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200301 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
302 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200303 (desc->mDirectOpenCount == 0))
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
305 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200306 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700307 closeOutput(output);
308 }
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700310 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
311 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700312 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700313 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800314 };
315
316 if (doCheckForDeviceAndOutputChanges) {
317 checkForDeviceAndOutputChanges(checkCloseOutputs);
318 } else {
319 checkCloseOutputs();
320 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100321 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100322 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700323 const DeviceVector activeMediaDevices =
324 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000325 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700326 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700327 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530328 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
329 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100330 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700331 // do not force device change on duplicated output because if device is 0, it will
332 // also force a device 0 for the two outputs it is duplicated to which may override
333 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100334 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100335 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700336 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700337 // always force when disconnecting (a non-duplicated device)
338 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000339 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
340 // If the device is using preferred mixer attributes, the output need to reopen
341 // with default configuration when the new selected devices are different from
342 // current routing devices
343 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
344 continue;
345 }
François Gaffie11d30102018-11-02 16:09:09 +0100346 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700347 }
jiabinbce0c1d2020-10-05 11:20:18 -0700348 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000349 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700350 desc->supportsDevicesForPlayback(activeMediaDevices)) {
351 // Reopen the output to query the dynamic profiles when there is not active
352 // clients or all active clients will be rerouted. Otherwise, set the flag
353 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
354 // can be reopened to query dynamic profiles when all clients are inactive.
355 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000356 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700357 } else {
358 desc->mPendingReopenToQueryProfiles = true;
359 }
360 }
361 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
362 // Clear the flag that previously set for re-querying profiles.
363 desc->mPendingReopenToQueryProfiles = false;
364 }
365 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000366 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700367
Eric Laurentd60560a2015-04-10 11:31:20 -0700368 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100369 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700370 }
371
Eric Laurent96d1dda2022-03-14 17:14:19 +0100372 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
373
Eric Laurent72aa32f2014-05-30 18:51:48 -0700374 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700375 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700376 } // end if is output device
377
Eric Laurente552edb2014-03-10 17:42:56 -0700378 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700379 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100380 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700381 switch (state)
382 {
383 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700384 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700385 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100386 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700387 return INVALID_OPERATION;
388 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700389
390 if (mAvailableInputDevices.add(device) < 0) {
391 return NO_MEMORY;
392 }
393
François Gaffie44481e72016-04-20 07:49:57 +0200394 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
395 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100396 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200397
Eric Laurent0dd51852019-04-19 18:18:58 -0700398 if (checkInputsForDevice(device, state) != NO_ERROR) {
399 mAvailableInputDevices.remove(device);
400
François Gaffie11d30102018-11-02 16:09:09 +0100401 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100402
403 mHwModules.cleanUpForDevice(device);
404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 return INVALID_OPERATION;
406 }
407
Eric Laurentd4692962014-05-05 18:13:44 -0700408 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700409
410 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700411 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700412 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100413 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700414 return INVALID_OPERATION;
415 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700416
François Gaffie11d30102018-11-02 16:09:09 +0100417 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700418
419 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100420 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700421
François Gaffie11d30102018-11-02 16:09:09 +0100422 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700423
424 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100425
426 // 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) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100464 DeviceDescriptorBase devDescr(device, device_address);
465 devDescr.setName(device_name);
466 return devDescr.writeToParcelable(aidlPort);
467}
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{
515 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700516 String8 reply;
517 AudioParameter param;
518 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800520 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
521 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800522
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800523 // connect/disconnect only 1 device at a time
524 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
525
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800526 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700527 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800528 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800529 // Nothing to do: device is not connected
530 return NO_ERROR;
531 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800532 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800533
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700534 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800535 // configure codecs.
536 // Handle two specific cases by sending a set parameter to
537 // configure A2DP codecs. No need to toggle device state.
538 // Case 1: A2DP active device switches from primary to primary
539 // module
540 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200541 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700542 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800543 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
544 if (availablePrimaryOutputDevices().contains(devDesc) &&
545 (module != 0 && module->getHandle() == primaryHandle)) {
546 reply = mpClientInterface->getParameters(
547 AUDIO_IO_HANDLE_NONE,
548 String8(AudioParameter::keyReconfigA2dpSupported));
549 AudioParameter repliedParameters(reply);
550 repliedParameters.getInt(
551 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
552 if (isReconfigA2dpSupported) {
553 const String8 key(AudioParameter::keyReconfigA2dp);
554 param.add(key, String8("true"));
555 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
556 devDesc->setEncodedFormat(encodedFormat);
557 return NO_ERROR;
558 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700559 }
560 }
cnx421bd2dcc42020-07-11 14:58:44 +0800561 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
562 for (size_t i = 0; i < mOutputs.size(); i++) {
563 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
564 // mute media strategies and delay device switch by the largest
565 // This avoid sending the music tail into the earpiece or headset.
566 setStrategyMute(musicStrategy, true, desc);
567 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
568 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
569 nullptr, true /*fromCache*/).types());
570 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800571 // Toggle the device state: UNAVAILABLE -> AVAILABLE
572 // This will force reading again the device configuration
573 status = setDeviceConnectionState(device,
574 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800575 device_address, device_name,
576 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800577 if (status != NO_ERROR) {
578 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
579 status);
580 return status;
581 }
582
583 status = setDeviceConnectionState(device,
584 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800585 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800586 if (status != NO_ERROR) {
587 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
588 status);
589 return status;
590 }
591
592 return NO_ERROR;
593}
594
Pattydd807582021-11-04 21:01:03 +0800595status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
596 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800597{
Pattydd807582021-11-04 21:01:03 +0800598 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800599 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800600 std::unordered_set<audio_format_t> formatSet;
601 sp<HwModule> primaryModule =
602 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700603 if (primaryModule == nullptr) {
604 ALOGE("%s() unable to get primary module", __func__);
605 return NO_INIT;
606 }
Pattydd807582021-11-04 21:01:03 +0800607
608 DeviceTypeSet audioDeviceSet;
609
610 switch(device) {
611 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
612 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
613 break;
614 case AUDIO_DEVICE_OUT_BLE_HEADSET:
615 audioDeviceSet = getAudioDeviceOutAllBleSet();
616 break;
617 default:
618 ALOGE("%s() device type 0x%08x not supported", __func__, device);
619 return BAD_VALUE;
620 }
621
jiabin9a3361e2019-10-01 09:38:30 -0700622 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800623 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800624 for (const auto& device : declaredDevices) {
625 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800626 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800627 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 return status;
629}
630
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100631DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
632{
633 DeviceVector rxSinkdevices{};
634 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
635 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
636 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
637 auto rxSinkDevice = rxSinkdevices.itemAt(0);
638 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
639 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
640 // retrieve Rx Source device descriptor
641 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
642 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
643
644 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
645 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
646 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
647 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
648 return DeviceVector(rxSinkDevice);
649 }
650 }
651 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
652 // the device returned is not necessarily reachable via this output
653 // (filter later by setOutputDevices())
654 return getNewOutputDevices(mPrimaryOutput, fromCache);
655}
656
657status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
658{
659 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
660 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
661 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
662 }
663 return INVALID_OPERATION;
664}
665
666status_t AudioPolicyManager::updateCallRoutingInternal(
667 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668{
669 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100670 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700671 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700672 if(!hasPrimaryOutput() ||
673 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100674 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700675 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
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);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100680 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100681
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100682 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100683 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700684
Francois Gaffie601801d2021-06-22 13:27:39 +0200685 disconnectTelephonyAudioSource(mCallRxSourceClient);
686 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700687
François Gaffie9eb18552018-11-05 10:33:26 +0100688 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700689 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100690 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700691 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100692 // retrieve Rx Source and Tx Sink device descriptors
693 sp<DeviceDescriptor> rxSourceDevice =
694 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
695 String8(),
696 AUDIO_FORMAT_DEFAULT);
697 sp<DeviceDescriptor> txSinkDevice =
698 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
699 String8(),
700 AUDIO_FORMAT_DEFAULT);
701
702 // RX and TX Telephony device are declared by Primary Audio HAL
703 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
704 (telephonyRxModule->getHalVersionMajor() >= 3)) {
705 if (rxSourceDevice == 0 || txSinkDevice == 0) {
706 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100707 ALOGE("%s() no telephony Tx and/or RX device", __func__);
708 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100709 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100710 // createAudioPatchInternal now supports both HW / SW bridging
711 createRxPatch = true;
712 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100713 } else {
714 // If the RX device is on the primary HW module, then use legacy routing method for
715 // voice calls via setOutputDevice() on primary output.
716 // Otherwise, create two audio patches for TX and RX path.
717 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
718 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700719 // If the TX device is also on the primary HW module, setOutputDevice() will take care
720 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100721 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
722 (txSinkDevice != 0);
723 }
724 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
725 // Otherwise, create two audio patches for TX and RX path.
726 if (!createRxPatch) {
727 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700728 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200729 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800730 // If the TX device is on the primary HW module but RX device is
731 // on other HW module, SinkMetaData of telephony input should handle it
732 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700733 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700734 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100735 // terminate active capture if on the same HW module as the call TX source device
736 // FIXME: would be better to refine to only inputs whose profile connects to the
737 // call TX device but this information is not in the audio patch and logic here must be
738 // symmetric to the one in startInput()
739 for (const auto& activeDesc : mInputs.getActiveInputs()) {
740 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
741 closeActiveClients(activeDesc);
742 }
743 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200744 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800745 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100746 if (waitMs != nullptr) {
747 *waitMs = muteWaitMs;
748 }
749 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800750}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700751
Mikhail Naganov100f0122018-11-29 11:22:16 -0800752bool AudioPolicyManager::isDeviceOfModule(
753 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
754 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
755 if (module != 0) {
756 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
757 .indexOf(devDesc) != NAME_NOT_FOUND
758 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
759 .indexOf(devDesc) != NAME_NOT_FOUND;
760 }
761 return false;
762}
763
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200764void AudioPolicyManager::connectTelephonyRxAudioSource()
765{
Francois Gaffie601801d2021-06-22 13:27:39 +0200766 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200767 const struct audio_port_config source = {
768 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
769 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
770 };
771 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200772 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
773 ALOGE_IF(mCallRxSourceClient == nullptr,
774 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200775}
776
Francois Gaffie601801d2021-06-22 13:27:39 +0200777void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200778{
Francois Gaffie601801d2021-06-22 13:27:39 +0200779 if (clientDesc == nullptr) {
780 return;
781 }
782 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
783 "%s error stopping audio source", __func__);
784 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200785}
786
787void AudioPolicyManager::connectTelephonyTxAudioSource(
788 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
789 uint32_t delayMs)
790{
Francois Gaffie601801d2021-06-22 13:27:39 +0200791 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200792 if (srcDevice == nullptr || sinkDevice == nullptr) {
793 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
794 return;
795 }
796 PatchBuilder patchBuilder;
797 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
798 ALOGV("%s between source %s and sink %s", __func__,
799 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200800 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200801 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
802
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200803 struct audio_port_config source = {};
804 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200805 mCallTxSourceClient = new InternalSourceClientDescriptor(
806 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200807 mCommunnicationStrategy, toVolumeSource(aa));
808 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
809 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200810 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
811 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200812 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
813 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200814 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200815 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200816}
817
Eric Laurente0720872014-03-11 09:30:41 -0700818void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700819{
820 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100821 // store previous phone state for management of sonification strategy below
822 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100823 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100824
825 if (mEngine->setPhoneState(state) != NO_ERROR) {
826 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700827 return;
828 }
François Gaffie2110e042015-03-24 08:41:51 +0100829 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700830 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700831 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700832 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800833 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700834 }
835
François Gaffie2110e042015-03-24 08:41:51 +0100836 /**
837 * Switching to or from incall state or switching between telephony and VoIP lead to force
838 * routing command.
839 */
Eric Laurent74b71512019-11-06 17:21:57 -0800840 bool force = ((isStateInCall(oldState) != isStateInCall(state))
841 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700842
843 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700844 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700845
Eric Laurente552edb2014-03-10 17:42:56 -0700846 int delayMs = 0;
847 if (isStateInCall(state)) {
848 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100849 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
850 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700851 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700852 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700853 // mute media and sonification strategies and delay device switch by the largest
854 // latency of any output where either strategy is active.
855 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100856 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
857 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
858 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700859 (delayMs < (int)desc->latency()*2)) {
860 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700861 }
François Gaffiec005e562018-11-06 15:04:49 +0100862 setStrategyMute(musicStrategy, true, desc);
863 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
864 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
865 nullptr, true /*fromCache*/).types());
866 setStrategyMute(sonificationStrategy, true, desc);
867 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
868 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
869 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700870 }
871 }
872
Eric Laurent87ffa392015-05-22 10:32:38 -0700873 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700874 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100875 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700876 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100877 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
878 // force routing command to audio hardware when ending call
879 // even if no device change is needed
880 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
881 rxDevices = mPrimaryOutput->devices();
882 }
883 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200884 disconnectTelephonyAudioSource(mCallRxSourceClient);
885 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100886 }
François Gaffie11d30102018-11-02 16:09:09 +0100887 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700888 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700889 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700890
jiabin3ff8d7d2022-12-13 06:27:44 +0000891 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700892 // reevaluate routing on all outputs in case tracks have been started during the call
893 for (size_t i = 0; i < mOutputs.size(); i++) {
894 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100895 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200896 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
897 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000898 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
899 // If the device is using preferred mixer attributes, the output need to reopen
900 // with default configuration when the new selected devices are different from
901 // current routing devices.
902 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
903 continue;
904 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200905 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
906 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700907 }
908 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000909 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700910
Eric Laurent96d1dda2022-03-14 17:14:19 +0100911 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
912
Eric Laurente552edb2014-03-10 17:42:56 -0700913 if (isStateInCall(state)) {
914 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700915 // force reevaluating accessibility routing when call starts
916 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700917 }
918
919 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100920 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
921 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700922}
923
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700924audio_mode_t AudioPolicyManager::getPhoneState() {
925 return mEngine->getPhoneState();
926}
927
Eric Laurente0720872014-03-11 09:30:41 -0700928void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100929 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700930{
François Gaffie2110e042015-03-24 08:41:51 +0100931 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700932 if (config == mEngine->getForceUse(usage)) {
933 return;
934 }
Eric Laurente552edb2014-03-10 17:42:56 -0700935
François Gaffie2110e042015-03-24 08:41:51 +0100936 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
937 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
938 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700939 }
François Gaffie2110e042015-03-24 08:41:51 +0100940 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
941 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
942 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700943
944 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700945 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800946
Eric Laurent22fcda22019-05-17 16:28:47 -0700947 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
948 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
949 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
950 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
951 }
952
Eric Laurentdc462862016-07-19 12:29:53 -0700953 //FIXME: workaround for truncated touch sounds
954 // to be removed when the problem is handled by system UI
955 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700956 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
957 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
958 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700959
960 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100961 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700962}
963
Eric Laurente0720872014-03-11 09:30:41 -0700964void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700965{
966 ALOGV("setSystemProperty() property %s, value %s", property, value);
967}
968
Dorin Drimusecc9f422022-03-09 17:57:40 +0100969// Find an MSD output profile compatible with the parameters passed.
970// When "directOnly" is set, restrict search to profiles for direct outputs.
971sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
972 const DeviceVector& devices,
973 uint32_t samplingRate,
974 audio_format_t format,
975 audio_channel_mask_t channelMask,
976 audio_output_flags_t flags,
977 bool directOnly)
978{
979 flags = getRelevantFlags(flags, directOnly);
980
981 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
982 if (msdModule != nullptr) {
983 // for the msd module check if there are patches to the output devices
984 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
985 HwModuleCollection modules;
986 modules.add(msdModule);
987 return searchCompatibleProfileHwModules(
988 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
989 flags, directOnly);
990 }
991 }
992 return nullptr;
993}
994
Michael Chana94fbb22018-04-24 14:31:19 +1000995// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
996// search to profiles for direct outputs.
997sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100998 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000999 uint32_t samplingRate,
1000 audio_format_t format,
1001 audio_channel_mask_t channelMask,
1002 audio_output_flags_t flags,
1003 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001004{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001005 flags = getRelevantFlags(flags, directOnly);
1006
1007 return searchCompatibleProfileHwModules(
1008 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1009}
1010
1011audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1012 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001013 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001014 // only retain flags that will drive the direct output profile selection
1015 // if explicitly requested
1016 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001017 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001018 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1019 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001020 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001021 return flags;
1022}
Eric Laurent861a6282015-05-18 15:40:16 -07001023
Dorin Drimusecc9f422022-03-09 17:57:40 +01001024sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1025 const HwModuleCollection& hwModules,
1026 const DeviceVector& devices,
1027 uint32_t samplingRate,
1028 audio_format_t format,
1029 audio_channel_mask_t channelMask,
1030 audio_output_flags_t flags,
1031 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001032 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001033 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001034 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001035 if (!curProfile->isCompatibleProfile(devices,
1036 samplingRate, NULL /*updatedSamplingRate*/,
1037 format, NULL /*updatedFormat*/,
1038 channelMask, NULL /*updatedChannelMask*/,
1039 flags)) {
1040 continue;
1041 }
1042 // reject profiles not corresponding to a device currently available
1043 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1044 continue;
1045 }
1046 // reject profiles if connected device does not support codec
1047 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1048 continue;
1049 }
1050 if (!directOnly) {
1051 return curProfile;
1052 }
1053
1054 // when searching for direct outputs, if several profiles are compatible, give priority
1055 // to one with offload capability
1056 if (profile != 0 &&
1057 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001058 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001059 }
1060 profile = curProfile;
1061 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1062 break;
1063 }
Eric Laurente552edb2014-03-10 17:42:56 -07001064 }
1065 }
Eric Laurent861a6282015-05-18 15:40:16 -07001066 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001067}
1068
Eric Laurentfa0f6742021-08-17 18:39:44 +02001069sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001070 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001071{
1072 for (const auto& hwModule : mHwModules) {
1073 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001074 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001075 continue;
1076 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001077 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001078 // reject profiles not corresponding to a device currently available
1079 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1080 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1081 continue;
1082 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001083 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1084 != devices.size()) {
1085 continue;
1086 }
1087 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001088 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1089 return curProfile;
1090 }
1091 }
1092 return nullptr;
1093}
1094
Eric Laurentf4e63452017-11-06 19:31:46 +00001095audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001096{
François Gaffiec005e562018-11-06 15:04:49 +01001097 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001098
1099 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1100 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1101 // format, flags, etc. This may result in some discrepancy for functions that utilize
1102 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1103 // and AudioSystem::getOutputSamplingRate().
1104
François Gaffie11d30102018-11-02 16:09:09 +01001105 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001106 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001107
François Gaffie11d30102018-11-02 16:09:09 +01001108 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1109 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001110 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001111}
1112
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001113status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1114 const audio_attributes_t *srcAttr,
1115 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001116{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001117 if (srcAttr != NULL) {
1118 if (!isValidAttributes(srcAttr)) {
1119 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1120 __func__,
1121 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1122 srcAttr->tags);
1123 return BAD_VALUE;
1124 }
1125 *dstAttr = *srcAttr;
1126 } else {
1127 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1128 ALOGE("%s: invalid stream type", __func__);
1129 return BAD_VALUE;
1130 }
François Gaffiec005e562018-11-06 15:04:49 +01001131 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001132 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001133
1134 // Only honor audibility enforced when required. The client will be
1135 // forced to reconnect if the forced usage changes.
1136 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001137 dstAttr->flags = static_cast<audio_flags_mask_t>(
1138 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001139 }
1140
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001141 return NO_ERROR;
1142}
1143
Kevin Rocard153f92d2018-12-18 18:33:28 -08001144status_t AudioPolicyManager::getOutputForAttrInt(
1145 audio_attributes_t *resultAttr,
1146 audio_io_handle_t *output,
1147 audio_session_t session,
1148 const audio_attributes_t *attr,
1149 audio_stream_type_t *stream,
1150 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001151 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001152 audio_output_flags_t *flags,
1153 audio_port_handle_t *selectedDeviceId,
1154 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001155 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001156 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001157 bool *isSpatialized,
1158 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001159{
François Gaffiec005e562018-11-06 15:04:49 +01001160 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001161 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001162 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001163 const sp<DeviceDescriptor> requestedDevice =
1164 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1165
Eric Laurent8a1095a2019-11-08 14:44:16 -08001166 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001167 *isSpatialized = false;
1168
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001169 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1170 if (status != NO_ERROR) {
1171 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001172 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001173 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001174 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001175 }
François Gaffiec005e562018-11-06 15:04:49 +01001176 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001177
François Gaffiec005e562018-11-06 15:04:49 +01001178 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1179 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001180
Kevin Rocard153f92d2018-12-18 18:33:28 -08001181 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1182 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1183 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001184 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001185 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1186 .channel_mask = config->channel_mask,
1187 .format = config->format,
1188 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001189 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
1190 primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001191 if (status != OK) {
1192 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001193 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001194
Kevin Rocard153f92d2018-12-18 18:33:28 -08001195 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001196 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001197
1198 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001199 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1200 && !audio_is_linear_pcm(config->format)) {
1201 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001202 return BAD_VALUE;
1203 }
1204 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001205 sp<DeviceDescriptor> deviceDesc =
1206 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1207 primaryMix->mDeviceAddress,
1208 AUDIO_FORMAT_DEFAULT);
1209 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001210 bool tryDirectForFlags = policyDesc == nullptr ||
1211 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1212 // if a direct output can be opened to deliver the track's multi-channel content to the
1213 // output rather than being downmixed by the primary output, then use this direct
1214 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1215 // mix.
1216 bool tryDirectForChannelMask = policyDesc != nullptr
1217 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1218 audio_channel_count_from_out_mask(config->channel_mask));
1219 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001220 audio_io_handle_t newOutput;
1221 status = openDirectOutput(
1222 *stream, session, config,
1223 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1224 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001225 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001226 policyDesc = mOutputs.valueFor(newOutput);
1227 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001228 } else if (tryDirectForFlags) {
1229 policyDesc = nullptr;
1230 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001231 }
1232 if (policyDesc != nullptr) {
1233 policyDesc->mPolicyMix = primaryMix;
1234 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001235 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001236
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001237 ALOGV("getOutputForAttr() returns output %d", *output);
1238 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1239 *outputType = API_OUT_MIX_PLAYBACK;
1240 } else {
1241 *outputType = API_OUTPUT_LEGACY;
1242 }
1243 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001244 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001245 }
François Gaffiec005e562018-11-06 15:04:49 +01001246 // Virtual sources must always be dynamicaly or explicitly routed
1247 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1248 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1249 return BAD_VALUE;
1250 }
1251 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1252 // in order to let the choice of the order to future vendor engine
1253 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001254
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001255 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001256 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001257 }
1258
Nadav Barb2f18162018-07-18 13:01:53 +03001259 // Set incall music only if device was explicitly set, and fallback to the device which is
1260 // chosen by the engine if not.
1261 // FIXME: provide a more generic approach which is not device specific and move this back
1262 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001263 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001264 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001265 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001266 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001267 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001268 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001269 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001270 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001271 }
1272 }
1273
François Gaffiec005e562018-11-06 15:04:49 +01001274 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1275 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1276 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001277
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001278 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001279 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001280 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001281 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001282 ALOGV("%s() Using MSD devices %s instead of devices %s",
1283 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001284 } else {
1285 *output = AUDIO_IO_HANDLE_NONE;
1286 }
1287 }
1288 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001289 sp<PreferredMixerAttributesInfo> info = nullptr;
1290 if (outputDevices.size() == 1) {
1291 info = getPreferredMixerAttributesInfo(
1292 outputDevices.itemAt(0)->getId(),
1293 mEngine->getProductStrategyForAttributes(*resultAttr));
1294 if (info != nullptr && info->getUid() != uid && info->getActiveClientCount() == 0) {
1295 // Only use preferred mixer when the requested uid matched or
1296 // there is active client on preferred mixer.
1297 info = nullptr;
1298 }
1299 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001300 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001301 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabinc658e452022-10-21 20:52:21 +00001302 *isBitPerfect = (info != nullptr
1303 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
1304 && *output != AUDIO_IO_HANDLE_NONE);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001305 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001306 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001307 AudioProfileVector profiles;
1308 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1309 if (ret == NO_ERROR && !profiles.empty()) {
1310 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1311 : *profiles[0]->getChannels().begin();
1312 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1313 : *profiles[0]->getSampleRates().begin();
1314 config->format = profiles[0]->getFormat();
1315 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001316 return INVALID_OPERATION;
1317 }
Paul McLeanaa981192015-03-21 09:55:15 -07001318
François Gaffiec005e562018-11-06 15:04:49 +01001319 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001320 for (auto &outputDevice : outputDevices) {
1321 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1322 *selectedDeviceId = outputDevice->getId();
1323 break;
1324 }
1325 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001326
Eric Laurent8a1095a2019-11-08 14:44:16 -08001327 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1328 *outputType = API_OUTPUT_TELEPHONY_TX;
1329 } else {
1330 *outputType = API_OUTPUT_LEGACY;
1331 }
1332
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001333 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1334
1335 return NO_ERROR;
1336}
1337
1338status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1339 audio_io_handle_t *output,
1340 audio_session_t session,
1341 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001342 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001343 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001344 audio_output_flags_t *flags,
1345 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001346 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001347 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001348 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001349 bool *isSpatialized,
1350 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001351{
1352 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1353 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1354 return INVALID_OPERATION;
1355 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001356 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001357 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001358 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001359 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001360 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001361 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001362 const sp<DeviceDescriptor> requestedDevice =
1363 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1364
1365 // Prevent from storing invalid requested device id in clients
1366 const audio_port_handle_t sanitizedRequestedPortId =
1367 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1368 *selectedDeviceId = sanitizedRequestedPortId;
1369
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001370 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001371 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001372 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1373 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001374 if (status != NO_ERROR) {
1375 return status;
1376 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001377 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001378 if (secondaryOutputs != nullptr) {
1379 for (auto &secondaryMix : secondaryMixes) {
1380 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1381 if (outputDesc != nullptr &&
1382 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1383 secondaryOutputs->push_back(outputDesc->mIoHandle);
1384 weakSecondaryOutputDescs.push_back(outputDesc);
1385 }
1386 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001387 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001388
Eric Laurent8fc147b2018-07-22 19:13:55 -07001389 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001390 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001391 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001392 };
jiabin4ef93452019-09-10 14:29:54 -07001393 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001394
Eric Laurentc209fe42020-06-05 18:11:23 -07001395 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001396 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001397 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001398 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001399 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001400 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001401 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001402 std::move(weakSecondaryOutputDescs),
1403 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001404 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001405
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001406 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1407 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001408
Eric Laurente83b55d2014-11-14 10:06:21 -08001409 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001410}
1411
Eric Laurentc529cf62020-04-17 18:19:10 -07001412status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1413 audio_session_t session,
1414 const audio_config_t *config,
1415 audio_output_flags_t flags,
1416 const DeviceVector &devices,
1417 audio_io_handle_t *output) {
1418
1419 *output = AUDIO_IO_HANDLE_NONE;
1420
1421 // skip direct output selection if the request can obviously be attached to a mixed output
1422 // and not explicitly requested
1423 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1424 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1425 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1426 return NAME_NOT_FOUND;
1427 }
1428
1429 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1430 // This prevents creating an offloaded track and tearing it down immediately after start
1431 // when audioflinger detects there is an active non offloadable effect.
1432 // FIXME: We should check the audio session here but we do not have it in this context.
1433 // This may prevent offloading in rare situations where effects are left active by apps
1434 // in the background.
1435 sp<IOProfile> profile;
1436 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1437 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1438 profile = getProfileForOutput(
1439 devices, config->sample_rate, config->format, config->channel_mask,
1440 flags, true /* directOnly */);
1441 }
1442
1443 if (profile == nullptr) {
1444 return NAME_NOT_FOUND;
1445 }
1446
1447 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1448 for (size_t i = 0; i < mOutputs.size(); i++) {
1449 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1450 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1451 // reuse direct output if currently open by the same client
1452 // and configured with same parameters
1453 if ((config->sample_rate == desc->getSamplingRate()) &&
1454 (config->format == desc->getFormat()) &&
1455 (config->channel_mask == desc->getChannelMask()) &&
1456 (session == desc->mDirectClientSession)) {
1457 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001458 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001459 mOutputs.keyAt(i), session);
1460 *output = mOutputs.keyAt(i);
1461 return NO_ERROR;
1462 }
1463 }
1464 }
1465
1466 if (!profile->canOpenNewIo()) {
1467 return NAME_NOT_FOUND;
1468 }
1469
1470 sp<SwAudioOutputDescriptor> outputDesc =
1471 new SwAudioOutputDescriptor(profile, mpClientInterface);
1472
Michael Chan6fb34492020-12-08 15:44:49 +11001473 // An MSD patch may be using the only output stream that can service this request. Release
1474 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001475 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001476
Eric Laurentf1f22e72021-07-13 14:04:14 +02001477 status_t status =
1478 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001479
1480 // only accept an output with the requested parameters
1481 if (status != NO_ERROR ||
1482 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1483 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1484 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1485 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1486 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1487 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1488 config->channel_mask, outputDesc->getChannelMask());
1489 if (*output != AUDIO_IO_HANDLE_NONE) {
1490 outputDesc->close();
1491 }
1492 // fall back to mixer output if possible when the direct output could not be open
1493 if (audio_is_linear_pcm(config->format) &&
1494 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1495 return NAME_NOT_FOUND;
1496 }
1497 *output = AUDIO_IO_HANDLE_NONE;
1498 return BAD_VALUE;
1499 }
1500 outputDesc->mDirectOpenCount = 1;
1501 outputDesc->mDirectClientSession = session;
1502
1503 addOutput(*output, outputDesc);
1504 mPreviousOutputs = mOutputs;
1505 ALOGV("%s returns new direct output %d", __func__, *output);
1506 mpClientInterface->onAudioPortListUpdate();
1507 return NO_ERROR;
1508}
1509
François Gaffie11d30102018-11-02 16:09:09 +01001510audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1511 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001512 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001513 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001514 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001515 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001516 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001517 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001518 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001519{
Andy Hungc88b0642018-04-27 15:42:35 -07001520 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001521
jiabine375d412019-02-26 12:54:53 -08001522 // Discard haptic channel mask when forcing muting haptic channels.
1523 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001524 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1525 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001526
Eric Laurente552edb2014-03-10 17:42:56 -07001527 // open a direct output if required by specified parameters
1528 //force direct flag if offload flag is set: offloading implies a direct output stream
1529 // and all common behaviors are driven by checking only the direct flag
1530 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001531 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1532 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001533 }
Nadav Bar766fb022018-01-07 12:18:03 +02001534 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1535 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001536 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001537
1538 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1539
Eric Laurente83b55d2014-11-14 10:06:21 -08001540 // only allow deep buffering for music stream type
1541 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001542 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001543 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001544 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001545 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1546 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001547 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001548 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001549 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001550 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001551 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001552 audio_is_linear_pcm(config->format) &&
1553 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001554 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001555 AUDIO_OUTPUT_FLAG_DIRECT);
1556 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001557 }
Eric Laurente552edb2014-03-10 17:42:56 -07001558
Carter Hsua3abb402021-10-26 11:11:20 +08001559 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1560 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1561 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1562 }
1563
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001564 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001565 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001566 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001567 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001568 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001569 }
1570
Eric Laurentc529cf62020-04-17 18:19:10 -07001571 audio_config_t directConfig = *config;
1572 directConfig.channel_mask = channelMask;
1573 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1574 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001575 return output;
1576 }
1577
Eric Laurent14cbfca2016-03-17 09:42:16 -07001578 // A request for HW A/V sync cannot fallback to a mixed output because time
1579 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001580 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001581 return AUDIO_IO_HANDLE_NONE;
1582 }
1583
Eric Laurente552edb2014-03-10 17:42:56 -07001584 // ignoring channel mask due to downmix capability in mixer
1585
1586 // open a non direct output
1587
1588 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001589 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001590 // get which output is suitable for the specified stream. The actual
1591 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001592 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001593 if (prefMixerConfigInfo != nullptr) {
1594 for (audio_io_handle_t outputHandle : outputs) {
1595 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1596 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1597 output = outputHandle;
1598 break;
1599 }
1600 }
1601 if (output == AUDIO_IO_HANDLE_NONE) {
1602 // No output open with the preferred profile. Open a new one.
1603 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1604 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1605 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1606 config.format = prefMixerConfigInfo->getConfigBase().format;
1607 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1608 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1609 &config, prefMixerConfigInfo->getFlags());
1610 if (preferredOutput == nullptr) {
1611 ALOGE("%s failed to open output with preferred mixer config", __func__);
1612 } else {
1613 output = preferredOutput->mIoHandle;
1614 }
1615 }
1616 } else {
1617 // at this stage we should ignore the DIRECT flag as no direct output could be
1618 // found earlier
1619 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1620 output = selectOutput(
1621 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1622 }
Eric Laurente552edb2014-03-10 17:42:56 -07001623 }
François Gaffie11d30102018-11-02 16:09:09 +01001624 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001625 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001626 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001627
Eric Laurente552edb2014-03-10 17:42:56 -07001628 return output;
1629}
1630
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001631sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001632 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1633 mAvailableInputDevices);
1634 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1635}
1636
1637DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1638 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1639 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001640}
1641
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001642const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001643 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001644 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1645 if (msdModule != 0) {
1646 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1647 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1648 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1649 const struct audio_port_config *source = &patch->mPatch.sources[j];
1650 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1651 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001652 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001653 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001654 }
1655 }
1656 }
1657 return msdPatches;
1658}
1659
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001660bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1661 ssize_t index = mAudioPatches.indexOfKey(handle);
1662 if (index < 0) {
1663 return false;
1664 }
1665 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1666 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1667 if (msdModule == nullptr) {
1668 return false;
1669 }
1670 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1671 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1672 return true;
1673 }
1674 index = getMsdOutputPatches().indexOfKey(handle);
1675 if (index < 0) {
1676 return false;
1677 }
1678 return true;
1679}
1680
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001681status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1682 const InputProfileCollection &inputProfiles,
1683 const OutputProfileCollection &outputProfiles,
1684 const sp<DeviceDescriptor> &sourceDevice,
1685 const sp<DeviceDescriptor> &sinkDevice,
1686 AudioProfileVector& sourceProfiles,
1687 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001688 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001689 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001690 return NO_INIT;
1691 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001692 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001693 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001694 return NO_INIT;
1695 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001696 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001697 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1698 inProfile->supportsDevice(sourceDevice)) {
1699 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001700 }
1701 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001702 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001703 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001704 outProfile->supportsDevice(sinkDevice)) {
1705 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001706 }
1707 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001708 return NO_ERROR;
1709}
1710
1711status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1712 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1713 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1714{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001715 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001716 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1717 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1718 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001719 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001720 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1721 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001722 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723 }
1724 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1725 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1726 sinkConfig->format = bestSinkConfig.format;
1727 // For encoded streams force direct flag to prevent downstream mixing.
1728 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1729 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001730 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1731 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001732 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001733 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1734 // raw and IEC61937 framed streams.
1735 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1736 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1737 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001738 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1739 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1740 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1741 sourceConfig->format = bestSinkConfig.format;
1742 // Copy input stream directly without any processing (e.g. resampling).
1743 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1744 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1745 if (hwAvSync) {
1746 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1747 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1748 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1749 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1750 }
1751 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1752 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1753 sinkConfig->config_mask |= config_mask;
1754 sourceConfig->config_mask |= config_mask;
1755 return NO_ERROR;
1756}
1757
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001758PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1759 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001760{
1761 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001762 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1763 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1764 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1765 if (deviceModule == nullptr) {
1766 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1767 return patchBuilder;
1768 }
1769 const InputProfileCollection inputProfiles = msdIsSource ?
1770 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1771 const OutputProfileCollection outputProfiles = msdIsSource ?
1772 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1773
1774 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1775 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1776 device : getMsdAudioOutDevices().itemAt(0);
1777 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1778
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001779 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1780 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001781 AudioProfileVector sourceProfiles;
1782 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001783 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1784 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001785 for (auto hwAvSync : { true, false }) {
1786 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1787 sourceProfiles, sinkProfiles) != NO_ERROR) {
1788 continue;
1789 }
1790 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1791 &sinkConfig) == NO_ERROR) {
1792 // Found a matching config. Re-create PatchBuilder with this config.
1793 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1794 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001795 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001796 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001797 " supporting PCM format conversion.", __func__);
1798 return patchBuilder;
1799}
1800
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001801status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001802 DeviceVector devices;
1803 if (outputDevices != nullptr && outputDevices->size() > 0) {
1804 devices.add(*outputDevices);
1805 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001806 // Use media strategy for unspecified output device. This should only
1807 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1808 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001809 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001810 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001811 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001812 }
Michael Chan6fb34492020-12-08 15:44:49 +11001813 std::vector<PatchBuilder> patchesToCreate;
1814 for (auto i = 0u; i < devices.size(); ++i) {
1815 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001816 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001817 }
1818 // Retain only the MSD patches associated with outputDevices request.
1819 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001820 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001821 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1822 auto retainedPatch = false;
1823 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1824 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1825 patchesToRemove.removeItemsAt(i);
1826 retainedPatch = true;
1827 break;
1828 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001829 }
Michael Chan6fb34492020-12-08 15:44:49 +11001830 if (retainedPatch) {
1831 it = patchesToCreate.erase(it);
1832 continue;
1833 }
1834 ++it;
1835 }
1836 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1837 return NO_ERROR;
1838 }
1839 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1840 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001841 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 }
Michael Chan6fb34492020-12-08 15:44:49 +11001843 status_t status = NO_ERROR;
1844 for (const auto &p : patchesToCreate) {
1845 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1846 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1847 char message[256];
1848 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1849 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1850 currStatus == NO_ERROR ? "Success" : "Error",
1851 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1852 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1853 if (currStatus == NO_ERROR) {
1854 ALOGD("%s", message);
1855 } else {
1856 ALOGE("%s", message);
1857 if (status == NO_ERROR) {
1858 status = currStatus;
1859 }
1860 }
1861 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001862 return status;
1863}
1864
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001865void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1866 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001867 for (size_t i = 0; i < msdPatches.size(); i++) {
1868 const auto& patch = msdPatches[i];
1869 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1870 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1871 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1872 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1873 releaseAudioPatch(patch->getHandle(), mUidCached);
1874 break;
1875 }
1876 }
1877 }
1878}
1879
Dorin Drimus94d94412022-02-02 09:05:02 +01001880bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1881 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1882 AudioPatchCollection msdPatches = getMsdOutputPatches();
1883 for (size_t i = 0; i < msdPatches.size(); i++) {
1884 const auto& patch = msdPatches[i];
1885 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1886 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1887 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1888 const auto& foundDevice = devicesToCheck.getDevice(
1889 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1890 if (foundDevice != nullptr) {
1891 devicesToCheck.remove(foundDevice);
1892 if (devicesToCheck.isEmpty()) {
1893 return true;
1894 }
1895 }
1896 }
1897 }
1898 }
1899 return false;
1900}
1901
Eric Laurente0720872014-03-11 09:30:41 -07001902audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001903 audio_output_flags_t flags,
1904 audio_format_t format,
1905 audio_channel_mask_t channelMask,
1906 uint32_t samplingRate,
1907 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001908{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001909 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1910 "%s called with format %#x", __func__, format);
1911
jiabinebb6af42020-06-09 17:31:17 -07001912 // Return the output that haptic-generating attached to when 1) session id is specified,
1913 // 2) haptic-generating effect exists for given session id and 3) the output that
1914 // haptic-generating effect attached to is in given outputs.
1915 if (sessionId != AUDIO_SESSION_NONE) {
1916 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1917 sessionId, FX_IID_HAPTICGENERATOR);
1918 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1919 return hapticGeneratingOutput;
1920 }
1921 }
1922
Eric Laurent16c66dd2019-05-01 17:54:10 -07001923 // Flags disqualifying an output: the match must happen before calling selectOutput()
1924 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1925 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1926
1927 // Flags expressing a functional request: must be honored in priority over
1928 // other criteria
1929 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1930 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001931 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1932 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001933 // Flags expressing a performance request: have lower priority than serving
1934 // requested sampling rate or channel mask
1935 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1936 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1937 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1938
1939 const audio_output_flags_t functionalFlags =
1940 (audio_output_flags_t)(flags & kFunctionalFlags);
1941 const audio_output_flags_t performanceFlags =
1942 (audio_output_flags_t)(flags & kPerformanceFlags);
1943
1944 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1945
Eric Laurente552edb2014-03-10 17:42:56 -07001946 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001947 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001948 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001949 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001950 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001951 // with tiebreak preferring the minimum number of extra functional flags
1952 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953 // 3: the output supporting the exact channel mask
1954 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001955 // 5: the output with the highest sampling rate if the requested sample rate is
1956 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001957 // 6: the output with the highest number of requested performance flags
1958 // 7: the output with the bit depth the closest to the requested one
1959 // 8: the primary output
1960 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001961
Eric Laurent16c66dd2019-05-01 17:54:10 -07001962 // matching criteria values in priority order for best matching output so far
1963 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001964
Eric Laurent16c66dd2019-05-01 17:54:10 -07001965 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1966 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1967 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001968
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001969 for (audio_io_handle_t output : outputs) {
1970 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001971 // matching criteria values in priority order for current output
1972 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001973
Eric Laurent16c66dd2019-05-01 17:54:10 -07001974 if (outputDesc->isDuplicated()) {
1975 continue;
1976 }
1977 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1978 continue;
1979 }
Eric Laurent8838a382014-09-08 16:44:28 -07001980
Eric Laurent16c66dd2019-05-01 17:54:10 -07001981 // If haptic channel is specified, use the haptic output if present.
1982 // When using haptic output, same audio format and sample rate are required.
1983 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001984 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001985 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1986 continue;
1987 }
1988 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001989 && format == outputDesc->getFormat()
1990 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001991 currentMatchCriteria[0] = outputHapticChannelCount;
1992 }
1993
1994 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001995 const int matchingFunctionalFlags =
1996 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1997 const int totalFunctionalFlags =
1998 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1999 // Prefer matching functional flags, but subtract unnecessary functional flags.
2000 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002001
2002 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002003 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2004 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002005 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2006 channelCount <= outputChannelCount) {
2007 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002008 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2009 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002010 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002011 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002012 currentMatchCriteria[3] = outputChannelCount;
2013 }
2014
2015 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002016 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002017 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002018 }
2019
2020 // performance flags match
2021 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2022
2023 // format match
2024 if (format != AUDIO_FORMAT_INVALID) {
2025 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002026 PolicyAudioPort::kFormatDistanceMax -
2027 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002028 }
2029
2030 // primary output match
2031 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2032
2033 // compare match criteria by priority then value
2034 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2035 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2036 bestMatchCriteria = currentMatchCriteria;
2037 bestOutput = output;
2038
2039 std::stringstream result;
2040 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2041 std::ostream_iterator<int>(result, " "));
2042 ALOGV("%s new bestOutput %d criteria %s",
2043 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002044 }
2045 }
2046
Eric Laurent16c66dd2019-05-01 17:54:10 -07002047 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002048}
2049
Eric Laurent8fc147b2018-07-22 19:13:55 -07002050status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002051{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002052 ALOGV("%s portId %d", __FUNCTION__, portId);
2053
2054 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2055 if (outputDesc == 0) {
2056 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002057 return BAD_VALUE;
2058 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002059 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002060
Eric Laurent8fc147b2018-07-22 19:13:55 -07002061 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002062 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002063
Eric Laurent733ce942017-12-07 12:18:25 -08002064 status_t status = outputDesc->start();
2065 if (status != NO_ERROR) {
2066 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002067 }
2068
Eric Laurent97ac8712018-07-27 18:59:02 -07002069 uint32_t delayMs;
2070 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002071
2072 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002073 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002074 if (status == DEAD_OBJECT) {
2075 sp<SwAudioOutputDescriptor> desc =
2076 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2077 if (desc == nullptr) {
2078 // This is not common, it may indicate something wrong with the HAL.
2079 ALOGE("%s unable to open output with default config", __func__);
2080 return status;
2081 }
2082 desc->mUsePreferredMixerAttributes = true;
2083 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002084 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002085 }
jiabina84c3d32022-12-02 18:59:55 +00002086
2087 // If the client is the first one active on preferred mixer parameters, reopen the output
2088 // if the current mixer parameters doesn't match the preferred one.
2089 if (outputDesc->devices().size() == 1) {
2090 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2091 outputDesc->devices()[0]->getId(), client->strategy());
2092 if (info != nullptr && info->getUid() == client->uid()) {
2093 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2094 info->getConfigBase(), info->getFlags())) {
2095 stopSource(outputDesc, client);
2096 outputDesc->stop();
2097 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2098 config.channel_mask = info->getConfigBase().channel_mask;
2099 config.sample_rate = info->getConfigBase().sample_rate;
2100 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002101 sp<SwAudioOutputDescriptor> desc =
2102 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2103 if (desc == nullptr) {
2104 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002105 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002106 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002107 // Intentionally return error to let the client side resending request for
2108 // creating and starting.
2109 return DEAD_OBJECT;
2110 }
2111 info->increaseActiveClient();
2112 }
2113 }
2114
Eric Laurentc75307b2015-03-17 15:29:32 -07002115 if (delayMs != 0) {
2116 usleep(delayMs * 1000);
2117 }
2118
2119 return status;
2120}
2121
Eric Laurent96d1dda2022-03-14 17:14:19 +01002122bool AudioPolicyManager::isLeUnicastActive() const {
2123 if (isInCall()) {
2124 return true;
2125 }
2126 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2127}
2128
2129bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2130 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2131 return false;
2132 }
2133 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2134 ALOGV("%s active %d", __func__, active);
2135 return active;
2136}
2137
Eric Laurent97ac8712018-07-27 18:59:02 -07002138status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2139 const sp<TrackClientDescriptor>& client,
2140 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002141{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002142 // cannot start playback of STREAM_TTS if any other output is being used
2143 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002144
2145 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002146 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002147 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002148 auto clientStrategy = client->strategy();
2149 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002150 if (stream == AUDIO_STREAM_TTS) {
2151 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002152 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002153 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002154 return INVALID_OPERATION;
2155 } else {
2156 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2157 }
2158 } else {
2159 // some playback other than beacon starts
2160 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2161 }
2162
Eric Laurent77305a62016-07-25 16:39:22 -07002163 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002164 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002165 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002166
François Gaffie11d30102018-11-02 16:09:09 +01002167 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002168 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002169 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002170 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002171 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002172 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002173 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002174 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002175 } else {
2176 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002177 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002178 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2179 AUDIO_FORMAT_DEFAULT);
2180 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2181 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002182 }
2183
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002184 // requiresMuteCheck is false when we can bypass mute strategy.
2185 // It covers a common case when there is no materially active audio
2186 // and muting would result in unnecessary delay and dropped audio.
2187 const uint32_t outputLatencyMs = outputDesc->latency();
2188 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002189 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002190
Eric Laurente552edb2014-03-10 17:42:56 -07002191 // increment usage count for this stream on the requested output:
2192 // NOTE that the usage count is the same for duplicated output and hardware output which is
2193 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002194 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002195
2196 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002197 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2198 client->isPreferredDeviceForExclusiveUse()) {
2199 // Preferred device may be exclusive, use only if no other active clients on this output
2200 devices = DeviceVector(
2201 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2202 } else {
2203 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2204 }
François Gaffie11d30102018-11-02 16:09:09 +01002205 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002206 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002207 }
2208 }
Eric Laurente552edb2014-03-10 17:42:56 -07002209
François Gaffiec005e562018-11-06 15:04:49 +01002210 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002211 selectOutputForMusicEffects();
2212 }
2213
François Gaffie1c878552018-11-22 16:53:21 +01002214 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002215 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002216 if (devices.isEmpty()) {
2217 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002218 }
François Gaffiec005e562018-11-06 15:04:49 +01002219 bool shouldWait =
2220 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2221 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2222 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002223 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002224 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002225 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002226 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002227 // An output has a shared device if
2228 // - managed by the same hw module
2229 // - supports the currently selected device
2230 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002231 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002232
Eric Laurent77305a62016-07-25 16:39:22 -07002233 // force a device change if any other output is:
2234 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002235 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002236 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002237 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002238 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002239 // change the device currently selected by the other output.
2240 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002241 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002242 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002243 force = true;
2244 }
2245 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002246 // a notification so that audio focus effect can propagate, or that a mute/unmute
2247 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002248 const uint32_t latencyMs = desc->latency();
2249 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2250
2251 if (shouldWait && isActive && (waitMs < latencyMs)) {
2252 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002253 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002254
2255 // Require mute check if another output is on a shared device
2256 // and currently active to have proper drain and avoid pops.
2257 // Note restoring AudioTracks onto this output needs to invoke
2258 // a volume ramp if there is no mute.
2259 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002260 }
2261 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002262
jiabin3ff8d7d2022-12-13 06:27:44 +00002263 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2264 // If the output is open with preferred mixer attributes, but the routed device is
2265 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2266 // changed.
2267 return DEAD_OBJECT;
2268 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002269 const uint32_t muteWaitMs =
jiabin3ff8d7d2022-12-13 06:27:44 +00002270 setOutputDevices(outputDesc, devices, force, 0, nullptr, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002271
Eric Laurente552edb2014-03-10 17:42:56 -07002272 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002273 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002274 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002275 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002276 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002277 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002278 outputDesc->useHwGain() /*force*/)) {
2279 // request AudioService to reinitialize the volume curves asynchronously
2280 ALOGE("checkAndSetVolume failed, requesting volume range init");
2281 mpClientInterface->onVolumeRangeInitRequest();
2282 };
Eric Laurente552edb2014-03-10 17:42:56 -07002283
2284 // update the outputs if starting an output with a stream that can affect notification
2285 // routing
2286 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002287
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002288 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002289 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002290 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2291 }
Eric Laurentdc462862016-07-19 12:29:53 -07002292
2293 if (waitMs > muteWaitMs) {
2294 *delayMs = waitMs - muteWaitMs;
2295 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002296
2297 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2298 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2299 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2300 // change occurs after the MixerThread starts and causes a stream volume
2301 // glitch.
2302 //
2303 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002304 }
Eric Laurentdc462862016-07-19 12:29:53 -07002305
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002306 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002307 mEngine->getForceUse(
2308 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002309 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002310 }
2311
Eric Laurent97ac8712018-07-27 18:59:02 -07002312 // Automatically enable the remote submix input when output is started on a re routing mix
2313 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002314 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2315 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002316 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2317 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2318 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002319 "remote-submix",
2320 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002321 }
2322
Eric Laurent96d1dda2022-03-14 17:14:19 +01002323 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2324
Eric Laurente552edb2014-03-10 17:42:56 -07002325 return NO_ERROR;
2326}
2327
Eric Laurent96d1dda2022-03-14 17:14:19 +01002328void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2329 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2330 bool isUnicastActive = isLeUnicastActive();
2331
2332 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002333 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002334 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2335 for (size_t i = 0; i < mOutputs.size(); i++) {
2336 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2337 if (desc != ignoredOutput && desc->isActive()
2338 && ((isUnicastActive &&
2339 !desc->devices().
2340 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2341 || (wasUnicastActive &&
2342 !desc->devices().getDevicesFromTypes(
2343 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2344 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2345 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002346 if (desc->mUsePreferredMixerAttributes && force) {
2347 // If the device is using preferred mixer attributes, the output need to reopen
2348 // with default configuration when the new selected devices are different from
2349 // current routing devices.
2350 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2351 continue;
2352 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002353 setOutputDevices(desc, newDevices, force, delayMs);
2354 // re-apply device specific volume if not done by setOutputDevice()
2355 if (!force) {
2356 applyStreamVolumes(desc, newDevices.types(), delayMs);
2357 }
2358 }
2359 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002360 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002361 }
2362}
2363
Eric Laurent8fc147b2018-07-22 19:13:55 -07002364status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002365{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002366 ALOGV("%s portId %d", __FUNCTION__, portId);
2367
2368 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2369 if (outputDesc == 0) {
2370 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002371 return BAD_VALUE;
2372 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002373 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002374
Eric Laurent97ac8712018-07-27 18:59:02 -07002375 ALOGV("stopOutput() output %d, stream %d, session %d",
2376 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002377
Eric Laurent97ac8712018-07-27 18:59:02 -07002378 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002379
Eric Laurent733ce942017-12-07 12:18:25 -08002380 if (status == NO_ERROR ) {
2381 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002382 } else {
2383 return status;
2384 }
2385
2386 if (outputDesc->devices().size() == 1) {
2387 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2388 outputDesc->devices()[0]->getId(), client->strategy());
2389 if (info != nullptr && info->getUid() == client->uid()) {
2390 info->decreaseActiveClient();
2391 if (info->getActiveClientCount() == 0) {
2392 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2393 }
2394 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002395 }
2396 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002397}
2398
Eric Laurent97ac8712018-07-27 18:59:02 -07002399status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2400 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002401{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002402 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002403 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002404 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002405 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002406
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002407 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2408
François Gaffie1c878552018-11-22 16:53:21 +01002409 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2410 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002411 // Automatically disable the remote submix input when output is stopped on a
2412 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002413 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002414 if (isSingleDeviceType(
2415 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002416 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002417 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002418 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2419 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002420 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002421 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002422 }
2423 }
2424 bool forceDeviceUpdate = false;
2425 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002426 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002427 forceDeviceUpdate = true;
2428 }
2429
Eric Laurente552edb2014-03-10 17:42:56 -07002430 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002431 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002432
Eric Laurente552edb2014-03-10 17:42:56 -07002433 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002434 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002435 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002436 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002437
2438 // If the routing does not change, if an output is routed on a device using HwGain
2439 // (aka setAudioPortConfig) and there are still active clients following different
2440 // volume group(s), force reapply volume
2441 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2442 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2443
Eric Laurente552edb2014-03-10 17:42:56 -07002444 // delay the device switch by twice the latency because stopOutput() is executed when
2445 // the track stop() command is received and at that time the audio track buffer can
2446 // still contain data that needs to be drained. The latency only covers the audio HAL
2447 // and kernel buffers. Also the latency does not always include additional delay in the
2448 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002449 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2450 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002451
2452 // force restoring the device selection on other active outputs if it differs from the
2453 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002454 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002455 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002456 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002457 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002458 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002459 desc->isActive() &&
2460 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002461 (newDevices != desc->devices())) {
2462 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2463 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002464
jiabin3ff8d7d2022-12-13 06:27:44 +00002465 if (desc->mUsePreferredMixerAttributes && force) {
2466 // If the device is using preferred mixer attributes, the output need to
2467 // reopen with default configuration when the new selected devices are
2468 // different from current routing devices.
2469 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2470 continue;
2471 }
François Gaffie11d30102018-11-02 16:09:09 +01002472 setOutputDevices(desc, newDevices2, force, delayMs);
2473
Eric Laurent57de36c2016-09-28 16:59:11 -07002474 // re-apply device specific volume if not done by setOutputDevice()
2475 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002476 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002477 }
Eric Laurente552edb2014-03-10 17:42:56 -07002478 }
2479 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002480 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002481 // update the outputs if stopping one with a stream that can affect notification routing
2482 handleNotificationRoutingForStream(stream);
2483 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002484
2485 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2486 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002487 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002488 }
2489
François Gaffiec005e562018-11-06 15:04:49 +01002490 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002491 selectOutputForMusicEffects();
2492 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002493
2494 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2495
Eric Laurente552edb2014-03-10 17:42:56 -07002496 return NO_ERROR;
2497 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002498 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002499 return INVALID_OPERATION;
2500 }
2501}
2502
jiabinbce0c1d2020-10-05 11:20:18 -07002503bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002504{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002505 ALOGV("%s portId %d", __FUNCTION__, portId);
2506
2507 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2508 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002509 // If an output descriptor is closed due to a device routing change,
2510 // then there are race conditions with releaseOutput from tracks
2511 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2512 // destroyed shortly thereafter.
2513 //
2514 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002515 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002516 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002517 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002518
2519 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002520
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302521 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2522 if (outputDesc->isClientActive(client)) {
2523 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2524 stopOutput(portId);
2525 }
2526
Eric Laurent8fc147b2018-07-22 19:13:55 -07002527 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2528 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002529 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002530 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002531 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002532 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002533 if (--outputDesc->mDirectOpenCount == 0) {
2534 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002535 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002536 }
2537 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302538
Andy Hung39efb7a2018-09-26 15:39:28 -07002539 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002540 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2541 // The output is pending reopened to query dynamic profiles and
2542 // there is no active clients
2543 closeOutput(outputDesc->mIoHandle);
2544 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2545 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2546 if (newOutputDesc == nullptr) {
2547 ALOGE("%s failed to open output", __func__);
2548 }
2549 return true;
2550 }
2551 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002552}
2553
Eric Laurentcaf7f482014-11-25 17:50:47 -08002554status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2555 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002556 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002557 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002558 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002559 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002560 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002561 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002562 input_type_t *inputType,
2563 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002564{
François Gaffiec005e562018-11-06 15:04:49 +01002565 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002566 "flags %#x attributes=%s requested device ID %d",
2567 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2568 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002569
Eric Laurentad2e7b92017-09-14 20:06:42 -07002570 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002571 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002572 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002573 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002574 sp<AudioInputDescriptor> inputDesc;
2575 sp<RecordClientDescriptor> clientDesc;
2576 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002577 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002578 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002579
2580 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2581 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2582 return INVALID_OPERATION;
2583 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002584
Francois Gaffie716e1432019-01-14 16:58:59 +01002585 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2586 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002587 }
2588
Paul McLean466dc8e2015-04-17 13:15:36 -06002589 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002590 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002591 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002592
Eric Laurentad2e7b92017-09-14 20:06:42 -07002593 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2594 // possible
2595 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2596 *input != AUDIO_IO_HANDLE_NONE) {
2597 ssize_t index = mInputs.indexOfKey(*input);
2598 if (index < 0) {
2599 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2600 status = BAD_VALUE;
2601 goto error;
2602 }
2603 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002604 RecordClientVector clients = inputDesc->getClientsForSession(session);
2605 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002606 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2607 status = BAD_VALUE;
2608 goto error;
2609 }
2610 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2611 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002612 // corresponds to a new client and is only permitted from the same UID.
2613 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002614 if (clients.size() > 1) {
2615 for (const auto& client : clients) {
2616 // The client map is ordered by key values (portId) and portIds are allocated
2617 // incrementaly. So the first client in this list is the one opened by audio flinger
2618 // when the mmap stream is created and should be ignored as it does not correspond
2619 // to an actual client
2620 if (client == *clients.cbegin()) {
2621 continue;
2622 }
2623 if (uid != client->uid() && !client->isSilenced()) {
2624 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2625 uid, client->portId(), client->uid());
2626 status = INVALID_OPERATION;
2627 goto error;
2628 }
Eric Laurent331679c2018-04-16 17:03:16 -07002629 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002630 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002631 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002632 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002633
Eric Laurentfecbceb2021-02-09 14:46:43 +01002634 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002635 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002636 }
2637
2638 *input = AUDIO_IO_HANDLE_NONE;
2639 *inputType = API_INPUT_INVALID;
2640
Francois Gaffie716e1432019-01-14 16:58:59 +01002641 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002642 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002643 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002644 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002645 ALOGW("%s could not find input mix for attr %s",
2646 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002647 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002648 }
jiabinc1de2df2019-05-07 14:26:40 -07002649 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2650 String8(attr->tags + strlen("addr=")),
2651 AUDIO_FORMAT_DEFAULT);
2652 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002653 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002654 __func__, attributes.source, attributes.tags);
2655 status = BAD_VALUE;
2656 goto error;
2657 }
2658
Kevin Rocard25f9b052019-02-27 15:08:54 -08002659 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2660 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2661 } else {
2662 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2663 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002664 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002665 if (explicitRoutingDevice != nullptr) {
2666 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002667 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002668 // Prevent from storing invalid requested device id in clients
2669 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002670 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002671 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2672 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002673 }
François Gaffie11d30102018-11-02 16:09:09 +01002674 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002675 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002676 status = BAD_VALUE;
2677 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002678 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002679 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2680 *inputType = API_INPUT_MIX_CAPTURE;
2681 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002682 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2683 // there is an external policy, but this input is attached to a mix of recorders,
2684 // meaning it receives audio injected into the framework, so the recorder doesn't
2685 // know about it and is therefore considered "legacy"
2686 *inputType = API_INPUT_LEGACY;
2687 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002688 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002689 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002690 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002691 } else {
2692 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002693 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002694
Eric Laurent599c7582015-12-07 18:05:55 -08002695 }
2696
François Gaffiec005e562018-11-06 15:04:49 +01002697 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002698 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002699 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002700 AudioProfileVector profiles;
2701 status_t ret = getProfilesForDevices(
2702 DeviceVector(device), profiles, flags, true /*isInput*/);
2703 if (ret == NO_ERROR && !profiles.empty()) {
2704 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2705 : *profiles[0]->getChannels().begin();
2706 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2707 : *profiles[0]->getSampleRates().begin();
2708 config->format = profiles[0]->getFormat();
2709 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002710 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002711 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002712
Eric Laurent8f42ea12018-08-08 09:08:25 -07002713exit:
2714
François Gaffiec005e562018-11-06 15:04:49 +01002715 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2716 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002717
Francois Gaffie716e1432019-01-14 16:58:59 +01002718 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002719 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002720 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002721
Mikhail Naganov2996f672019-04-18 12:29:59 -07002722 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002723 requestedDeviceId, attributes.source, flags,
2724 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002725 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002726 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002727
2728 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2729 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002730
Eric Laurent599c7582015-12-07 18:05:55 -08002731 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002732
2733error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002734 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002735}
2736
2737
François Gaffie11d30102018-11-02 16:09:09 +01002738audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002739 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002740 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002741 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002742 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002743 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002744{
2745 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002746 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002747 bool isSoundTrigger = false;
2748
François Gaffiec005e562018-11-06 15:04:49 +01002749 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002750 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2751 if (index >= 0) {
2752 input = mSoundTriggerSessions.valueFor(session);
2753 isSoundTrigger = true;
2754 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2755 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2756 } else {
2757 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002758 }
François Gaffiec005e562018-11-06 15:04:49 +01002759 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002760 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002761 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002762 }
2763
Carter Hsua3abb402021-10-26 11:11:20 +08002764 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2765 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2766 }
2767
Eric Laurentfe231122017-11-17 17:48:06 -08002768 // sampling rate and flags may be updated by getInputProfile
2769 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2770 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002771 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002772 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002773 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002774 // find a compatible input profile (not necessarily identical in parameters)
2775 sp<IOProfile> profile = getInputProfile(
2776 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2777 if (profile == nullptr) {
2778 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002779 }
jiabin2fd710d2022-05-02 23:20:22 +00002780
Glenn Kasten05ddca52016-02-11 08:17:12 -08002781 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002782 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002783 if (samplingRate == 0) {
2784 samplingRate = profileSamplingRate;
2785 }
Eric Laurente552edb2014-03-10 17:42:56 -07002786
Eric Laurent322b4d22015-04-03 15:57:54 -07002787 if (profile->getModuleHandle() == 0) {
2788 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002789 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002790 }
2791
Eric Laurentec376dc2021-04-08 20:41:22 +02002792 // Reuse an already opened input if a client with the same session ID already exists
2793 // on that input
2794 for (size_t i = 0; i < mInputs.size(); i++) {
2795 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2796 if (desc->mProfile != profile) {
2797 continue;
2798 }
2799 RecordClientVector clients = desc->clientsList();
2800 for (const auto &client : clients) {
2801 if (session == client->session()) {
2802 return desc->mIoHandle;
2803 }
2804 }
2805 }
2806
Eric Laurent3974e3b2017-12-07 17:58:43 -08002807 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002808 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002809 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002810 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002811 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002812 continue;
2813 }
2814 // if sound trigger, reuse input if used by other sound trigger on same session
2815 // else
2816 // reuse input if active client app is not in IDLE state
2817 //
2818 RecordClientVector clients = desc->clientsList();
2819 bool doClose = false;
2820 for (const auto& client : clients) {
2821 if (isSoundTrigger != client->isSoundTrigger()) {
2822 continue;
2823 }
2824 if (client->isSoundTrigger()) {
2825 if (session == client->session()) {
2826 return desc->mIoHandle;
2827 }
2828 continue;
2829 }
2830 if (client->active() && client->appState() != APP_STATE_IDLE) {
2831 return desc->mIoHandle;
2832 }
2833 doClose = true;
2834 }
2835 if (doClose) {
2836 closeInput(desc->mIoHandle);
2837 } else {
2838 i++;
2839 }
2840 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002841 }
2842
Eric Laurentfe231122017-11-17 17:48:06 -08002843 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002844
Eric Laurentfe231122017-11-17 17:48:06 -08002845 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2846 lConfig.sample_rate = profileSamplingRate;
2847 lConfig.channel_mask = profileChannelMask;
2848 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002849
François Gaffie11d30102018-11-02 16:09:09 +01002850 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002851
2852 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002853 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002854 (profileSamplingRate != lConfig.sample_rate) ||
2855 !audio_formats_match(profileFormat, lConfig.format) ||
2856 (profileChannelMask != lConfig.channel_mask)) {
2857 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002858 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002859 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002860 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002861 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002862 }
Eric Laurent599c7582015-12-07 18:05:55 -08002863 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002864 }
2865
Eric Laurentc722f302014-12-10 11:21:49 -08002866 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002867
Eric Laurent599c7582015-12-07 18:05:55 -08002868 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002869 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002870
Eric Laurent599c7582015-12-07 18:05:55 -08002871 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002872}
2873
Eric Laurent4eb58f12018-12-07 16:41:02 -08002874status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002875{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002876 ALOGV("%s portId %d", __FUNCTION__, portId);
2877
2878 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2879 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002880 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002881 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002882 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002883 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002884 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002885 if (client->active()) {
2886 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2887 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002888 }
2889
Eric Laurent8f42ea12018-08-08 09:08:25 -07002890 audio_session_t session = client->session();
2891
Eric Laurent4eb58f12018-12-07 16:41:02 -08002892 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002893
Eric Laurent4eb58f12018-12-07 16:41:02 -08002894 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002895
Eric Laurent4eb58f12018-12-07 16:41:02 -08002896 status_t status = inputDesc->start();
2897 if (status != NO_ERROR) {
2898 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002899 }
Eric Laurente552edb2014-03-10 17:42:56 -07002900
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002901 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002902 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002903 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002904
Eric Laurent8f42ea12018-08-08 09:08:25 -07002905 // indicate active capture to sound trigger service if starting capture from a mic on
2906 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002907 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002908 if (device != nullptr) {
2909 status = setInputDevice(input, device, true /* force */);
2910 } else {
2911 ALOGW("%s no new input device can be found for descriptor %d",
2912 __FUNCTION__, inputDesc->getId());
2913 status = BAD_VALUE;
2914 }
Eric Laurente552edb2014-03-10 17:42:56 -07002915
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002916 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002917 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002918 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002919 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002920 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2921 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002922 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002923 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002924
François Gaffie11d30102018-11-02 16:09:09 +01002925 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2926 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002927 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002928 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002929 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002930
Eric Laurent8f42ea12018-08-08 09:08:25 -07002931 // automatically enable the remote submix output when input is started if not
2932 // used by a policy mix of type MIX_TYPE_RECORDERS
2933 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002934 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002935 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002936 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002937 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002938 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2939 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002940 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002941 if (address != "") {
2942 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2943 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002944 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002945 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002946 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002947 } else if (status != NO_ERROR) {
2948 // Restore client activity state.
2949 inputDesc->setClientActive(client, false);
2950 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002951 }
2952
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002953 ALOGV("%s input %d source = %d status = %d exit",
2954 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002955
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002956 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002957}
2958
Eric Laurent8fc147b2018-07-22 19:13:55 -07002959status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002960{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002961 ALOGV("%s portId %d", __FUNCTION__, portId);
2962
2963 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2964 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002965 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002966 return BAD_VALUE;
2967 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002968 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002969 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002970 if (!client->active()) {
2971 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002972 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002973 }
Carter Hsue6139d52021-07-08 10:30:20 +08002974 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002975 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002976
Eric Laurent8f42ea12018-08-08 09:08:25 -07002977 inputDesc->stop();
2978 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002979 auto current_source = inputDesc->source();
2980 setInputDevice(input, getNewInputDevice(inputDesc),
2981 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002982 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002983 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002984 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002985 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002986 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2987 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002988 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002989 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002990
2991 // automatically disable the remote submix output when input is stopped if not
2992 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002993 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002994 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002995 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002996 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002997 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2998 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002999 }
3000 if (address != "") {
3001 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3002 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003003 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003004 }
3005 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003006 resetInputDevice(input);
3007
3008 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3009 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003010 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3011 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003012 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003013 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003014 }
3015 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003016 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003017 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003018}
3019
Eric Laurent8fc147b2018-07-22 19:13:55 -07003020void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003021{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003022 ALOGV("%s portId %d", __FUNCTION__, portId);
3023
3024 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3025 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003026 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003027 return;
3028 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003029 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003030 audio_io_handle_t input = inputDesc->mIoHandle;
3031
Eric Laurent8f42ea12018-08-08 09:08:25 -07003032 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003033
Andy Hung39efb7a2018-09-26 15:39:28 -07003034 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08003035
Andy Hung39efb7a2018-09-26 15:39:28 -07003036 if (inputDesc->getClientCount() > 0) {
3037 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003038 return;
3039 }
3040
Eric Laurent05b90f82014-08-27 15:32:29 -07003041 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003042 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003043 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003044}
3045
Eric Laurent8f42ea12018-08-08 09:08:25 -07003046void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003047{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003048 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003049
3050 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003051 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003052 }
3053}
3054
Eric Laurent8f42ea12018-08-08 09:08:25 -07003055void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3056{
3057 stopInput(portId);
3058 releaseInput(portId);
3059}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003060
Eric Laurent0dd51852019-04-19 18:18:58 -07003061void AudioPolicyManager::checkCloseInputs() {
3062 // After connecting or disconnecting an input device, close input if:
3063 // - it has no client (was just opened to check profile) OR
3064 // - none of its supported devices are connected anymore OR
3065 // - one of its clients cannot be routed to one of its supported
3066 // devices anymore. Otherwise update device selection
3067 std::vector<audio_io_handle_t> inputsToClose;
3068 for (size_t i = 0; i < mInputs.size(); i++) {
3069 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3070 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003071 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003072 inputsToClose.push_back(mInputs.keyAt(i));
3073 } else {
3074 bool close = false;
3075 for (const auto& client : input->clientsList()) {
3076 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003077 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3078 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003079 if (!input->supportedDevices().contains(device)) {
3080 close = true;
3081 break;
3082 }
3083 }
3084 if (close) {
3085 inputsToClose.push_back(mInputs.keyAt(i));
3086 } else {
3087 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3088 }
3089 }
3090 }
3091
3092 for (const audio_io_handle_t handle : inputsToClose) {
3093 ALOGV("%s closing input %d", __func__, handle);
3094 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003095 }
Eric Laurentd4692962014-05-05 18:13:44 -07003096}
3097
François Gaffie251c7f02018-11-07 10:41:08 +01003098void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003099{
3100 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003101 if (indexMin < 0 || indexMax < 0) {
3102 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3103 return;
3104 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003105 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003106
3107 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003108 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3109 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003110 continue;
3111 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003112 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003113 }
Eric Laurente552edb2014-03-10 17:42:56 -07003114}
3115
Eric Laurente0720872014-03-11 09:30:41 -07003116status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003117 int index,
3118 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003119{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003120 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003121 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3122 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3123 return NO_ERROR;
3124 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003125 ALOGV("%s: stream %s attributes=%s", __func__,
3126 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003127 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003128}
3129
Eric Laurente0720872014-03-11 09:30:41 -07003130status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003131 int *index,
3132 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003133{
François Gaffiec005e562018-11-06 15:04:49 +01003134 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3135 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003136 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003137 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003138 deviceTypes = mEngine->getOutputDevicesForStream(
3139 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003140 }
jiabin9a3361e2019-10-01 09:38:30 -07003141 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003142}
3143
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003144status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003145 int index,
3146 audio_devices_t device)
3147{
3148 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003149 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3150 if (group == VOLUME_GROUP_NONE) {
3151 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003152 return BAD_VALUE;
3153 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003154 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003155 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003156 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003157 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003158 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3159 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3160 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3161 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003162 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3163
3164 status = setVolumeCurveIndex(index, device, curves);
3165 if (status != NO_ERROR) {
3166 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3167 return status;
3168 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003169
jiabin9a3361e2019-10-01 09:38:30 -07003170 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003171 auto curCurvAttrs = curves.getAttributes();
3172 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3173 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003174 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003175 } else if (!curves.getStreamTypes().empty()) {
3176 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003177 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003178 } else {
3179 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3180 return BAD_VALUE;
3181 }
jiabin9a3361e2019-10-01 09:38:30 -07003182 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3183 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003184
François Gaffiecfe17322018-11-07 13:41:29 +01003185 // update volume on all outputs and streams matching the following:
3186 // - The requested stream (or a stream matching for volume control) is active on the output
3187 // - The device (or devices) selected by the engine for this stream includes
3188 // the requested device
3189 // - For non default requested device, currently selected device on the output is either the
3190 // requested device or one of the devices selected by the engine for this stream
3191 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3192 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003193 for (size_t i = 0; i < mOutputs.size(); i++) {
3194 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003195 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003196
jiabin9a3361e2019-10-01 09:38:30 -07003197 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3198 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003199 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003200
3201 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003202 continue;
3203 }
3204 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3205 curDevices.find(device) == curDevices.end()) {
3206 continue;
3207 }
3208 bool applyVolume = false;
3209 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3210 curSrcDevices.insert(device);
3211 applyVolume = (curSrcDevices.find(
3212 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3213 } else {
3214 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3215 }
3216 if (!applyVolume) {
3217 continue; // next output
3218 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003219 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3220 // If a higher priority strategy is active, and the output is routed to a device with a
3221 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003222 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003223 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003224 // If the volume source is active with higher priority source, ensure at least Sw Muted
3225 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003226 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3227 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3228 false /*preferredDevice*/);
3229 if (activeClients.empty()) {
3230 continue;
3231 }
3232 bool isPreempted = false;
3233 bool isHigherPriority = productStrategy < strategy;
3234 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003235 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003236 ALOGV("%s: Strategy=%d (\nrequester:\n"
3237 " group %d, volumeGroup=%d attributes=%s)\n"
3238 " higher priority source active:\n"
3239 " volumeGroup=%d attributes=%s) \n"
3240 " on output %zu, bailing out", __func__, productStrategy,
3241 group, group, toString(attributes).c_str(),
3242 client->volumeSource(), toString(client->attributes()).c_str(), i);
3243 applyVolume = false;
3244 isPreempted = true;
3245 break;
3246 }
3247 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003248 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003249 applyVolume = true;
3250 }
3251 }
3252 if (isPreempted || applyVolume) {
3253 break;
3254 }
3255 }
3256 if (!applyVolume) {
3257 continue; // next output
3258 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003259 }
François Gaffieed91f582020-01-31 10:35:37 +01003260 //FIXME: workaround for truncated touch sounds
3261 // delayed volume change for system stream to be removed when the problem is
3262 // handled by system UI
3263 status_t volStatus = checkAndSetVolume(
3264 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003265 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003266 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3267 if (volStatus != NO_ERROR) {
3268 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003269 }
3270 }
François Gaffiecfe17322018-11-07 13:41:29 +01003271 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3272 return status;
3273}
3274
François Gaffieaaac0fd2018-11-22 17:56:39 +01003275status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003276 audio_devices_t device,
3277 IVolumeCurves &volumeCurves)
3278{
3279 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3280 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003281 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3282 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003283 (index > volumeCurves.getVolumeIndexMax())) {
3284 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3285 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3286 return BAD_VALUE;
3287 }
3288 if (!audio_is_output_device(device)) {
3289 return BAD_VALUE;
3290 }
3291
3292 // Force max volume if stream cannot be muted
3293 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3294
François Gaffieaaac0fd2018-11-22 17:56:39 +01003295 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003296 volumeCurves.addCurrentVolumeIndex(device, index);
3297 return NO_ERROR;
3298}
3299
3300status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3301 int &index,
3302 audio_devices_t device)
3303{
3304 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3305 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003306 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003307 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003308 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003309 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003310 }
jiabin9a3361e2019-10-01 09:38:30 -07003311 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003312}
3313
3314status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3315 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003316 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003317{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003318 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003319 return BAD_VALUE;
3320 }
jiabin9a3361e2019-10-01 09:38:30 -07003321 index = curves.getVolumeIndex(deviceTypes);
3322 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003323 return NO_ERROR;
3324}
3325
3326status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3327 int &index)
3328{
3329 index = getVolumeCurves(attr).getVolumeIndexMin();
3330 return NO_ERROR;
3331}
3332
3333status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3334 int &index)
3335{
3336 index = getVolumeCurves(attr).getVolumeIndexMax();
3337 return NO_ERROR;
3338}
3339
Eric Laurent36829f92017-04-07 19:04:42 -07003340audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003341{
3342 // select one output among several suitable for global effects.
3343 // The priority is as follows:
3344 // 1: An offloaded output. If the effect ends up not being offloadable,
3345 // AudioFlinger will invalidate the track and the offloaded output
3346 // will be closed causing the effect to be moved to a PCM output.
3347 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003348 // 3: The primary output
3349 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003350
François Gaffiec005e562018-11-06 15:04:49 +01003351 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3352 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003353 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003354
Eric Laurent36829f92017-04-07 19:04:42 -07003355 if (outputs.size() == 0) {
3356 return AUDIO_IO_HANDLE_NONE;
3357 }
Eric Laurente552edb2014-03-10 17:42:56 -07003358
Eric Laurent36829f92017-04-07 19:04:42 -07003359 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3360 bool activeOnly = true;
3361
3362 while (output == AUDIO_IO_HANDLE_NONE) {
3363 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3364 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3365 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3366
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003367 for (audio_io_handle_t output : outputs) {
3368 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003369 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003370 continue;
3371 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003372 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3373 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003374 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003375 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003376 }
3377 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003378 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003379 }
3380 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003381 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003382 }
3383 }
3384 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3385 output = outputOffloaded;
3386 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3387 output = outputDeepBuffer;
3388 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3389 output = outputPrimary;
3390 } else {
3391 output = outputs[0];
3392 }
3393 activeOnly = false;
3394 }
3395
3396 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003397 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003398 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3399 mMusicEffectOutput = output;
3400 }
3401
3402 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003403 return output;
3404}
3405
Eric Laurent36829f92017-04-07 19:04:42 -07003406audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3407{
3408 return selectOutputForMusicEffects();
3409}
3410
Eric Laurente0720872014-03-11 09:30:41 -07003411status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003412 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003413 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003414 int session,
3415 int id)
3416{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003417 if (session != AUDIO_SESSION_DEVICE) {
3418 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003419 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003420 index = mInputs.indexOfKey(io);
3421 if (index < 0) {
3422 ALOGW("registerEffect() unknown io %d", io);
3423 return INVALID_OPERATION;
3424 }
Eric Laurente552edb2014-03-10 17:42:56 -07003425 }
3426 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003427 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3428 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3429 || strategy == PRODUCT_STRATEGY_NONE));
3430 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003431}
3432
Eric Laurentc241b0d2018-11-28 09:08:49 -08003433status_t AudioPolicyManager::unregisterEffect(int id)
3434{
3435 if (mEffects.getEffect(id) == nullptr) {
3436 return INVALID_OPERATION;
3437 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003438 if (mEffects.isEffectEnabled(id)) {
3439 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3440 setEffectEnabled(id, false);
3441 }
3442 return mEffects.unregisterEffect(id);
3443}
3444
3445status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3446{
3447 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3448 if (effect == nullptr) {
3449 return INVALID_OPERATION;
3450 }
3451
3452 status_t status = mEffects.setEffectEnabled(id, enabled);
3453 if (status == NO_ERROR) {
3454 mInputs.trackEffectEnabled(effect, enabled);
3455 }
3456 return status;
3457}
3458
Eric Laurent6c796322019-04-09 14:13:17 -07003459
3460status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3461{
3462 mEffects.moveEffects(ids, io);
3463 return NO_ERROR;
3464}
3465
Eric Laurentc75307b2015-03-17 15:29:32 -07003466bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3467{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003468 auto vs = toVolumeSource(stream, false);
3469 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003470}
3471
3472bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3473{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003474 auto vs = toVolumeSource(stream, false);
3475 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003476}
3477
Eric Laurente0720872014-03-11 09:30:41 -07003478bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003479{
3480 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003481 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003482 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003483 return true;
3484 }
3485 }
3486 return false;
3487}
3488
Eric Laurent275e8e92014-11-30 15:14:47 -08003489// Register a list of custom mixes with their attributes and format.
3490// When a mix is registered, corresponding input and output profiles are
3491// added to the remote submix hw module. The profile contains only the
3492// parameters (sampling rate, format...) specified by the mix.
3493// The corresponding input remote submix device is also connected.
3494//
3495// When a remote submix device is connected, the address is checked to select the
3496// appropriate profile and the corresponding input or output stream is opened.
3497//
3498// When capture starts, getInputForAttr() will:
3499// - 1 look for a mix matching the address passed in attribtutes tags if any
3500// - 2 if none found, getDeviceForInputSource() will:
3501// - 2.1 look for a mix matching the attributes source
3502// - 2.2 if none found, default to device selection by policy rules
3503// At this time, the corresponding output remote submix device is also connected
3504// and active playback use cases can be transferred to this mix if needed when reconnecting
3505// after AudioTracks are invalidated
3506//
3507// When playback starts, getOutputForAttr() will:
3508// - 1 look for a mix matching the address passed in attribtutes tags if any
3509// - 2 if none found, look for a mix matching the attributes usage
3510// - 3 if none found, default to device and output selection by policy rules.
3511
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003512status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003513{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003514 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3515 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003516 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003517 sp<HwModule> rSubmixModule;
3518 // examine each mix's route type
3519 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003520 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003521 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3522 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3523 ALOGE("Unsupported Policy Mix %zu of %zu: "
3524 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3525 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003526 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003527 break;
3528 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003529 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3530 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003531 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003532 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3533 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003534 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003535 rSubmixModule = mHwModules.getModuleFromName(
3536 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3537 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003538 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003539 i);
3540 res = INVALID_OPERATION;
3541 break;
3542 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003543 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003544
Eric Laurent97ac8712018-07-27 18:59:02 -07003545 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003546 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003547 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003548 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003549 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3550 } else {
3551 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3552 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003553 }
François Gaffie036e1e92015-03-19 10:16:24 +01003554
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003555 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003556 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003557 res = INVALID_OPERATION;
3558 break;
3559 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003560 audio_config_t outputConfig = mix.mFormat;
3561 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003562 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3563 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003564 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3565 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003566 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003567 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003568 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003569 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003570
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003571 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003572 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3573 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3574 ALOGE("Failed to set remote submix device available, type %u, address %s",
3575 mix.mDeviceType, address.string());
3576 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003577 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003578 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3579 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003580 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003581 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003582 i, mixes.size(), type, address.string());
3583
3584 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3585 mix.mDeviceType, mix.mDeviceAddress,
3586 String8(), AUDIO_FORMAT_DEFAULT);
3587 if (device == nullptr) {
3588 res = INVALID_OPERATION;
3589 break;
3590 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003591
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003592 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003593 // First try to find an already opened output supporting the device
3594 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003595 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003596
Eric Laurentc529cf62020-04-17 18:19:10 -07003597 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003598 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003599 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3600 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003601 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003602 } else {
3603 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003604 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003605 }
3606 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003607 // If no output found, try to find a direct output profile supporting the device
3608 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3609 sp<HwModule> module = mHwModules[i];
3610 for (size_t j = 0;
3611 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3612 j++) {
3613 sp<IOProfile> profile = module->getOutputProfiles()[j];
3614 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3615 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3616 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3617 address.string());
3618 res = INVALID_OPERATION;
3619 } else {
3620 foundOutput = true;
3621 }
3622 }
3623 }
3624 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003625 if (res != NO_ERROR) {
3626 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003627 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003628 res = INVALID_OPERATION;
3629 break;
3630 } else if (!foundOutput) {
3631 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003632 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003633 res = INVALID_OPERATION;
3634 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003635 } else {
3636 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003637 }
Eric Laurentc722f302014-12-10 11:21:49 -08003638 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003639 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003640 if (res != NO_ERROR) {
3641 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003642 } else if (checkOutputs) {
3643 checkForDeviceAndOutputChanges();
3644 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003645 }
3646 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003647}
3648
3649status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3650{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003651 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003652 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003653 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003654 sp<HwModule> rSubmixModule;
3655 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003656 for (const auto& mix : mixes) {
3657 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003658
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003659 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003660 rSubmixModule = mHwModules.getModuleFromName(
3661 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3662 if (rSubmixModule == 0) {
3663 res = INVALID_OPERATION;
3664 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003665 }
3666 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003667
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003668 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003669
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003670 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003671 res = INVALID_OPERATION;
3672 continue;
3673 }
3674
Kevin Rocard04ed0462019-05-02 17:53:24 -07003675 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3676 if (getDeviceConnectionState(device, address.string()) ==
3677 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3678 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3679 address.string(), "remote-submix",
3680 AUDIO_FORMAT_DEFAULT);
3681 if (res != OK) {
3682 ALOGE("Error making RemoteSubmix device unavailable for mix "
3683 "with type %d, address %s", device, address.string());
3684 }
3685 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003686 }
jiabin5740f082019-08-19 15:08:30 -07003687 rSubmixModule->removeOutputProfile(address.c_str());
3688 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003689
Kevin Rocard153f92d2018-12-18 18:33:28 -08003690 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003691 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003692 res = INVALID_OPERATION;
3693 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003694 } else {
3695 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003696 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003697 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003698 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003699 if (res == NO_ERROR && checkOutputs) {
3700 checkForDeviceAndOutputChanges();
3701 updateCallAndOutputRouting();
3702 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003703 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003704}
3705
Mikhail Naganov100f0122018-11-29 11:22:16 -08003706void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3707{
3708 size_t i = 0;
3709 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3710 for (const auto& fmt : mManualSurroundFormats) {
3711 if (i++ != 0) dst->append(", ");
3712 std::string sfmt;
3713 FormatConverter::toString(fmt, sfmt);
3714 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3715 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3716 }
3717}
3718
Eric Laurentc529cf62020-04-17 18:19:10 -07003719// Returns true if all devices types match the predicate and are supported by one HW module
3720bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003721 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003722 std::function<bool(audio_devices_t)> predicate,
3723 const char *context) {
3724 for (size_t i = 0; i < devices.size(); i++) {
3725 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003726 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003727 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003728 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003729 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003730 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003731 return false;
3732 }
3733 }
3734 return true;
3735}
3736
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003737status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003738 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003739 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003740 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3741 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003742 }
3743 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003744 if (res != NO_ERROR) {
3745 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3746 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003747 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003748
3749 checkForDeviceAndOutputChanges();
3750 updateCallAndOutputRouting();
3751
3752 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003753}
3754
3755status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3756 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003757 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3758 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003759 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003760 __FUNCTION__, uid);
3761 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003762 }
3763
Eric Laurentc529cf62020-04-17 18:19:10 -07003764 checkForDeviceAndOutputChanges();
3765 updateCallAndOutputRouting();
3766
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003767 return res;
3768}
3769
Eric Laurent2517af32020-11-25 15:31:27 +01003770
jiabin0a488932020-08-07 17:32:40 -07003771status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3772 device_role_t role,
3773 const AudioDeviceTypeAddrVector &devices) {
3774 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3775 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003776
Eric Laurentc529cf62020-04-17 18:19:10 -07003777 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003778 return BAD_VALUE;
3779 }
jiabin0a488932020-08-07 17:32:40 -07003780 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003781 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003782 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3783 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003784 return status;
3785 }
3786
3787 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003788
3789 bool forceVolumeReeval = false;
3790 // FIXME: workaround for truncated touch sounds
3791 // to be removed when the problem is handled by system UI
3792 uint32_t delayMs = 0;
3793 if (strategy == mCommunnicationStrategy) {
3794 forceVolumeReeval = true;
3795 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3796 updateInputRouting();
3797 }
3798 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003799
3800 return NO_ERROR;
3801}
3802
3803void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3804{
3805 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003806 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003807 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003808 // Only apply special touch sound delay once
3809 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003810 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003811 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003812 for (size_t i = 0; i < mOutputs.size(); i++) {
3813 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3814 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003815 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3816 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003817 // As done in setDeviceConnectionState, we could also fix default device issue by
3818 // preventing the force re-routing in case of default dev that distinguishes on address.
3819 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003820 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003821 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3822 // If the device is using preferred mixer attributes, the output need to reopen
3823 // with default configuration when the new selected devices are different from
3824 // current routing devices.
3825 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3826 continue;
3827 }
Francois Gaffie601801d2021-06-22 13:27:39 +02003828 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3829 true /*requiresMuteCheck*/,
3830 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003831 // Only apply special touch sound delay once
3832 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003833 }
3834 if (forceVolumeReeval && !newDevices.isEmpty()) {
3835 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3836 }
3837 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003838 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003839 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003840}
3841
Eric Laurent2517af32020-11-25 15:31:27 +01003842void AudioPolicyManager::updateInputRouting() {
3843 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303844 // Skip for hotword recording as the input device switch
3845 // is handled within sound trigger HAL
3846 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3847 continue;
3848 }
Eric Laurent2517af32020-11-25 15:31:27 +01003849 auto newDevice = getNewInputDevice(activeDesc);
3850 // Force new input selection if the new device can not be reached via current input
3851 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3852 setInputDevice(activeDesc->mIoHandle, newDevice);
3853 } else {
3854 closeInput(activeDesc->mIoHandle);
3855 }
3856 }
3857}
3858
jiabin0a488932020-08-07 17:32:40 -07003859status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3860 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003861{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003862 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003863
jiabin0a488932020-08-07 17:32:40 -07003864 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003865 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003866 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3867 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003868 return status;
3869 }
3870
3871 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003872
3873 bool forceVolumeReeval = false;
3874 // FIXME: workaround for truncated touch sounds
3875 // to be removed when the problem is handled by system UI
3876 uint32_t delayMs = 0;
3877 if (strategy == mCommunnicationStrategy) {
3878 forceVolumeReeval = true;
3879 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3880 updateInputRouting();
3881 }
3882 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003883
3884 return NO_ERROR;
3885}
3886
jiabin0a488932020-08-07 17:32:40 -07003887status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3888 device_role_t role,
3889 AudioDeviceTypeAddrVector &devices) {
3890 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003891}
3892
Jiabin Huang3b98d322020-09-03 17:54:16 +00003893status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3894 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3895 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3896 dumpAudioDeviceTypeAddrVector(devices).c_str());
3897
Mikhail Naganov55773032020-10-01 15:08:13 -07003898 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003899 return BAD_VALUE;
3900 }
3901 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3902 ALOGW_IF(status != NO_ERROR,
3903 "Engine could not set preferred devices %s for audio source %d role %d",
3904 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3905
3906 return status;
3907}
3908
3909status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3910 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3911 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3912 dumpAudioDeviceTypeAddrVector(devices).c_str());
3913
Mikhail Naganov55773032020-10-01 15:08:13 -07003914 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003915 return BAD_VALUE;
3916 }
3917 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3918 ALOGW_IF(status != NO_ERROR,
3919 "Engine could not add preferred devices %s for audio source %d role %d",
3920 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3921
Eric Laurent2517af32020-11-25 15:31:27 +01003922 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003923 return status;
3924}
3925
3926status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3927 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3928{
3929 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3930 dumpAudioDeviceTypeAddrVector(devices).c_str());
3931
Mikhail Naganov55773032020-10-01 15:08:13 -07003932 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003933 return BAD_VALUE;
3934 }
3935
3936 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3937 audioSource, role, devices);
3938 ALOGW_IF(status != NO_ERROR,
3939 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3940
Eric Laurent2517af32020-11-25 15:31:27 +01003941 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003942 return status;
3943}
3944
3945status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3946 device_role_t role) {
3947 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3948
3949 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3950 ALOGW_IF(status != NO_ERROR,
3951 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3952
Eric Laurent2517af32020-11-25 15:31:27 +01003953 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003954 return status;
3955}
3956
3957status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3958 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3959 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3960}
3961
Oscar Azucena90e77632019-11-27 17:12:28 -08003962status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003963 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003964 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003965 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3966 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003967 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003968 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3969 if (status != NO_ERROR) {
3970 ALOGE("%s() could not set device affinity for userId %d",
3971 __FUNCTION__, userId);
3972 return status;
3973 }
3974
3975 // reevaluate outputs for all devices
3976 checkForDeviceAndOutputChanges();
3977 updateCallAndOutputRouting();
3978
3979 return NO_ERROR;
3980}
3981
3982status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003983 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003984 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3985 if (status != NO_ERROR) {
3986 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3987 __FUNCTION__, userId);
3988 return status;
3989 }
3990
3991 // reevaluate outputs for all devices
3992 checkForDeviceAndOutputChanges();
3993 updateCallAndOutputRouting();
3994
3995 return NO_ERROR;
3996}
3997
Andy Hungc29d82b2018-10-05 12:23:17 -07003998void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003999{
Andy Hungc29d82b2018-10-05 12:23:17 -07004000 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004001 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004002 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004003 std::string stateLiteral;
4004 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004005 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004006 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4007 "communications", "media", "record", "dock", "system",
4008 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4009 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4010 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004011 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4012 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4013 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4014 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4015 dst->append(" (MANUAL: ");
4016 dumpManualSurroundFormats(dst);
4017 dst->append(")");
4018 }
4019 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004020 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004021 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4022 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004023 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07004024 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01004025
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004026 dst->append("\n");
4027 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4028 dst->append("\n");
4029 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004030 mHwModulesAll.dump(dst);
4031 mOutputs.dump(dst);
4032 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004033 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004034 mAudioPatches.dump(dst);
4035 mPolicyMixes.dump(dst);
4036 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004037
Kevin Rocardb99cc752019-03-21 20:52:24 -07004038 dst->appendFormat(" AllowedCapturePolicies:\n");
4039 for (auto& policy : mAllowedCapturePolicies) {
4040 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4041 }
4042
jiabina84c3d32022-12-02 18:59:55 +00004043 dst->appendFormat(" Preferred mixer audio configuration:\n");
4044 for (const auto it : mPreferredMixerAttrInfos) {
4045 dst->appendFormat(" - device port id: %d\n", it.first);
4046 for (const auto preferredMixerInfoIt : it.second) {
4047 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4048 preferredMixerInfoIt.second->dump(dst);
4049 }
4050 }
4051
François Gaffiec005e562018-11-06 15:04:49 +01004052 dst->appendFormat("\nPolicy Engine dump:\n");
4053 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004054}
4055
4056status_t AudioPolicyManager::dump(int fd)
4057{
4058 String8 result;
4059 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004060 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004061 return NO_ERROR;
4062}
4063
Kevin Rocardb99cc752019-03-21 20:52:24 -07004064status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4065{
4066 mAllowedCapturePolicies[uid] = capturePolicy;
4067 return NO_ERROR;
4068}
4069
Eric Laurente552edb2014-03-10 17:42:56 -07004070// This function checks for the parameters which can be offloaded.
4071// This can be enhanced depending on the capability of the DSP and policy
4072// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004073audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004074{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004075 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004076 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004077 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004078 offloadInfo.format,
4079 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4080 offloadInfo.has_video);
4081
jiabin2b9d5a12021-12-10 01:06:29 +00004082 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004083 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004084 }
4085
4086 // See if there is a profile to support this.
4087 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004088 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004089 offloadInfo.sample_rate,
4090 offloadInfo.format,
4091 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004092 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4093 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004094 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4095 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4096 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004097 if (profile == nullptr) {
4098 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4099 }
4100 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4101 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4102 }
4103 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004104}
4105
Michael Chana94fbb22018-04-24 14:31:19 +10004106bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4107 const audio_attributes_t& attributes) {
4108 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004109 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004110 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4111 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004112 config.sample_rate,
4113 config.format,
4114 config.channel_mask,
4115 output_flags,
4116 true /* directOnly */);
4117 ALOGV("%s() profile %sfound with name: %s, "
4118 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4119 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004120 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004121 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004122
4123 // also try the MSD module if compatible profile not found
4124 if (profile == nullptr) {
4125 profile = getMsdProfileForOutput(outputDevices,
4126 config.sample_rate,
4127 config.format,
4128 config.channel_mask,
4129 output_flags,
4130 true /* directOnly */);
4131 ALOGV("%s() MSD profile %sfound with name: %s, "
4132 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4133 __FUNCTION__, profile != 0 ? "" : "NOT ",
4134 (profile != 0 ? profile->getTagName().c_str() : "null"),
4135 config.sample_rate, config.format, config.channel_mask, output_flags);
4136 }
4137 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004138}
4139
jiabin2b9d5a12021-12-10 01:06:29 +00004140bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4141 bool durationIgnored) {
4142 if (mMasterMono) {
4143 return false; // no offloading if mono is set.
4144 }
4145
4146 // Check if offload has been disabled
4147 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4148 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4149 return false;
4150 }
4151
4152 // Check if stream type is music, then only allow offload as of now.
4153 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4154 {
4155 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4156 return false;
4157 }
4158
4159 //TODO: enable audio offloading with video when ready
4160 const bool allowOffloadWithVideo =
4161 property_get_bool("audio.offload.video", false /* default_value */);
4162 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4163 ALOGV("%s: has_video == true, returning false", __func__);
4164 return false;
4165 }
4166
4167 //If duration is less than minimum value defined in property, return false
4168 const int min_duration_secs = property_get_int32(
4169 "audio.offload.min.duration.secs", -1 /* default_value */);
4170 if (!durationIgnored) {
4171 if (min_duration_secs >= 0) {
4172 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4173 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4174 __func__, min_duration_secs);
4175 return false;
4176 }
4177 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4178 ALOGV("%s: Offload denied by duration < default min(=%u)",
4179 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4180 return false;
4181 }
4182 }
4183
4184 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4185 // creating an offloaded track and tearing it down immediately after start when audioflinger
4186 // detects there is an active non offloadable effect.
4187 // FIXME: We should check the audio session here but we do not have it in this context.
4188 // This may prevent offloading in rare situations where effects are left active by apps
4189 // in the background.
4190 if (mEffects.isNonOffloadableEffectEnabled()) {
4191 return false;
4192 }
4193
4194 return true;
4195}
4196
4197audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4198 const audio_config_t *config) {
4199 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4200 offloadInfo.format = config->format;
4201 offloadInfo.sample_rate = config->sample_rate;
4202 offloadInfo.channel_mask = config->channel_mask;
4203 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4204 offloadInfo.has_video = false;
4205 offloadInfo.is_streaming = false;
4206 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4207
4208 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4209 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4210 audio_flags_to_audio_output_flags(attr->flags, &flags);
4211 // only retain flags that will drive compressed offload or passthrough
4212 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4213 if (offloadPossible) {
4214 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4215 }
4216 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4217
Dorin Drimusfae3c642022-03-17 18:36:30 +01004218 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004219 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004220 DeviceVector outputDevices = engineOutputDevices;
4221 // the MSD module checks for different conditions and output devices
4222 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4223 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4224 continue;
4225 }
4226 outputDevices = getMsdAudioOutDevices();
4227 }
jiabin2b9d5a12021-12-10 01:06:29 +00004228 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004229 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004230 config->sample_rate, nullptr /*updatedSamplingRate*/,
4231 config->format, nullptr /*updatedFormat*/,
4232 config->channel_mask, nullptr /*updatedChannelMask*/,
4233 flags)) {
4234 continue;
4235 }
4236 // reject profiles not corresponding to a device currently available
4237 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4238 continue;
4239 }
4240 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4241 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004242 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004243 != AUDIO_DIRECT_NOT_SUPPORTED) {
4244 // Already reports offload gapless supported. No need to report offload support.
4245 continue;
4246 }
4247 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4248 != AUDIO_OUTPUT_FLAG_NONE) {
4249 // If offload gapless is reported, no need to report offload support.
4250 directMode = (audio_direct_mode_t) ((directMode &
4251 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4252 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4253 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004254 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004255 }
4256 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004257 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004258 }
4259 }
4260 }
4261 return directMode;
4262}
4263
Dorin Drimusf2196d82022-01-03 12:11:18 +01004264status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4265 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004266 if (mEffects.isNonOffloadableEffectEnabled()) {
4267 return OK;
4268 }
jiabinf1c73972022-04-14 16:28:52 -07004269 DeviceVector devices;
4270 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004271 if (status != OK) {
4272 return status;
4273 }
4274 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4275 if (devices.empty()) {
4276 return OK; // no output devices for the attributes
4277 }
jiabinf1c73972022-04-14 16:28:52 -07004278 return getProfilesForDevices(devices, audioProfilesVector,
4279 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004280}
4281
jiabina84c3d32022-12-02 18:59:55 +00004282status_t AudioPolicyManager::getSupportedMixerAttributes(
4283 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4284 ALOGV("%s, portId=%d", __func__, portId);
4285 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4286 if (deviceDescriptor == nullptr) {
4287 ALOGE("%s the requested device is currently unavailable", __func__);
4288 return BAD_VALUE;
4289 }
4290 for (const auto& hwModule : mHwModules) {
4291 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4292 if (curProfile->supportsDevice(deviceDescriptor)) {
4293 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4294 }
4295 }
4296 }
4297 return NO_ERROR;
4298}
4299
4300status_t AudioPolicyManager::setPreferredMixerAttributes(
4301 const audio_attributes_t *attr,
4302 audio_port_handle_t portId,
4303 uid_t uid,
4304 const audio_mixer_attributes_t *mixerAttributes) {
4305 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4306 "mixerBehavior=%d}, uid=%d, portId=%u",
4307 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4308 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4309 mixerAttributes->mixer_behavior, uid, portId);
4310 if (attr->usage != AUDIO_USAGE_MEDIA) {
4311 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4312 return BAD_VALUE;
4313 }
4314 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4315 if (deviceDescriptor == nullptr) {
4316 ALOGE("%s the requested device is currently unavailable", __func__);
4317 return BAD_VALUE;
4318 }
4319 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4320 ALOGE("%s(%d), type=%d, is not a usb output device",
4321 __func__, portId, deviceDescriptor->type());
4322 return BAD_VALUE;
4323 }
4324
4325 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4326 audio_flags_to_audio_output_flags(attr->flags, &flags);
4327 flags = (audio_output_flags_t) (flags |
4328 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4329 sp<IOProfile> profile = nullptr;
4330 DeviceVector devices(deviceDescriptor);
4331 for (const auto& hwModule : mHwModules) {
4332 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4333 if (curProfile->hasDynamicAudioProfile()
4334 && curProfile->isCompatibleProfile(devices,
4335 mixerAttributes->config.sample_rate,
4336 nullptr /*updatedSamplingRate*/,
4337 mixerAttributes->config.format,
4338 nullptr /*updatedFormat*/,
4339 mixerAttributes->config.channel_mask,
4340 nullptr /*updatedChannelMask*/,
4341 flags,
4342 false /*exactMatchRequiredForInputFlags*/)) {
4343 profile = curProfile;
4344 break;
4345 }
4346 }
4347 }
4348 if (profile == nullptr) {
4349 ALOGE("%s, there is no compatible profile found", __func__);
4350 return BAD_VALUE;
4351 }
4352
4353 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4354 sp<PreferredMixerAttributesInfo>::make(
4355 uid, portId, profile, flags, *mixerAttributes);
4356 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4357 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4358
4359 // If 1) there is any client from the preferred mixer configuration owner that is currently
4360 // active and matches the strategy and 2) current output is on the preferred device and the
4361 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4362 // configuration.
4363 std::vector<audio_io_handle_t> outputsToReopen;
4364 for (size_t i = 0; i < mOutputs.size(); i++) {
4365 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004366 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4367 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4368 output->mUsePreferredMixerAttributes = true;
4369 } else {
4370 for (const auto &client: output->getActiveClients()) {
4371 if (client->uid() == uid && client->strategy() == strategy) {
4372 client->setIsInvalid();
4373 outputsToReopen.push_back(output->mIoHandle);
4374 }
jiabina84c3d32022-12-02 18:59:55 +00004375 }
4376 }
4377 }
4378 }
4379 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4380 config.sample_rate = mixerAttributes->config.sample_rate;
4381 config.channel_mask = mixerAttributes->config.channel_mask;
4382 config.format = mixerAttributes->config.format;
4383 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004384 sp<SwAudioOutputDescriptor> desc =
4385 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4386 if (desc == nullptr) {
4387 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4388 continue;
4389 }
4390 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004391 }
4392
4393 return NO_ERROR;
4394}
4395
4396sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4397 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4398 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4399 if (it == mPreferredMixerAttrInfos.end()) {
4400 return nullptr;
4401 }
4402 auto mixerAttrInfoIt = it->second.find(strategy);
4403 if (mixerAttrInfoIt == it->second.end()) {
4404 return nullptr;
4405 }
4406 return mixerAttrInfoIt->second;
4407}
4408
4409status_t AudioPolicyManager::getPreferredMixerAttributes(
4410 const audio_attributes_t *attr,
4411 audio_port_handle_t portId,
4412 audio_mixer_attributes_t* mixerAttributes) {
4413 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4414 portId, mEngine->getProductStrategyForAttributes(*attr));
4415 if (info == nullptr) {
4416 return NAME_NOT_FOUND;
4417 }
4418 *mixerAttributes = info->getMixerAttributes();
4419 return NO_ERROR;
4420}
4421
4422status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4423 audio_port_handle_t portId,
4424 uid_t uid) {
4425 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4426 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4427 if (preferredMixerAttrInfo == nullptr) {
4428 return NAME_NOT_FOUND;
4429 }
4430 if (preferredMixerAttrInfo->getUid() != uid) {
4431 ALOGE("%s, requested uid=%d, owned uid=%d",
4432 __func__, uid, preferredMixerAttrInfo->getUid());
4433 return PERMISSION_DENIED;
4434 }
4435 mPreferredMixerAttrInfos[portId].erase(strategy);
4436 if (mPreferredMixerAttrInfos[portId].empty()) {
4437 mPreferredMixerAttrInfos.erase(portId);
4438 }
4439
4440 // Reconfig existing output
4441 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4442 for (size_t i = 0; i < mOutputs.size(); i++) {
4443 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4444 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4445 }
4446 }
4447 for (const auto output : potentialOutputsToReopen) {
4448 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4449 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4450 preferredMixerAttrInfo->getFlags())) {
4451 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4452 }
4453 }
4454 return NO_ERROR;
4455}
4456
Eric Laurent6a94d692014-05-20 11:18:06 -07004457status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4458 audio_port_type_t type,
4459 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004460 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004461 unsigned int *generation)
4462{
jiabin19cdba52020-11-24 11:28:58 -08004463 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4464 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004465 return BAD_VALUE;
4466 }
4467 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004468 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004469 *num_ports = 0;
4470 }
4471
4472 size_t portsWritten = 0;
4473 size_t portsMax = *num_ports;
4474 *num_ports = 0;
4475 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004476 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4477 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004478 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004479 for (const auto& dev : mAvailableOutputDevices) {
4480 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004481 continue;
4482 }
4483 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004484 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004485 }
4486 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004487 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004488 }
4489 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004490 for (const auto& dev : mAvailableInputDevices) {
4491 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004492 continue;
4493 }
4494 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004495 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004496 }
4497 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004498 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004499 }
4500 }
4501 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4502 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4503 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4504 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4505 }
4506 *num_ports += mInputs.size();
4507 }
4508 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004509 size_t numOutputs = 0;
4510 for (size_t i = 0; i < mOutputs.size(); i++) {
4511 if (!mOutputs[i]->isDuplicated()) {
4512 numOutputs++;
4513 if (portsWritten < portsMax) {
4514 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4515 }
4516 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004517 }
Eric Laurent84c70242014-06-23 08:46:27 -07004518 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004519 }
4520 }
jiabina84c3d32022-12-02 18:59:55 +00004521
Eric Laurent6a94d692014-05-20 11:18:06 -07004522 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004523 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004524 return NO_ERROR;
4525}
4526
jiabin19cdba52020-11-24 11:28:58 -08004527status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004528{
Eric Laurent99fcae42018-05-17 16:59:18 -07004529 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4530 return BAD_VALUE;
4531 }
4532 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4533 if (dev != 0) {
4534 dev->toAudioPort(port);
4535 return NO_ERROR;
4536 }
4537 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4538 if (dev != 0) {
4539 dev->toAudioPort(port);
4540 return NO_ERROR;
4541 }
4542 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4543 if (out != 0) {
4544 out->toAudioPort(port);
4545 return NO_ERROR;
4546 }
4547 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4548 if (in != 0) {
4549 in->toAudioPort(port);
4550 return NO_ERROR;
4551 }
4552 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004553}
4554
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004555status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4556 audio_patch_handle_t *handle,
4557 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004558{
François Gaffieafd4cea2019-11-18 15:50:22 +01004559 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004560 if (handle == NULL || patch == NULL) {
4561 return BAD_VALUE;
4562 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004563 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004564 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004565 return BAD_VALUE;
4566 }
4567 // only one source per audio patch supported for now
4568 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004569 return INVALID_OPERATION;
4570 }
Eric Laurent874c42872014-08-08 15:13:39 -07004571 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004572 return INVALID_OPERATION;
4573 }
Eric Laurent874c42872014-08-08 15:13:39 -07004574 for (size_t i = 0; i < patch->num_sinks; i++) {
4575 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4576 return INVALID_OPERATION;
4577 }
4578 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004579
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004580 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4581 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4582 if (srcDevice == nullptr || sinkDevice == nullptr) {
4583 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4584 return BAD_VALUE;
4585 }
4586 ALOGV("%s between source %s and sink %s", __func__,
4587 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4588 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4589 // Default attributes, default volume priority, not to infer with non raw audio patches.
4590 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4591 const struct audio_port_config *source = &patch->sources[0];
4592 sp<SourceClientDescriptor> sourceDesc =
4593 new InternalSourceClientDescriptor(
4594 portId, uid, attributes, *source, srcDevice, sinkDevice,
4595 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4596
4597 status_t status =
4598 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4599
4600 if (status != NO_ERROR) {
4601 return INVALID_OPERATION;
4602 }
4603 mAudioSources.add(portId, sourceDesc);
4604 return NO_ERROR;
4605}
4606
4607status_t AudioPolicyManager::connectAudioSourceToSink(
4608 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4609 const struct audio_patch *patch,
4610 audio_patch_handle_t &handle,
4611 uid_t uid, uint32_t delayMs)
4612{
4613 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4614 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4615 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4616 return INVALID_OPERATION;
4617 }
4618 sourceDesc->connect(handle, sinkDevice);
4619 if (isMsdPatch(handle)) {
4620 return NO_ERROR;
4621 }
4622 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4623 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4624 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4625 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4626 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4627 goto FailurePatchAdded;
4628 }
4629 status = swOutput->start();
4630 if (status != NO_ERROR) {
4631 goto FailureSourceAdded;
4632 }
4633 swOutput->addClient(sourceDesc);
4634 status = startSource(swOutput, sourceDesc, &delayMs);
4635 if (status != NO_ERROR) {
4636 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4637 goto FailureSourceActive;
4638 }
4639 if (delayMs != 0) {
4640 usleep(delayMs * 1000);
4641 }
4642 return NO_ERROR;
4643
4644FailureSourceActive:
4645 swOutput->stop();
4646 releaseOutput(sourceDesc->portId());
4647FailureSourceAdded:
4648 sourceDesc->setSwOutput(nullptr);
4649FailurePatchAdded:
4650 releaseAudioPatchInternal(handle);
4651 return INVALID_OPERATION;
4652}
4653
4654status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4655 audio_patch_handle_t *handle,
4656 uid_t uid, uint32_t delayMs,
4657 const sp<SourceClientDescriptor>& sourceDesc)
4658{
4659 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004660 sp<AudioPatch> patchDesc;
4661 ssize_t index = mAudioPatches.indexOfKey(*handle);
4662
François Gaffieafd4cea2019-11-18 15:50:22 +01004663 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4664 patch->sources[0].role,
4665 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004666#if LOG_NDEBUG == 0
4667 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004668 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4669 patch->sinks[i].role,
4670 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004671 }
4672#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004673
4674 if (index >= 0) {
4675 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004676 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4677 __func__, mUidCached, patchDesc->getUid(), uid);
4678 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004679 return INVALID_OPERATION;
4680 }
4681 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004682 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004683 }
4684
4685 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004686 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004687 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004688 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004689 return BAD_VALUE;
4690 }
Eric Laurent84c70242014-06-23 08:46:27 -07004691 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4692 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004693 if (patchDesc != 0) {
4694 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004695 ALOGV("%s source id differs for patch current id %d new id %d",
4696 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004697 return BAD_VALUE;
4698 }
4699 }
Eric Laurent874c42872014-08-08 15:13:39 -07004700 DeviceVector devices;
4701 for (size_t i = 0; i < patch->num_sinks; i++) {
4702 // Only support mix to devices connection
4703 // TODO add support for mix to mix connection
4704 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004705 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004706 return INVALID_OPERATION;
4707 }
4708 sp<DeviceDescriptor> devDesc =
4709 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4710 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004711 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004712 return BAD_VALUE;
4713 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004714
François Gaffie11d30102018-11-02 16:09:09 +01004715 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004716 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004717 NULL, // updatedSamplingRate
4718 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004719 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004720 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004721 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004722 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004723 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004724 return INVALID_OPERATION;
4725 }
4726 devices.add(devDesc);
4727 }
4728 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004729 return INVALID_OPERATION;
4730 }
Eric Laurent874c42872014-08-08 15:13:39 -07004731
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004733 ALOGV("%s setting device %s on output %d",
4734 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004735 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004736 index = mAudioPatches.indexOfKey(*handle);
4737 if (index >= 0) {
4738 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004739 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004740 }
4741 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004742 patchDesc->setUid(uid);
4743 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004745 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004746 return INVALID_OPERATION;
4747 }
4748 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4749 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4750 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004751 // only one sink supported when connecting an input device to a mix
4752 if (patch->num_sinks > 1) {
4753 return INVALID_OPERATION;
4754 }
François Gaffie53615e22015-03-19 09:24:12 +01004755 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004756 if (inputDesc == NULL) {
4757 return BAD_VALUE;
4758 }
4759 if (patchDesc != 0) {
4760 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4761 return BAD_VALUE;
4762 }
4763 }
François Gaffie11d30102018-11-02 16:09:09 +01004764 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004765 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004766 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004767 return BAD_VALUE;
4768 }
4769
François Gaffie11d30102018-11-02 16:09:09 +01004770 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004771 patch->sinks[0].sample_rate,
4772 NULL, /*updatedSampleRate*/
4773 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004774 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004775 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004776 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004777 // FIXME for the parameter type,
4778 // and the NONE
4779 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004780 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004781 return INVALID_OPERATION;
4782 }
4783 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004784 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004785 device->toString().c_str(), inputDesc->mIoHandle);
4786 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004787 index = mAudioPatches.indexOfKey(*handle);
4788 if (index >= 0) {
4789 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004790 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004791 }
4792 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004793 patchDesc->setUid(uid);
4794 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004795 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004796 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 return INVALID_OPERATION;
4798 }
4799 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4800 // device to device connection
4801 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004802 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004803 return BAD_VALUE;
4804 }
4805 }
François Gaffie11d30102018-11-02 16:09:09 +01004806 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004807 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004808 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004809 return BAD_VALUE;
4810 }
Eric Laurent874c42872014-08-08 15:13:39 -07004811
Eric Laurent6a94d692014-05-20 11:18:06 -07004812 //update source and sink with our own data as the data passed in the patch may
4813 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004814 PatchBuilder patchBuilder;
4815 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004816
4817 // if first sink is to MSD, establish single MSD patch
4818 if (getMsdAudioOutDevices().contains(
4819 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4820 ALOGV("%s patching to MSD", __FUNCTION__);
4821 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4822 goto installPatch;
4823 }
4824
François Gaffieafd4cea2019-11-18 15:50:22 +01004825 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4826 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004827
Eric Laurent874c42872014-08-08 15:13:39 -07004828 for (size_t i = 0; i < patch->num_sinks; i++) {
4829 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004830 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004831 return INVALID_OPERATION;
4832 }
François Gaffie11d30102018-11-02 16:09:09 +01004833 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004834 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004835 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004836 return BAD_VALUE;
4837 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004838 audio_port_config sinkPortConfig = {};
4839 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4840 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004841
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004842 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4843 // volume management purpose (tracking activity)
4844 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4845 // in config XML to reach the sink so that is can be declared as available.
4846 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004847 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004848 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004849 // take care of dynamic routing for SwOutput selection,
4850 audio_attributes_t attributes = sourceDesc->attributes();
4851 audio_stream_type_t stream = sourceDesc->stream();
4852 audio_attributes_t resultAttr;
4853 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4854 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004855 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4856 config.channel_mask =
4857 (audio_channel_mask_get_representation(sourceMask)
4858 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4859 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004860 config.format = sourceDesc->config().format;
4861 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4862 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4863 bool isRequestedDeviceForExclusiveUse = false;
4864 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004865 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004866 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004867 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4868 &stream, sourceDesc->uid(), &config, &flags,
4869 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004870 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004871 if (output == AUDIO_IO_HANDLE_NONE) {
4872 ALOGV("%s no output for device %s",
4873 __FUNCTION__, sinkDevice->toString().c_str());
4874 return INVALID_OPERATION;
4875 }
4876 outputDesc = mOutputs.valueFor(output);
4877 if (outputDesc->isDuplicated()) {
4878 ALOGE("%s output is duplicated", __func__);
4879 return INVALID_OPERATION;
4880 }
François Gaffie7e39df22022-04-26 12:48:49 +02004881 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4882 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004883 } else {
4884 // Same for "raw patches" aka created from createAudioPatch API
4885 SortedVector<audio_io_handle_t> outputs =
4886 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4887 // if the sink device is reachable via an opened output stream, request to
4888 // go via this output stream by adding a second source to the patch
4889 // description
4890 output = selectOutput(outputs);
4891 if (output == AUDIO_IO_HANDLE_NONE) {
4892 ALOGE("%s no output available for internal patch sink", __func__);
4893 return INVALID_OPERATION;
4894 }
4895 outputDesc = mOutputs.valueFor(output);
4896 if (outputDesc->isDuplicated()) {
4897 ALOGV("%s output for device %s is duplicated",
4898 __func__, sinkDevice->toString().c_str());
4899 return INVALID_OPERATION;
4900 }
François Gaffie7e39df22022-04-26 12:48:49 +02004901 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004902 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004903 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004904 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004905 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004906 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004907 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4908 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004909 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4910 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004911 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004912 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004913 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004914 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004915 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004916 return INVALID_OPERATION;
4917 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004918 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004919 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004920 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004921 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004922 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004923 srcMixPortConfig.ext.mix.usecase.stream =
4924 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004925 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4926 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004927 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004928 }
Eric Laurent83b88082014-06-20 18:31:16 -07004929 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 }
4931 // TODO: check from routing capabilities in config file and other conflicting patches
4932
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004933installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004934 status_t status = installPatch(
4935 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004936 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004937 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004938 return INVALID_OPERATION;
4939 }
4940 } else {
4941 return BAD_VALUE;
4942 }
4943 } else {
4944 return BAD_VALUE;
4945 }
4946 return NO_ERROR;
4947}
4948
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004949status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004950{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004951 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004952 ssize_t index = mAudioPatches.indexOfKey(handle);
4953
4954 if (index < 0) {
4955 return BAD_VALUE;
4956 }
4957 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004958 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4959 __func__, mUidCached, patchDesc->getUid(), uid);
4960 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 return INVALID_OPERATION;
4962 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004963 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4964 for (size_t i = 0; i < mAudioSources.size(); i++) {
4965 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4966 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4967 portId = sourceDesc->portId();
4968 break;
4969 }
4970 }
4971 return portId != AUDIO_PORT_HANDLE_NONE ?
4972 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004973}
Eric Laurent6a94d692014-05-20 11:18:06 -07004974
François Gaffieafd4cea2019-11-18 15:50:22 +01004975status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004976 uint32_t delayMs,
4977 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004978{
4979 ALOGV("%s patch %d", __func__, handle);
4980 if (mAudioPatches.indexOfKey(handle) < 0) {
4981 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4982 return BAD_VALUE;
4983 }
4984 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004985 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004986 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004987 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004988 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004989 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004990 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004991 return BAD_VALUE;
4992 }
4993
François Gaffie11d30102018-11-02 16:09:09 +01004994 setOutputDevices(outputDesc,
4995 getNewOutputDevices(outputDesc, true /*fromCache*/),
4996 true,
4997 0,
4998 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004999 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5000 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005001 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005003 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 return BAD_VALUE;
5005 }
5006 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005007 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005008 true,
5009 NULL);
5010 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005011 status_t status =
5012 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5013 ALOGV("%s patch panel returned %d patchHandle %d",
5014 __func__, status, patchDesc->getAfHandle());
5015 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005017 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005018 // SW or HW Bridge
5019 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5020 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005021 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005022 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5023 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5024 outputDesc = sourceDesc->swOutput().promote();
5025 }
5026 if (outputDesc == nullptr) {
5027 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5028 // releaseOutput has already called closeOutput in case of direct output
5029 return NO_ERROR;
5030 }
François Gaffie7e39df22022-04-26 12:48:49 +02005031 patchHandle = outputDesc->getPatchHandle();
5032 // When a Sw bridge is released, the mixer used by this bridge will release its
5033 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5034 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5035 // updating hal patch handle (prevent leaks).
5036 // While using a HwBridge, force reconsidering device only if not reusing an existing
5037 // output and no more activity on output (will force to close).
5038 bool force = sourceDesc->useSwBridge() ||
5039 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5040 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5041 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5042 // Reconsider device only for cases:
5043 // 1 / Active Output
5044 // 2 / Inactive Output previously hosting HwBridge
5045 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5046 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5047 sourceDesc->canCloseOutput();
5048 setOutputDevices(outputDesc,
5049 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5050 outputDesc->devices(),
5051 force,
5052 0,
5053 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005054 } else {
5055 return BAD_VALUE;
5056 }
5057 } else {
5058 return BAD_VALUE;
5059 }
5060 return NO_ERROR;
5061}
5062
5063status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5064 struct audio_patch *patches,
5065 unsigned int *generation)
5066{
François Gaffie53615e22015-03-19 09:24:12 +01005067 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005068 return BAD_VALUE;
5069 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005070 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005071 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005072}
5073
Eric Laurente1715a42014-05-20 11:30:42 -07005074status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005075{
Eric Laurente1715a42014-05-20 11:30:42 -07005076 ALOGV("setAudioPortConfig()");
5077
5078 if (config == NULL) {
5079 return BAD_VALUE;
5080 }
5081 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5082 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005083 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5084 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005085 }
5086
Eric Laurenta121f902014-06-03 13:32:54 -07005087 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005088 if (config->type == AUDIO_PORT_TYPE_MIX) {
5089 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005090 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005091 if (outputDesc == NULL) {
5092 return BAD_VALUE;
5093 }
Eric Laurent84c70242014-06-23 08:46:27 -07005094 ALOG_ASSERT(!outputDesc->isDuplicated(),
5095 "setAudioPortConfig() called on duplicated output %d",
5096 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005097 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005098 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005099 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005100 if (inputDesc == NULL) {
5101 return BAD_VALUE;
5102 }
Eric Laurenta121f902014-06-03 13:32:54 -07005103 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005104 } else {
5105 return BAD_VALUE;
5106 }
5107 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5108 sp<DeviceDescriptor> deviceDesc;
5109 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5110 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5111 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5112 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5113 } else {
5114 return BAD_VALUE;
5115 }
5116 if (deviceDesc == NULL) {
5117 return BAD_VALUE;
5118 }
Eric Laurenta121f902014-06-03 13:32:54 -07005119 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005120 } else {
5121 return BAD_VALUE;
5122 }
5123
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005124 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005125 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5126 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005127 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005128 audioPortConfig->toAudioPortConfig(&newConfig, config);
5129 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005130 }
Eric Laurenta121f902014-06-03 13:32:54 -07005131 if (status != NO_ERROR) {
5132 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005133 }
Eric Laurente1715a42014-05-20 11:30:42 -07005134
5135 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005136}
5137
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005138void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5139{
Eric Laurentd60560a2015-04-10 11:31:20 -07005140 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005141 clearAudioPatches(uid);
5142 clearSessionRoutes(uid);
5143}
5144
Eric Laurent6a94d692014-05-20 11:18:06 -07005145void AudioPolicyManager::clearAudioPatches(uid_t uid)
5146{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005147 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005148 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005149 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005150 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005151 }
5152 }
5153}
5154
François Gaffiec005e562018-11-06 15:04:49 +01005155void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005156{
François Gaffiec005e562018-11-06 15:04:49 +01005157 // Take the first attributes following the product strategy as it is used to retrieve the routed
5158 // device. All attributes wihin a strategy follows the same "routing strategy"
5159 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5160 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005161 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005162 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005163 for (size_t j = 0; j < mOutputs.size(); j++) {
5164 if (mOutputs.keyAt(j) == ouptutToSkip) {
5165 continue;
5166 }
5167 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005168 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005169 continue;
5170 }
5171 // If the default device for this strategy is on another output mix,
5172 // invalidate all tracks in this strategy to force re connection.
5173 // Otherwise select new device on the output mix.
5174 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01005175 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
5176 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005177 }
5178 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005179 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5180 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5181 // If the device is using preferred mixer attributes, the output need to reopen
5182 // with default configuration when the new selected devices are different from
5183 // current routing devices.
5184 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5185 continue;
5186 }
5187 setOutputDevices(outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005188 }
5189 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005190 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005191}
5192
5193void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5194{
5195 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005196 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005197 for (size_t i = 0; i < mOutputs.size(); i++) {
5198 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005199 for (const auto& client : outputDesc->getClientIterable()) {
5200 if (client->hasPreferredDevice() && client->uid() == uid) {
5201 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005202 auto clientStrategy = client->strategy();
5203 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5204 end(affectedStrategies)) {
5205 continue;
5206 }
5207 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005208 }
5209 }
5210 }
5211 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005212 for (const auto& strategy : affectedStrategies) {
5213 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005214 }
5215
5216 // remove input routes associated with this uid
5217 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005218 for (size_t i = 0; i < mInputs.size(); i++) {
5219 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005220 for (const auto& client : inputDesc->getClientIterable()) {
5221 if (client->hasPreferredDevice() && client->uid() == uid) {
5222 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5223 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005224 }
5225 }
5226 }
5227 // reroute inputs if necessary
5228 SortedVector<audio_io_handle_t> inputsToClose;
5229 for (size_t i = 0; i < mInputs.size(); i++) {
5230 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005231 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005232 inputsToClose.add(inputDesc->mIoHandle);
5233 }
5234 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005235 for (const auto& input : inputsToClose) {
5236 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005237 }
5238}
5239
Eric Laurentd60560a2015-04-10 11:31:20 -07005240void AudioPolicyManager::clearAudioSources(uid_t uid)
5241{
5242 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005243 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5244 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005245 stopAudioSource(mAudioSources.keyAt(i));
5246 }
5247 }
5248}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005249
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005250status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5251 audio_io_handle_t *ioHandle,
5252 audio_devices_t *device)
5253{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005254 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5255 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005256 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005257 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005258
François Gaffiedf372692015-03-19 10:43:27 +01005259 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005260}
5261
Eric Laurentd60560a2015-04-10 11:31:20 -07005262status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005263 const audio_attributes_t *attributes,
5264 audio_port_handle_t *portId,
5265 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005266{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005267 ALOGV("%s", __FUNCTION__);
5268 *portId = AUDIO_PORT_HANDLE_NONE;
5269
5270 if (source == NULL || attributes == NULL || portId == NULL) {
5271 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5272 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005273 return BAD_VALUE;
5274 }
5275
Eric Laurentd60560a2015-04-10 11:31:20 -07005276 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5277 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005278 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5279 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005280 return INVALID_OPERATION;
5281 }
5282
François Gaffie11d30102018-11-02 16:09:09 +01005283 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005284 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005285 String8(source->ext.device.address),
5286 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005287 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005288 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005289 return BAD_VALUE;
5290 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005291
jiabin4ef93452019-09-10 14:29:54 -07005292 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005293
François Gaffieaaac0fd2018-11-22 17:56:39 +01005294 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005295 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005296 mEngine->getStreamTypeForAttributes(*attributes),
5297 mEngine->getProductStrategyForAttributes(*attributes),
5298 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005299
5300 status_t status = connectAudioSource(sourceDesc);
5301 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005302 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005303 }
5304 return status;
5305}
5306
Francois Gaffie601801d2021-06-22 13:27:39 +02005307sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5308 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5309{
5310 ALOGV("%s", __FUNCTION__);
5311 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5312
5313 status_t status = startAudioSource(source, attributes, &portId, uid);
5314 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5315 return mAudioSources.valueFor(portId);
5316}
5317
5318
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005319status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005320{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005321 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005322
5323 // make sure we only have one patch per source.
5324 disconnectAudioSource(sourceDesc);
5325
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005326 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005327 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5328 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5329 sourceDesc->srcDevice()->type(),
5330 String8(sourceDesc->srcDevice()->address().c_str()),
5331 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005332 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005333 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005334 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005335 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005336 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5337 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5338 return INVALID_OPERATION;
5339 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005340 PatchBuilder patchBuilder;
5341 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5342 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005343
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005344 return connectAudioSourceToSink(
5345 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005346}
5347
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005348status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005349{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005350 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5351 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005352 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005353 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005354 return BAD_VALUE;
5355 }
5356 status_t status = disconnectAudioSource(sourceDesc);
5357
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005358 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005359 return status;
5360}
5361
Andy Hung2ddee192015-12-18 17:34:44 -08005362status_t AudioPolicyManager::setMasterMono(bool mono)
5363{
5364 if (mMasterMono == mono) {
5365 return NO_ERROR;
5366 }
5367 mMasterMono = mono;
5368 // if enabling mono we close all offloaded devices, which will invalidate the
5369 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5370 // for recreating the new AudioTrack as non-offloaded PCM.
5371 //
5372 // If disabling mono, we leave all tracks as is: we don't know which clients
5373 // and tracks are able to be recreated as offloaded. The next "song" should
5374 // play back offloaded.
5375 if (mMasterMono) {
5376 Vector<audio_io_handle_t> offloaded;
5377 for (size_t i = 0; i < mOutputs.size(); ++i) {
5378 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5379 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5380 offloaded.push(desc->mIoHandle);
5381 }
5382 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005383 for (const auto& handle : offloaded) {
5384 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005385 }
5386 }
5387 // update master mono for all remaining outputs
5388 for (size_t i = 0; i < mOutputs.size(); ++i) {
5389 updateMono(mOutputs.keyAt(i));
5390 }
5391 return NO_ERROR;
5392}
5393
5394status_t AudioPolicyManager::getMasterMono(bool *mono)
5395{
5396 *mono = mMasterMono;
5397 return NO_ERROR;
5398}
5399
Eric Laurentac9cef52017-06-09 15:46:26 -07005400float AudioPolicyManager::getStreamVolumeDB(
5401 audio_stream_type_t stream, int index, audio_devices_t device)
5402{
jiabin9a3361e2019-10-01 09:38:30 -07005403 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005404}
5405
jiabin81772902018-04-02 17:52:27 -07005406status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5407 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005408 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005409{
Kriti Dang6537def2021-03-02 13:46:59 +01005410 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5411 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005412 return BAD_VALUE;
5413 }
Kriti Dang6537def2021-03-02 13:46:59 +01005414 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5415 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005416
5417 size_t formatsWritten = 0;
5418 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005419
Kriti Dang6537def2021-03-02 13:46:59 +01005420 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005421 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5422 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005423 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005424 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005425 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005426 bool formatEnabled = true;
5427 switch (forceUse) {
5428 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005429 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005430 break;
5431 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5432 formatEnabled = false;
5433 break;
5434 default: // AUTO or ALWAYS => true
5435 break;
jiabin81772902018-04-02 17:52:27 -07005436 }
5437 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5438 }
jiabin81772902018-04-02 17:52:27 -07005439 }
5440 return NO_ERROR;
5441}
5442
Kriti Dang6537def2021-03-02 13:46:59 +01005443status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5444 audio_format_t *surroundFormats) {
5445 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5446 return BAD_VALUE;
5447 }
5448 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5449 __func__, *numSurroundFormats, surroundFormats);
5450
5451 size_t formatsWritten = 0;
5452 size_t formatsMax = *numSurroundFormats;
5453 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5454
5455 // Return formats from all device profiles that have already been resolved by
5456 // checkOutputsForDevice().
5457 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5458 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5459 audio_devices_t deviceType = device->type();
5460 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5461 // returns formats reported by HDMI devices.
5462 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5463 continue;
5464 }
5465 // Formats reported by sink devices
5466 std::unordered_set<audio_format_t> formatset;
5467 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5468 formatset.insert(it->second.begin(), it->second.end());
5469 }
5470
5471 // Formats hard-coded in the in policy configuration file (if any).
5472 FormatVector encodedFormats = device->encodedFormats();
5473 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5474 // Filter the formats which are supported by the vendor hardware.
5475 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5476 if (mConfig.getSurroundFormats().count(*it) != 0) {
5477 formats.insert(*it);
5478 } else {
5479 for (const auto& pair : mConfig.getSurroundFormats()) {
5480 if (pair.second.count(*it) != 0) {
5481 formats.insert(pair.first);
5482 break;
5483 }
5484 }
5485 }
5486 }
5487 }
5488 *numSurroundFormats = formats.size();
5489 for (const auto& format: formats) {
5490 if (formatsWritten < formatsMax) {
5491 surroundFormats[formatsWritten++] = format;
5492 }
5493 }
5494 return NO_ERROR;
5495}
5496
jiabin81772902018-04-02 17:52:27 -07005497status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5498{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005499 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005500 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5501 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005502 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005503 return BAD_VALUE;
5504 }
5505
Mikhail Naganov100f0122018-11-29 11:22:16 -08005506 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5507 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005508 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005509 return INVALID_OPERATION;
5510 }
5511
Mikhail Naganov100f0122018-11-29 11:22:16 -08005512 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005513 return NO_ERROR;
5514 }
5515
Mikhail Naganov100f0122018-11-29 11:22:16 -08005516 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005517 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005518 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005519 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005520 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005521 }
5522 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005523 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005524 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005525 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005526 }
5527 }
5528
5529 sp<SwAudioOutputDescriptor> outputDesc;
5530 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005531 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5532 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005533 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5534 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005535 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005536 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005537 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5538 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5539 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005540 name.c_str(),
5541 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005542 if (status != NO_ERROR) {
5543 continue;
5544 }
5545 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5546 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5547 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005548 name.c_str(),
5549 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005550 profileUpdated |= (status == NO_ERROR);
5551 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005552 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005553 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005554 AUDIO_DEVICE_IN_HDMI);
5555 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5556 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005557 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005558 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005559 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5560 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5561 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005562 name.c_str(),
5563 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005564 if (status != NO_ERROR) {
5565 continue;
5566 }
5567 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5568 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5569 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005570 name.c_str(),
5571 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005572 profileUpdated |= (status == NO_ERROR);
5573 }
5574
jiabin81772902018-04-02 17:52:27 -07005575 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005576 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005577 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005578 }
5579
5580 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5581}
5582
Eric Laurent5ada82e2019-08-29 17:53:54 -07005583void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005584{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005585 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005586 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005587 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005588 }
5589}
5590
jiabin6012f912018-11-02 17:06:30 -07005591bool AudioPolicyManager::isHapticPlaybackSupported()
5592{
5593 for (const auto& hwModule : mHwModules) {
5594 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5595 for (const auto &outProfile : outputProfiles) {
5596 struct audio_port audioPort;
5597 outProfile->toAudioPort(&audioPort);
5598 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5599 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5600 return true;
5601 }
5602 }
5603 }
5604 }
5605 return false;
5606}
5607
Carter Hsu325a8eb2022-01-19 19:56:51 +08005608bool AudioPolicyManager::isUltrasoundSupported()
5609{
5610 bool hasUltrasoundOutput = false;
5611 bool hasUltrasoundInput = false;
5612 for (const auto& hwModule : mHwModules) {
5613 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5614 if (!hasUltrasoundOutput) {
5615 for (const auto &outProfile : outputProfiles) {
5616 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5617 hasUltrasoundOutput = true;
5618 break;
5619 }
5620 }
5621 }
5622
5623 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5624 if (!hasUltrasoundInput) {
5625 for (const auto &inputProfile : inputProfiles) {
5626 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5627 hasUltrasoundInput = true;
5628 break;
5629 }
5630 }
5631 }
5632
5633 if (hasUltrasoundOutput && hasUltrasoundInput)
5634 return true;
5635 }
5636 return false;
5637}
5638
Eric Laurent8340e672019-11-06 11:01:08 -08005639bool AudioPolicyManager::isCallScreenModeSupported()
5640{
5641 return getConfig().isCallScreenModeSupported();
5642}
5643
5644
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005645status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005646{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005647 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005648 if (!sourceDesc->isConnected()) {
5649 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5650 return NO_ERROR;
5651 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005652 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5653 if (swOutput != 0) {
5654 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005655 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005656 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005657 }
jiabinbce0c1d2020-10-05 11:20:18 -07005658 if (releaseOutput(sourceDesc->portId())) {
5659 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5660 // no need to release audio patch here but just return NO_ERROR.
5661 return NO_ERROR;
5662 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005663 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005664 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005665 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005666 // close Hwoutput and remove from mHwOutputs
5667 } else {
5668 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5669 }
5670 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005671 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005672 sourceDesc->disconnect();
5673 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005674}
5675
François Gaffiec005e562018-11-06 15:04:49 +01005676sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5677 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005678{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005679 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005680 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005681 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005682 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005683 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5684 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005685 source = sourceDesc;
5686 break;
5687 }
5688 }
5689 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005690}
5691
Eric Laurentb4f42a92022-01-17 17:37:31 +01005692bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005693 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005694 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005695{
5696 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5697 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005698 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005699 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005700 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5701 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5702 return false;
5703 }
5704 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5705 return false;
5706 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005707 }
5708
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005709 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005710 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005711 if (profile == nullptr) {
5712 return false;
5713 }
5714
5715 // The caller can have the audio config criteria ignored by either passing a null ptr or
5716 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005717 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005718 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005719
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005720 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005721 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005722 return false;
5723 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005724 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005725 return true;
5726}
5727
5728void AudioPolicyManager::checkVirtualizerClientRoutes() {
5729 std::set<audio_stream_type_t> streamsToInvalidate;
5730 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005731 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5732 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005733 audio_attributes_t attr = client->attributes();
5734 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5735 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5736 audio_config_base_t clientConfig = client->config();
5737 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005738 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005739 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005740 streamsToInvalidate.insert(client->stream());
5741 }
5742 }
5743 }
5744
5745 for (audio_stream_type_t stream : streamsToInvalidate) {
5746 mpClientInterface->invalidateStream(stream);
5747 }
5748}
5749
Eric Laurente191d1b2022-04-15 11:59:25 +02005750
5751bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5752 const sp<SwAudioOutputDescriptor>& outputDesc) {
5753 if (outputDesc->isDuplicated()) {
5754 return false;
5755 }
5756 DeviceVector devices = outputDesc->supportedDevices();
5757 for (size_t i = 0; i < mOutputs.size(); i++) {
5758 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5759 if (desc == outputDesc || desc->isDuplicated()) {
5760 continue;
5761 }
5762 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5763 if (!sharedDevices.isEmpty()
5764 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5765 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5766 return false;
5767 }
5768 }
5769 return true;
5770}
5771
5772
Eric Laurentfa0f6742021-08-17 18:39:44 +02005773status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005774 const audio_attributes_t *attr,
5775 audio_io_handle_t *output) {
5776 *output = AUDIO_IO_HANDLE_NONE;
5777
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005778 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5779 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5780 audio_config_t *configPtr = nullptr;
5781 audio_config_t config;
5782 if (mixerConfig != nullptr) {
5783 config = audio_config_initializer(mixerConfig);
5784 configPtr = &config;
5785 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005786 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005787 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005788 return BAD_VALUE;
5789 }
5790
5791 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005792 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005793 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005794 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005795 return BAD_VALUE;
5796 }
5797
Eric Laurente191d1b2022-04-15 11:59:25 +02005798 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005799 for (size_t i = 0; i < mOutputs.size(); i++) {
5800 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005801 if (!desc->isDuplicated()
5802 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5803 spatializerOutputs.push_back(desc);
5804 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005805 }
5806 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005807 mSpatializerOutput.clear();
5808 bool outputsChanged = false;
5809 for (const auto& desc : spatializerOutputs) {
5810 if (desc->mProfile == profile
5811 && (configPtr == nullptr
5812 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5813 mSpatializerOutput = desc;
5814 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5815 } else {
5816 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5817 " and devices %s", __func__, desc->mIoHandle,
5818 configPtr != nullptr ? configPtr->channel_mask : 0,
5819 devices.toString().c_str());
5820 closeOutput(desc->mIoHandle);
5821 outputsChanged = true;
5822 }
Eric Laurent39095982021-08-24 18:29:27 +02005823 }
5824
Eric Laurente191d1b2022-04-15 11:59:25 +02005825 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005826 sp<SwAudioOutputDescriptor> desc =
5827 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005828 if (desc != nullptr) {
5829 mSpatializerOutput = desc;
5830 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005831 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005832 }
5833
5834 checkVirtualizerClientRoutes();
5835
Eric Laurente191d1b2022-04-15 11:59:25 +02005836 if (outputsChanged) {
5837 mPreviousOutputs = mOutputs;
5838 mpClientInterface->onAudioPortListUpdate();
5839 }
5840
5841 if (mSpatializerOutput == nullptr) {
5842 ALOGV("%s could not open spatializer output with requested config", __func__);
5843 return BAD_VALUE;
5844 }
Eric Laurent39095982021-08-24 18:29:27 +02005845 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005846 ALOGV("%s returning new spatializer output %d", __func__, *output);
5847 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005848}
5849
Eric Laurentfa0f6742021-08-17 18:39:44 +02005850status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5851 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005852 return INVALID_OPERATION;
5853 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005854 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005855 return BAD_VALUE;
5856 }
Eric Laurent39095982021-08-24 18:29:27 +02005857
Eric Laurente191d1b2022-04-15 11:59:25 +02005858 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5859 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5860 closeOutput(mSpatializerOutput->mIoHandle);
5861 //from now on mSpatializerOutput is null
5862 checkVirtualizerClientRoutes();
5863 }
Eric Laurent39095982021-08-24 18:29:27 +02005864
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005865 return NO_ERROR;
5866}
5867
Eric Laurente552edb2014-03-10 17:42:56 -07005868// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005869// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005870// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005871uint32_t AudioPolicyManager::nextAudioPortGeneration()
5872{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005873 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005874}
5875
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005876static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005877 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5878 !audioPolicyXmlConfigFile.empty()) {
5879 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5880 if (ret == NO_ERROR) {
5881 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005882 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005883 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005884 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005885 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005886}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005887
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005888AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5889 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005890 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005891 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005892 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005893 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005894 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005895 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005896 mAudioPortGeneration(1),
5897 mBeaconMuteRefCount(0),
5898 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005899 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005900 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005901 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005902 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005903{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005904}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005905
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005906AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5907 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5908{
5909 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005910}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005911
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005912void AudioPolicyManager::loadConfig() {
5913 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005914 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005915 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005916 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005917}
5918
5919status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005920 {
5921 auto engLib = EngineLibrary::load(
5922 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5923 if (!engLib) {
5924 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5925 return NO_INIT;
5926 }
5927 mEngine = engLib->createEngine();
5928 if (mEngine == nullptr) {
5929 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5930 return NO_INIT;
5931 }
François Gaffie2110e042015-03-24 08:41:51 +01005932 }
5933 mEngine->setObserver(this);
5934 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005935 if (status != NO_ERROR) {
5936 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5937 return status;
5938 }
François Gaffie2110e042015-03-24 08:41:51 +01005939
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005940 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005941 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5942 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5943
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005944 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005945 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005946 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005947
Eric Laurent3a4311c2014-03-17 12:00:47 -07005948 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005949 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5950 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5951 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005952 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005953 }
jiabin9ff780e2018-03-19 18:19:52 -07005954 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005955 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005956 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005957 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005958 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005959 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005960 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005961 }
5962 }
5963 }
Eric Laurente552edb2014-03-10 17:42:56 -07005964
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005965 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005966
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005967 // Silence ALOGV statements
5968 property_set("log.tag." LOG_TAG, "D");
5969
Eric Laurente552edb2014-03-10 17:42:56 -07005970 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005971 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005972}
5973
Eric Laurente0720872014-03-11 09:30:41 -07005974AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005975{
Eric Laurente552edb2014-03-10 17:42:56 -07005976 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005977 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005978 }
5979 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005980 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005981 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005982 mAvailableOutputDevices.clear();
5983 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005984 mOutputs.clear();
5985 mInputs.clear();
5986 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005987 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005988 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005989}
5990
Eric Laurente0720872014-03-11 09:30:41 -07005991status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005992{
Eric Laurent87ffa392015-05-22 10:32:38 -07005993 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005994}
5995
Eric Laurente552edb2014-03-10 17:42:56 -07005996// ---
5997
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005998void AudioPolicyManager::onNewAudioModulesAvailable()
5999{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006000 DeviceVector newDevices;
6001 onNewAudioModulesAvailableInt(&newDevices);
6002 if (!newDevices.empty()) {
6003 nextAudioPortGeneration();
6004 mpClientInterface->onAudioPortListUpdate();
6005 }
6006}
6007
6008void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6009{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006010 for (const auto& hwModule : mHwModulesAll) {
6011 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6012 continue;
6013 }
6014 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
6015 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
6016 ALOGW("could not open HW module %s", hwModule->getName());
6017 continue;
6018 }
6019 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006020 // open all output streams needed to access attached devices.
6021 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006022 // This also validates mAvailableOutputDevices list
6023 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6024 if (!outProfile->canOpenNewIo()) {
6025 ALOGE("Invalid Output profile max open count %u for profile %s",
6026 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6027 continue;
6028 }
6029 if (!outProfile->hasSupportedDevices()) {
6030 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6031 continue;
6032 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006033 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6034 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006035 mTtsOutputAvailable = true;
6036 }
6037
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006038 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
6039 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
6040 sp<DeviceDescriptor> supportedDevice = 0;
6041 if (supportedDevices.contains(mDefaultOutputDevice)) {
6042 supportedDevice = mDefaultOutputDevice;
6043 } else {
6044 // choose first device present in profile's SupportedDevices also part of
6045 // mAvailableOutputDevices.
6046 if (availProfileDevices.isEmpty()) {
6047 continue;
6048 }
6049 supportedDevice = availProfileDevices.itemAt(0);
6050 }
6051 if (!mOutputDevicesAll.contains(supportedDevice)) {
6052 continue;
6053 }
6054 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6055 mpClientInterface);
6056 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006057 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6058 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006059 AUDIO_STREAM_DEFAULT,
6060 AUDIO_OUTPUT_FLAG_NONE, &output);
6061 if (status != NO_ERROR) {
6062 ALOGW("Cannot open output stream for devices %s on hw module %s",
6063 supportedDevice->toString().c_str(), hwModule->getName());
6064 continue;
6065 }
6066 for (const auto &device : availProfileDevices) {
6067 // give a valid ID to an attached device once confirmed it is reachable
6068 if (!device->isAttached()) {
6069 device->attach(hwModule);
6070 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006071 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006072 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006073 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6074 }
6075 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006076 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006077 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6078 mPrimaryOutput = outputDesc;
6079 }
Eric Laurent39095982021-08-24 18:29:27 +02006080 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006081 outputDesc->close();
6082 } else {
6083 addOutput(output, outputDesc);
6084 setOutputDevices(outputDesc,
6085 DeviceVector(supportedDevice),
6086 true,
6087 0,
6088 NULL);
6089 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006090 }
6091 // open input streams needed to access attached devices to validate
6092 // mAvailableInputDevices list
6093 for (const auto& inProfile : hwModule->getInputProfiles()) {
6094 if (!inProfile->canOpenNewIo()) {
6095 ALOGE("Invalid Input profile max open count %u for profile %s",
6096 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6097 continue;
6098 }
6099 if (!inProfile->hasSupportedDevices()) {
6100 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6101 continue;
6102 }
6103 // chose first device present in profile's SupportedDevices also part of
6104 // available input devices
6105 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6106 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6107 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006108 ALOGV("%s: Input device list is empty! for profile %s",
6109 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006110 continue;
6111 }
6112 sp<AudioInputDescriptor> inputDesc =
6113 new AudioInputDescriptor(inProfile, mpClientInterface);
6114
6115 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6116 status_t status = inputDesc->open(nullptr,
6117 availProfileDevices.itemAt(0),
6118 AUDIO_SOURCE_MIC,
6119 AUDIO_INPUT_FLAG_NONE,
6120 &input);
6121 if (status != NO_ERROR) {
6122 ALOGW("Cannot open input stream for device %s on hw module %s",
6123 availProfileDevices.toString().c_str(),
6124 hwModule->getName());
6125 continue;
6126 }
6127 for (const auto &device : availProfileDevices) {
6128 // give a valid ID to an attached device once confirmed it is reachable
6129 if (!device->isAttached()) {
6130 device->attach(hwModule);
6131 device->importAudioPortAndPickAudioProfile(inProfile, true);
6132 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006133 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006134 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6135 }
6136 }
6137 inputDesc->close();
6138 }
6139 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006140
6141 // Check if spatializer outputs can be closed until used.
6142 // mOutputs vector never contains duplicated outputs at this point.
6143 std::vector<audio_io_handle_t> outputsClosed;
6144 for (size_t i = 0; i < mOutputs.size(); i++) {
6145 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6146 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6147 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6148 outputsClosed.push_back(desc->mIoHandle);
6149 desc->close();
6150 }
6151 }
6152 for (auto output : outputsClosed) {
6153 removeOutput(output);
6154 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006155}
6156
Eric Laurent98e38192018-02-15 18:31:53 -08006157void AudioPolicyManager::addOutput(audio_io_handle_t output,
6158 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006159{
Eric Laurent1c333e22014-05-20 10:48:17 -07006160 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006161 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006162 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006163 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006164 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006165}
6166
François Gaffie53615e22015-03-19 09:24:12 +01006167void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6168{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006169 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6170 ALOGV("%s: removing primary output", __func__);
6171 mPrimaryOutput = nullptr;
6172 }
François Gaffie53615e22015-03-19 09:24:12 +01006173 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006174 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006175}
6176
Eric Laurent98e38192018-02-15 18:31:53 -08006177void AudioPolicyManager::addInput(audio_io_handle_t input,
6178 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006179{
Eric Laurent1c333e22014-05-20 10:48:17 -07006180 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006181 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006182}
Eric Laurente552edb2014-03-10 17:42:56 -07006183
François Gaffie11d30102018-11-02 16:09:09 +01006184status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006185 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006186 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006187{
François Gaffie11d30102018-11-02 16:09:09 +01006188 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006189 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006190 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006191
François Gaffie11d30102018-11-02 16:09:09 +01006192 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006193 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006194 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006195 }
Eric Laurente552edb2014-03-10 17:42:56 -07006196
Eric Laurent3b73df72014-03-11 09:06:29 -07006197 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006198 // first call getAudioPort to get the supported attributes from the HAL
6199 struct audio_port_v7 port = {};
6200 device->toAudioPort(&port);
6201 status_t status = mpClientInterface->getAudioPort(&port);
6202 if (status == NO_ERROR) {
6203 device->importAudioPort(port);
6204 }
6205
6206 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006207 for (size_t i = 0; i < mOutputs.size(); i++) {
6208 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006209 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006210 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006211 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6212 mOutputs.keyAt(i), device->toString().c_str());
6213 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006214 }
6215 }
6216 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006217 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006218 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006219 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6220 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006221 if (profile->supportsDevice(device)) {
6222 profiles.add(profile);
6223 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6224 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006225 }
6226 }
6227 }
6228
Eric Laurent7b279bb2015-12-14 10:18:23 -08006229 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006230
Eric Laurente552edb2014-03-10 17:42:56 -07006231 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006232 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006233 return BAD_VALUE;
6234 }
6235
6236 // open outputs for matching profiles if needed. Direct outputs are also opened to
6237 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6238 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006239 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006240
6241 // nothing to do if one output is already opened for this profile
6242 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006243 for (j = 0; j < outputs.size(); j++) {
6244 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006245 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006246 // matching profile: save the sample rates, format and channel masks supported
6247 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006248 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006249 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006250 }
Eric Laurente552edb2014-03-10 17:42:56 -07006251 break;
6252 }
6253 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006254 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006255 continue;
6256 }
6257
Eric Laurent3974e3b2017-12-07 17:58:43 -08006258 if (!profile->canOpenNewIo()) {
6259 ALOGW("Max Output number %u already opened for this profile %s",
6260 profile->maxOpenCount, profile->getTagName().c_str());
6261 continue;
6262 }
6263
Eric Laurent83efe1c2017-07-09 16:51:08 -07006264 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006265 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006266 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6267 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006268 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006269 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006270 profiles.removeAt(profile_index);
6271 profile_index--;
6272 } else {
6273 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006274 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006275 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006276 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6277 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006278 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006279 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006280
François Gaffie11d30102018-11-02 16:09:09 +01006281 if (device_distinguishes_on_address(deviceType)) {
6282 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6283 device->toString().c_str());
6284 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6285 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006286 }
Eric Laurente552edb2014-03-10 17:42:56 -07006287 ALOGV("checkOutputsForDevice(): adding output %d", output);
6288 }
6289 }
6290
6291 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006292 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006293 return BAD_VALUE;
6294 }
Eric Laurentd4692962014-05-05 18:13:44 -07006295 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006296 // check if one opened output is not needed any more after disconnecting one device
6297 for (size_t i = 0; i < mOutputs.size(); i++) {
6298 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006299 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006300 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006301 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006302 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006303 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006304 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006305 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6306 mOutputs.keyAt(i));
6307 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006308 }
Eric Laurente552edb2014-03-10 17:42:56 -07006309 }
6310 }
Eric Laurentd4692962014-05-05 18:13:44 -07006311 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006312 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006313 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6314 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006315 if (!profile->supportsDevice(device)) {
6316 continue;
6317 }
6318 ALOGV("checkOutputsForDevice(): "
6319 "clearing direct output profile %zu on module %s",
6320 j, hwModule->getName());
6321 profile->clearAudioProfiles();
6322 if (!profile->hasDynamicAudioProfile()) {
6323 continue;
6324 }
6325 // When a device is disconnected, if there is an IOProfile that contains dynamic
6326 // profiles and supports the disconnected device, call getAudioPort to repopulate
6327 // the capabilities of the devices that is supported by the IOProfile.
6328 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6329 if (supportedDevice == device ||
6330 !mAvailableOutputDevices.contains(supportedDevice)) {
6331 continue;
6332 }
6333 struct audio_port_v7 port;
6334 supportedDevice->toAudioPort(&port);
6335 status_t status = mpClientInterface->getAudioPort(&port);
6336 if (status == NO_ERROR) {
6337 supportedDevice->importAudioPort(port);
6338 }
Eric Laurente552edb2014-03-10 17:42:56 -07006339 }
6340 }
6341 }
6342 }
6343 return NO_ERROR;
6344}
6345
François Gaffie11d30102018-11-02 16:09:09 +01006346status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006347 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006348{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006349 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006350
François Gaffie11d30102018-11-02 16:09:09 +01006351 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006352 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006353 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006354 }
6355
Eric Laurentd4692962014-05-05 18:13:44 -07006356 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006357 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006358 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006359 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006360 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006361 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006362 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006363 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006364
François Gaffie11d30102018-11-02 16:09:09 +01006365 if (profile->supportsDevice(device)) {
6366 profiles.add(profile);
6367 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6368 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006369 }
6370 }
6371 }
6372
Eric Laurent0dd51852019-04-19 18:18:58 -07006373 if (profiles.isEmpty()) {
6374 ALOGW("%s: No input profile available for device %s",
6375 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006376 return BAD_VALUE;
6377 }
6378
6379 // open inputs for matching profiles if needed. Direct inputs are also opened to
6380 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6381 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6382
Eric Laurent1c333e22014-05-20 10:48:17 -07006383 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006384
Eric Laurentd4692962014-05-05 18:13:44 -07006385 // nothing to do if one input is already opened for this profile
6386 size_t input_index;
6387 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6388 desc = mInputs.valueAt(input_index);
6389 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006390 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006391 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006392 }
Eric Laurentd4692962014-05-05 18:13:44 -07006393 break;
6394 }
6395 }
6396 if (input_index != mInputs.size()) {
6397 continue;
6398 }
6399
Eric Laurent3974e3b2017-12-07 17:58:43 -08006400 if (!profile->canOpenNewIo()) {
6401 ALOGW("Max Input number %u already opened for this profile %s",
6402 profile->maxOpenCount, profile->getTagName().c_str());
6403 continue;
6404 }
6405
Eric Laurentfe231122017-11-17 17:48:06 -08006406 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006407 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006408 status_t status = desc->open(nullptr,
6409 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006410 AUDIO_SOURCE_MIC,
6411 AUDIO_INPUT_FLAG_NONE,
6412 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006413
Eric Laurentcf2c0212014-07-25 16:20:43 -07006414 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006415 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006416 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006417 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006418 mpClientInterface->setParameters(input, String8(param));
6419 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006420 }
François Gaffie11d30102018-11-02 16:09:09 +01006421 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006422 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006423 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006424 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006425 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006426 }
6427
Eric Laurent0dd51852019-04-19 18:18:58 -07006428 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006429 addInput(input, desc);
6430 }
6431 } // endif input != 0
6432
Eric Laurentcf2c0212014-07-25 16:20:43 -07006433 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006434 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006435 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006436 profiles.removeAt(profile_index);
6437 profile_index--;
6438 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006439 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006440 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006441 }
Eric Laurentd4692962014-05-05 18:13:44 -07006442 ALOGV("checkInputsForDevice(): adding input %d", input);
6443 }
6444 } // end scan profiles
6445
6446 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006447 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006448 return BAD_VALUE;
6449 }
6450 } else {
6451 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006452 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006453 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006454 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006455 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006456 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006457 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006458 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006459 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6460 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006461 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006462 }
6463 }
6464 }
6465 } // end disconnect
6466
6467 return NO_ERROR;
6468}
6469
6470
Eric Laurente0720872014-03-11 09:30:41 -07006471void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006472{
6473 ALOGV("closeOutput(%d)", output);
6474
François Gaffie1c878552018-11-22 16:53:21 +01006475 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6476 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006477 ALOGW("closeOutput() unknown output %d", output);
6478 return;
6479 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006480 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006481 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006482
Eric Laurente552edb2014-03-10 17:42:56 -07006483 // look for duplicated outputs connected to the output being removed.
6484 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006485 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6486 if (dupOutput->isDuplicated() &&
6487 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6488 sp<SwAudioOutputDescriptor> remainingOutput =
6489 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006490 // As all active tracks on duplicated output will be deleted,
6491 // and as they were also referenced on the other output, the reference
6492 // count for their stream type must be adjusted accordingly on
6493 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006494 const bool wasActive = remainingOutput->isActive();
6495 // Note: no-op on the closing output where all clients has already been set inactive
6496 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006497 // stop() will be a no op if the output is still active but is needed in case all
6498 // active streams refcounts where cleared above
6499 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006500 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006501 }
Eric Laurente552edb2014-03-10 17:42:56 -07006502 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6503 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6504
6505 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006506 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006507 }
6508 }
6509
Eric Laurent05b90f82014-08-27 15:32:29 -07006510 nextAudioPortGeneration();
6511
François Gaffie1c878552018-11-22 16:53:21 +01006512 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006513 if (index >= 0) {
6514 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006515 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6516 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006517 mAudioPatches.removeItemsAt(index);
6518 mpClientInterface->onAudioPatchListUpdate();
6519 }
6520
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006521 if (closingOutputWasActive) {
6522 closingOutput->stop();
6523 }
François Gaffie1c878552018-11-22 16:53:21 +01006524 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006525
François Gaffie53615e22015-03-19 09:24:12 +01006526 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006527 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006528 if (closingOutput == mSpatializerOutput) {
6529 mSpatializerOutput.clear();
6530 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006531
6532 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6533 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006534 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006535 bool directOutputOpen = false;
6536 for (size_t i = 0; i < mOutputs.size(); i++) {
6537 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6538 directOutputOpen = true;
6539 break;
6540 }
6541 }
6542 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006543 ALOGV("no direct outputs open, reset MSD patches");
6544 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6545 // how output devices for patching are resolved. Avoid by caching and reusing the
6546 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6547 // devices to patch to. This may be complicated by the fact that devices may become
6548 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006549 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006550 }
6551 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006552}
6553
6554void AudioPolicyManager::closeInput(audio_io_handle_t input)
6555{
6556 ALOGV("closeInput(%d)", input);
6557
6558 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6559 if (inputDesc == NULL) {
6560 ALOGW("closeInput() unknown input %d", input);
6561 return;
6562 }
6563
Eric Laurent6a94d692014-05-20 11:18:06 -07006564 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006565
François Gaffie11d30102018-11-02 16:09:09 +01006566 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006567 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006568 if (index >= 0) {
6569 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006570 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6571 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006572 mAudioPatches.removeItemsAt(index);
6573 mpClientInterface->onAudioPatchListUpdate();
6574 }
6575
Eric Laurentfe231122017-11-17 17:48:06 -08006576 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006577 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006578
François Gaffie11d30102018-11-02 16:09:09 +01006579 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6580 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006581 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006582 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006583 }
Eric Laurente552edb2014-03-10 17:42:56 -07006584}
6585
François Gaffie11d30102018-11-02 16:09:09 +01006586SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6587 const DeviceVector &devices,
6588 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006589{
6590 SortedVector<audio_io_handle_t> outputs;
6591
François Gaffie11d30102018-11-02 16:09:09 +01006592 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006593 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006594 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006595 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006596 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006597 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006598 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006599 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006600 outputs.add(openOutputs.keyAt(i));
6601 }
6602 }
6603 return outputs;
6604}
6605
Mikhail Naganov37977152018-07-11 15:54:44 -07006606void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6607{
6608 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6609 // output is suspended before any tracks are moved to it
6610 checkA2dpSuspend();
6611 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006612 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006613 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006614 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006615 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006616 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6617 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6618 // configuration changes will ultimately be rerouted correctly. We can still avoid
6619 // unnecessary rerouting by caching and reusing the arguments to
6620 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6621 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006622 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006623 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006624 // an event that changed routing likely occurred, inform upper layers
6625 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006626}
6627
François Gaffiec005e562018-11-06 15:04:49 +01006628bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6629 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006630{
François Gaffiec005e562018-11-06 15:04:49 +01006631 return mEngine->getProductStrategyForAttributes(lAttr) ==
6632 mEngine->getProductStrategyForAttributes(rAttr);
6633}
6634
Francois Gaffieff1eb522020-05-06 18:37:04 +02006635void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6636{
6637 for (size_t i = 0; i < mAudioSources.size(); i++) {
6638 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6639 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006640 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006641 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006642 connectAudioSource(sourceDesc);
6643 }
6644 }
6645}
6646
6647void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6648{
6649 for (size_t i = 0; i < mAudioSources.size(); i++) {
6650 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6651 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6652 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6653 disconnectAudioSource(sourceDesc);
6654 }
6655 }
6656}
6657
François Gaffiec005e562018-11-06 15:04:49 +01006658void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6659{
6660 auto psId = mEngine->getProductStrategyForAttributes(attr);
6661
6662 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6663 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006664
François Gaffie11d30102018-11-02 16:09:09 +01006665 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6666 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006667
Eric Laurentc209fe42020-06-05 18:11:23 -07006668 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006669 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006670 // take into account dynamic audio policies related changes: if a client is now associated
6671 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006672 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006673 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6674 if (desc->isDuplicated()) {
6675 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006676 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006677 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6678 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6679 continue;
6680 }
6681 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006682 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006683 client->uid(), client->session(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006684 if (status != OK) {
6685 continue;
6686 }
yucliuf4de36d2020-09-14 14:57:56 -07006687 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006688 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006689 maxLatency = desc->latency();
6690 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006691 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006692 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006693 }
6694 }
6695
Eric Laurent56ed8842022-11-15 16:04:41 +01006696 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006697 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6698 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006699 for (audio_io_handle_t srcOut : srcOutputs) {
6700 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006701 if (desc == nullptr) continue;
6702
6703 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006704 maxLatency = desc->latency();
6705 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006706
Eric Laurent56ed8842022-11-15 16:04:41 +01006707 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006708 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006709 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006710 // a client on a non direct outputs has necessarily a linear PCM format
6711 // so we can call selectOutput() safely
6712 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6713 client->flags(),
6714 client->config().format,
6715 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006716 client->config().sample_rate,
6717 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006718 if (newOutput != srcOut) {
6719 invalidate = true;
6720 break;
6721 }
6722 } else {
6723 sp<IOProfile> profile = getProfileForOutput(newDevices,
6724 client->config().sample_rate,
6725 client->config().format,
6726 client->config().channel_mask,
6727 client->flags(),
6728 true /* directOnly */);
6729 if (profile != desc->mProfile) {
6730 invalidate = true;
6731 break;
6732 }
6733 }
6734 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006735 // mute strategy while moving tracks from one output to another
6736 if (invalidate) {
6737 invalidatedOutputs.push_back(desc);
6738 if (desc->isStrategyActive(psId)) {
6739 setStrategyMute(psId, true, desc);
6740 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6741 newDevices.types());
6742 }
Eric Laurente552edb2014-03-10 17:42:56 -07006743 }
François Gaffiec005e562018-11-06 15:04:49 +01006744 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006745 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006746 connectAudioSource(source);
6747 }
Eric Laurente552edb2014-03-10 17:42:56 -07006748 }
6749
Eric Laurent56ed8842022-11-15 16:04:41 +01006750 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6751 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6752 std::to_string(srcOutputs[0]).c_str(),
6753 std::to_string(dstOutputs[0]).c_str());
6754
François Gaffiec005e562018-11-06 15:04:49 +01006755 // Move effects associated to this stream from previous output to new output
6756 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006757 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006758 }
François Gaffiec005e562018-11-06 15:04:49 +01006759 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006760 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006761 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6762 mpClientInterface->invalidateStream(stream);
6763 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006764 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006765 desc->setTracksInvalidatedStatusByStrategy(psId);
6766 }
Eric Laurente552edb2014-03-10 17:42:56 -07006767 }
6768 }
6769}
6770
Eric Laurente0720872014-03-11 09:30:41 -07006771void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006772{
François Gaffiec005e562018-11-06 15:04:49 +01006773 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6774 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6775 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006776 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006777 }
Eric Laurente552edb2014-03-10 17:42:56 -07006778}
6779
Kevin Rocard153f92d2018-12-18 18:33:28 -08006780void AudioPolicyManager::checkSecondaryOutputs() {
6781 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006782 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006783 for (size_t i = 0; i < mOutputs.size(); i++) {
6784 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6785 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006786 sp<AudioPolicyMix> primaryMix;
6787 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006788 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006789 client->uid(), client->session(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006790 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6791 for (auto &secondaryMix : secondaryMixes) {
6792 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6793 if (outputDesc != nullptr &&
6794 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6795 secondaryDescs.push_back(outputDesc);
6796 }
6797 }
6798
jiabin10a03f12021-05-07 23:46:28 +00006799 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006800 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006801 } else if (!std::equal(
6802 client->getSecondaryOutputs().begin(),
6803 client->getSecondaryOutputs().end(),
6804 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006805 if (!audio_is_linear_pcm(client->config().format)) {
6806 // If the format is not PCM, the tracks should be invalidated to get correct
6807 // behavior when the secondary output is changed.
6808 streamsToInvalidate.insert(client->stream());
6809 } else {
6810 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6811 std::vector<audio_io_handle_t> secondaryOutputIds;
6812 for (const auto &secondaryDesc: secondaryDescs) {
6813 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6814 weakSecondaryDescs.push_back(secondaryDesc);
6815 }
6816 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6817 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006818 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006819 }
6820 }
6821 }
jiabin10a03f12021-05-07 23:46:28 +00006822 if (!trackSecondaryOutputs.empty()) {
6823 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6824 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006825 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006826 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006827 mpClientInterface->invalidateStream(stream);
6828 }
6829}
6830
Eric Laurent2517af32020-11-25 15:31:27 +01006831bool AudioPolicyManager::isScoRequestedForComm() const {
6832 AudioDeviceTypeAddrVector devices;
6833 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6834 for (const auto &device : devices) {
6835 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6836 return true;
6837 }
6838 }
6839 return false;
6840}
6841
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006842bool AudioPolicyManager::isHearingAidUsedForComm() const {
6843 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6844 true /*fromCache*/);
6845 for (const auto &device : devices) {
6846 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6847 return true;
6848 }
6849 }
6850 return false;
6851}
6852
6853
Eric Laurente0720872014-03-11 09:30:41 -07006854void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006855{
François Gaffie53615e22015-03-19 09:24:12 +01006856 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006857 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006858 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006859 return;
6860 }
6861
Eric Laurent3a4311c2014-03-17 12:00:47 -07006862 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006863 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6864 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006865 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006866
6867 // if suspended, restore A2DP output if:
6868 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006869 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006870 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006871 //
Eric Laurentf732e072016-08-03 19:30:28 -07006872 // if not suspended, suspend A2DP output if:
6873 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006874 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006875 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006876 //
6877 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006878 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006879 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006880 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006881 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006882
6883 mpClientInterface->restoreOutput(a2dpOutput);
6884 mA2dpSuspended = false;
6885 }
6886 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006887 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006888 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006889 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006890 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006891
6892 mpClientInterface->suspendOutput(a2dpOutput);
6893 mA2dpSuspended = true;
6894 }
6895 }
6896}
6897
François Gaffie11d30102018-11-02 16:09:09 +01006898DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6899 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006900{
François Gaffie11d30102018-11-02 16:09:09 +01006901 DeviceVector devices;
6902
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006903 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006904 if (index >= 0) {
6905 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006906 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006907 ALOGV("%s device %s forced by patch %d", __func__,
6908 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6909 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006910 }
6911 }
6912
Dean Wheatley514b4312020-06-17 21:45:00 +10006913 // Do not retrieve engine device for outputs through MSD
6914 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6915 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6916 return outputDesc->devices();
6917 }
6918
Eric Laurent97ac8712018-07-27 18:59:02 -07006919 // Honor explicit routing requests only if no client using default routing is active on this
6920 // input: a specific app can not force routing for other apps by setting a preferred device.
6921 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006922 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006923 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006924 if (device != nullptr) {
6925 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006926 }
6927
François Gaffiea807ef92018-11-05 10:44:33 +01006928 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6929 // of setForceUse / Default Bus device here
6930 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6931 if (device != nullptr) {
6932 return DeviceVector(device);
6933 }
6934
François Gaffiec005e562018-11-06 15:04:49 +01006935 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6936 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6937 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306938 auto hasStreamActive = [&](auto stream) {
6939 return hasStream(streams, stream) && isStreamActive(stream, 0);
6940 };
Eric Laurent484e9272018-06-07 17:29:23 -07006941
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306942 auto doGetOutputDevicesForVoice = [&]() {
6943 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006944 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306945 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006946 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6947 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306948 };
6949
6950 // With low-latency playing on speaker, music on WFD, when the first low-latency
6951 // output is stopped, getNewOutputDevices checks for a product strategy
6952 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006953 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306954 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6955 // stream is associated to the output descriptor.
6956 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6957 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6958 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6959 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006960 // Retrieval of devices for voice DL is done on primary output profile, cannot
6961 // check the route (would force modifying configuration file for this profile)
6962 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6963 break;
6964 }
Eric Laurente552edb2014-03-10 17:42:56 -07006965 }
François Gaffiec005e562018-11-06 15:04:49 +01006966 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006967 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006968}
6969
François Gaffie11d30102018-11-02 16:09:09 +01006970sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6971 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006972{
François Gaffie11d30102018-11-02 16:09:09 +01006973 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006974
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006975 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006976 if (index >= 0) {
6977 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006978 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006979 ALOGV("getNewInputDevice() device %s forced by patch %d",
6980 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6981 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006982 }
6983 }
6984
Eric Laurent97ac8712018-07-27 18:59:02 -07006985 // Honor explicit routing requests only if no client using default routing is active on this
6986 // input: a specific app can not force routing for other apps by setting a preferred device.
6987 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006988 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6989 if (device != nullptr) {
6990 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006991 }
6992
Eric Laurentdc95a252018-04-12 12:46:56 -07006993 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006994 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006995 audio_attributes_t attributes;
6996 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006997 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006998 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6999 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007000 attributes = topClient->attributes();
7001 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007002 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007003 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007004 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7005 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007006 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007007 }
7008
Francois Gaffie716e1432019-01-14 16:58:59 +01007009 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7010 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007011 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007012 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007013 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007014 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007015
Eric Laurente552edb2014-03-10 17:42:56 -07007016 return device;
7017}
7018
Eric Laurent794fde22016-03-11 09:50:45 -08007019bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7020 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007021 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007022}
7023
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007024status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007025 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007026 if (devices == nullptr) {
7027 return BAD_VALUE;
7028 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007029
Andy Hung6d23c0f2022-02-16 09:37:15 -08007030 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007031 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7032 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007033 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007034 for (const auto& device : curDevices) {
7035 devices->push_back(device->getDeviceTypeAddr());
7036 }
7037 return NO_ERROR;
7038}
7039
Eric Laurente0720872014-03-11 09:30:41 -07007040void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007041 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007042 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007043 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007044 updateDevicesAndOutputs();
7045 break;
7046 default:
7047 break;
7048 }
7049}
7050
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007051uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007052
7053 // skip beacon mute management if a dedicated TTS output is available
7054 if (mTtsOutputAvailable) {
7055 return 0;
7056 }
7057
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007058 switch(event) {
7059 case STARTING_OUTPUT:
7060 mBeaconMuteRefCount++;
7061 break;
7062 case STOPPING_OUTPUT:
7063 if (mBeaconMuteRefCount > 0) {
7064 mBeaconMuteRefCount--;
7065 }
7066 break;
7067 case STARTING_BEACON:
7068 mBeaconPlayingRefCount++;
7069 break;
7070 case STOPPING_BEACON:
7071 if (mBeaconPlayingRefCount > 0) {
7072 mBeaconPlayingRefCount--;
7073 }
7074 break;
7075 }
7076
7077 if (mBeaconMuteRefCount > 0) {
7078 // any playback causes beacon to be muted
7079 return setBeaconMute(true);
7080 } else {
7081 // no other playback: unmute when beacon starts playing, mute when it stops
7082 return setBeaconMute(mBeaconPlayingRefCount == 0);
7083 }
7084}
7085
7086uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7087 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7088 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7089 // keep track of muted state to avoid repeating mute/unmute operations
7090 if (mBeaconMuted != mute) {
7091 // mute/unmute AUDIO_STREAM_TTS on all outputs
7092 ALOGV("\t muting %d", mute);
7093 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007094 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7095 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7096 ALOGV("\t no tts volume source available");
7097 return 0;
7098 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007099 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007100 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007101 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007102 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007103 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007104 maxLatency = latency;
7105 }
7106 }
7107 mBeaconMuted = mute;
7108 return maxLatency;
7109 }
7110 return 0;
7111}
7112
Eric Laurente0720872014-03-11 09:30:41 -07007113void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007114{
François Gaffiec005e562018-11-06 15:04:49 +01007115 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007116 mPreviousOutputs = mOutputs;
7117}
7118
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007119uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007120 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007121 uint32_t delayMs)
7122{
7123 // mute/unmute strategies using an incompatible device combination
7124 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7125 // if unmuting, unmute only after the specified delay
7126 if (outputDesc->isDuplicated()) {
7127 return 0;
7128 }
7129
7130 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007131 DeviceVector devices = outputDesc->devices();
7132 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007133
François Gaffiec005e562018-11-06 15:04:49 +01007134 auto productStrategies = mEngine->getOrderedProductStrategies();
7135 for (const auto &productStrategy : productStrategies) {
7136 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7137 DeviceVector curDevices =
7138 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7139 curDevices = curDevices.filter(outputDesc->supportedDevices());
7140 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007141 bool doMute = false;
7142
François Gaffiec005e562018-11-06 15:04:49 +01007143 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007144 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007145 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7146 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007147 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007148 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007149 }
Eric Laurent99401132014-05-07 19:48:15 -07007150 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007151 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007152 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007153 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007154 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007155 continue;
7156 }
François Gaffiec005e562018-11-06 15:04:49 +01007157 ALOGVV("%s() %s (curDevice %s)", __func__,
7158 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7159 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7160 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007161 if (mute) {
7162 // FIXME: should not need to double latency if volume could be applied
7163 // immediately by the audioflinger mixer. We must account for the delay
7164 // between now and the next time the audioflinger thread for this output
7165 // will process a buffer (which corresponds to one buffer size,
7166 // usually 1/2 or 1/4 of the latency).
7167 if (muteWaitMs < desc->latency() * 2) {
7168 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007169 }
7170 }
7171 }
7172 }
7173 }
7174 }
7175
Eric Laurent99401132014-05-07 19:48:15 -07007176 // temporary mute output if device selection changes to avoid volume bursts due to
7177 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007178 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007179 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007180
Eric Laurentdc462862016-07-19 12:29:53 -07007181 if (muteWaitMs < tempMuteWaitMs) {
7182 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007183 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007184
7185 // If recommended duration is defined, replace temporary mute duration to avoid
7186 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7187 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7188 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7189 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7190 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7191
François Gaffieaaac0fd2018-11-22 17:56:39 +01007192 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7193 // make sure that we do not start the temporary mute period too early in case of
7194 // delayed device change
7195 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7196 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007197 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007198 }
7199 }
7200
Eric Laurente552edb2014-03-10 17:42:56 -07007201 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7202 if (muteWaitMs > delayMs) {
7203 muteWaitMs -= delayMs;
7204 usleep(muteWaitMs * 1000);
7205 return muteWaitMs;
7206 }
7207 return 0;
7208}
7209
François Gaffie11d30102018-11-02 16:09:09 +01007210uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7211 const DeviceVector &devices,
7212 bool force,
7213 int delayMs,
7214 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007215 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007216{
jiabin3ff8d7d2022-12-13 06:27:44 +00007217 // TODO(b/262404095): Consider if the output need to be reopened.
François Gaffie11d30102018-11-02 16:09:09 +01007218 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007219 uint32_t muteWaitMs;
7220
7221 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007222 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7223 nullptr /* patchHandle */, requiresMuteCheck);
7224 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7225 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007226 return muteWaitMs;
7227 }
Eric Laurente552edb2014-03-10 17:42:56 -07007228
7229 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007230 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007231 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007232 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007233
François Gaffie11d30102018-11-02 16:09:09 +01007234 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7235
7236 if (!filteredDevices.isEmpty()) {
7237 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007238 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007239
7240 // if the outputs are not materially active, there is no need to mute.
7241 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007242 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007243 } else {
7244 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7245 muteWaitMs = 0;
7246 }
Eric Laurente552edb2014-03-10 17:42:56 -07007247
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007248 bool outputRouted = outputDesc->isRouted();
7249
Eric Laurent79ea9582020-06-11 18:49:24 -07007250 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7251 // output profile or if new device is not supported AND previous device(s) is(are) still
7252 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007253 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007254 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7255 // restore previous device after evaluating strategy mute state
7256 outputDesc->setDevices(prevDevices);
7257 return muteWaitMs;
7258 }
7259
Eric Laurente552edb2014-03-10 17:42:56 -07007260 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007261 // the requested device is AUDIO_DEVICE_NONE
7262 // OR the requested device is the same as current device
7263 // AND force is not specified
7264 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007265 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007266 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007267 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7268 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007269 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7270 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7271 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7272 }
Eric Laurente552edb2014-03-10 17:42:56 -07007273 return muteWaitMs;
7274 }
7275
François Gaffie11d30102018-11-02 16:09:09 +01007276 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007277
Eric Laurente552edb2014-03-10 17:42:56 -07007278 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007279 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007280 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007281 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007282 PatchBuilder patchBuilder;
7283 patchBuilder.addSource(outputDesc);
7284 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7285 for (const auto &filteredDevice : filteredDevices) {
7286 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007287 }
7288
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007289 // Add half reported latency to delayMs when muteWaitMs is null in order
7290 // to avoid disordered sequence of muting volume and changing devices.
7291 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7292 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007293 }
Eric Laurente552edb2014-03-10 17:42:56 -07007294
7295 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007296 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007297
7298 return muteWaitMs;
7299}
7300
Eric Laurentc75307b2015-03-17 15:29:32 -07007301status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007302 int delayMs,
7303 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007304{
Eric Laurent6a94d692014-05-20 11:18:06 -07007305 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007306 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7307 return INVALID_OPERATION;
7308 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007309 if (patchHandle) {
7310 index = mAudioPatches.indexOfKey(*patchHandle);
7311 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007312 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007313 }
7314 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007315 return INVALID_OPERATION;
7316 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007317 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007318 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007319 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007320 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007321 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007322 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007323 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007324 return status;
7325}
7326
7327status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007328 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007329 bool force,
7330 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007331{
7332 status_t status = NO_ERROR;
7333
Eric Laurent1f2f2232014-06-02 12:01:23 -07007334 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007335 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7336 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007337
François Gaffie11d30102018-11-02 16:09:09 +01007338 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007339 PatchBuilder patchBuilder;
7340 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007341 // AUDIO_SOURCE_HOTWORD is for internal use only:
7342 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007343 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7344 auto result = usecase;
7345 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7346 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7347 }
7348 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007349 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007350 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007351 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007352 }
7353 }
7354 return status;
7355}
7356
Eric Laurent6a94d692014-05-20 11:18:06 -07007357status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7358 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007359{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007360 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007361 ssize_t index;
7362 if (patchHandle) {
7363 index = mAudioPatches.indexOfKey(*patchHandle);
7364 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007365 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007366 }
7367 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007368 return INVALID_OPERATION;
7369 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007370 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007371 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007372 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007373 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007374 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007375 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007376 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007377 return status;
7378}
7379
François Gaffie11d30102018-11-02 16:09:09 +01007380sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007381 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007382 audio_format_t& format,
7383 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007384 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007385{
7386 // Choose an input profile based on the requested capture parameters: select the first available
7387 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007388 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007389 //
7390 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7391 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007392
jiabin2fd710d2022-05-02 23:20:22 +00007393 const audio_input_flags_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ;
7394 const audio_input_flags_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007395
jiabin2fd710d2022-05-02 23:20:22 +00007396 for (;;) {
7397 sp<IOProfile> firstInexact = nullptr;
7398 uint32_t updatedSamplingRate = 0;
7399 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7400 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7401 for (const auto& hwModule : mHwModules) {
7402 for (const auto& profile : hwModule->getInputProfiles()) {
7403 // profile->log();
7404 //updatedFormat = format;
7405 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7406 &samplingRate /*updatedSamplingRate*/,
7407 format,
7408 &format, /*updatedFormat*/
7409 channelMask,
7410 &channelMask /*updatedChannelMask*/,
7411 // FIXME ugly cast
7412 (audio_output_flags_t) flags,
7413 true /*exactMatchRequiredForInputFlags*/)) {
7414 return profile;
7415 }
7416 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7417 samplingRate,
7418 &updatedSamplingRate,
7419 format,
7420 &updatedFormat,
7421 channelMask,
7422 &updatedChannelMask,
7423 // FIXME ugly cast
7424 (audio_output_flags_t) flags,
7425 false /*exactMatchRequiredForInputFlags*/)) {
7426 firstInexact = profile;
7427 }
7428 }
7429 }
7430
7431 if (firstInexact != nullptr) {
7432 samplingRate = updatedSamplingRate;
7433 format = updatedFormat;
7434 channelMask = updatedChannelMask;
7435 return firstInexact;
7436 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7437 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7438 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7439 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7440 flags = AUDIO_INPUT_FLAG_NONE;
7441 } else { // fail
7442 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7443 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7444 samplingRate, format, channelMask, oriFlags);
7445 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007446 }
7447 }
jiabin2fd710d2022-05-02 23:20:22 +00007448
7449 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007450}
7451
François Gaffieaaac0fd2018-11-22 17:56:39 +01007452float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7453 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007454 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007455 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007456{
jiabin9a3361e2019-10-01 09:38:30 -07007457 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007458
7459 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7460 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7461 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7462 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007463 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7464 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7465 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7466 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7467 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007468
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007469 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007470 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7471 mOutputs.isActive(ringVolumeSrc, 0)) {
7472 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007473 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007474 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007475 }
7476
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007477 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007478 if ((volumeSource != callVolumeSrc && (isInCall() ||
7479 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007480 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007481 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7482 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007483 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7484 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7485 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007486 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007487 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007488 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007489 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007490 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007491 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007492 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7493 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7494 // programmatically muted.
7495 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7496 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7497 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007498 bool exemptFromCapping =
7499 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7500 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007501 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7502 volumeSource, volumeDb);
7503 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007504 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7505 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7506 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007507 }
7508 }
Eric Laurente552edb2014-03-10 17:42:56 -07007509 // if a headset is connected, apply the following rules to ring tones and notifications
7510 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007511 // - always attenuate notifications volume by 6dB
7512 // - attenuate ring tones volume by 6dB unless music is not playing and
7513 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007514 // - if music is playing, always limit the volume to current music volume,
7515 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007516 if (!Intersection(deviceTypes,
7517 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7518 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007519 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7520 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007521 ((volumeSource == alarmVolumeSrc ||
7522 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007523 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7524 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7525 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007526 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7527 curves.canBeMuted()) {
7528
Eric Laurente552edb2014-03-10 17:42:56 -07007529 // when the phone is ringing we must consider that music could have been paused just before
7530 // by the music application and behave as if music was active if the last music track was
7531 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007532 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007533 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007534 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007535 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007536 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7537 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007538 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007539 float musicVolDb = computeVolume(musicCurves,
7540 musicVolumeSrc,
7541 musicCurves.getVolumeIndex(musicDevice),
7542 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007543 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7544 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7545 if (volumeDb > minVolDb) {
7546 volumeDb = minVolDb;
7547 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007548 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007549 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7550 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7551 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007552 // on A2DP, also ensure notification volume is not too low compared to media when
7553 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007554 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007555 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007556 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7557 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007558 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7559 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007560 }
7561 }
jiabin9a3361e2019-10-01 09:38:30 -07007562 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007563 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007564 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007565 }
7566 }
7567
François Gaffie43c73442018-11-08 08:21:55 +01007568 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007569}
7570
Eric Laurent3839bc02018-07-10 18:33:34 -07007571int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007572 VolumeSource fromVolumeSource,
7573 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007574{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007575 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007576 return srcIndex;
7577 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007578 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7579 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007580 float minSrc = (float)srcCurves.getVolumeIndexMin();
7581 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7582 float minDst = (float)dstCurves.getVolumeIndexMin();
7583 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007584
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007585 // preserve mute request or correct range
7586 if (srcIndex < minSrc) {
7587 if (srcIndex == 0) {
7588 return 0;
7589 }
7590 srcIndex = minSrc;
7591 } else if (srcIndex > maxSrc) {
7592 srcIndex = maxSrc;
7593 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007594 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7595}
7596
François Gaffieaaac0fd2018-11-22 17:56:39 +01007597status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7598 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007599 int index,
7600 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007601 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007602 int delayMs,
7603 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007604{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007605 // do not change actual attributes volume if the attributes is muted
7606 if (outputDesc->isMuted(volumeSource)) {
7607 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7608 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007609 return NO_ERROR;
7610 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007611 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7612 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7613 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7614 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007615
Eric Laurent2517af32020-11-25 15:31:27 +01007616 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007617 bool isHAUsed = isHearingAidUsedForComm();
7618
Eric Laurente552edb2014-03-10 17:42:56 -07007619 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007620 // if sco and call follow same curves, bypass forceUseForComm
7621 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007622 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007623 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007624 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007625 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007626 // Do not return an error here as AudioService will always set both voice call
7627 // and bluetooth SCO volumes due to stream aliasing.
7628 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007629 }
jiabin9a3361e2019-10-01 09:38:30 -07007630 if (deviceTypes.empty()) {
7631 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007632 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007633
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007634 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7635 ALOGE("invalid volume index range");
7636 return BAD_VALUE;
7637 }
7638
jiabin9a3361e2019-10-01 09:38:30 -07007639 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7640 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007641 // Force VoIP volume to max for bluetooth SCO device except if muted
7642 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007643 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007644 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007645 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007646 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007647 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007648 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007649
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007650 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007651 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007652 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed by the headset
François Gaffieaaac0fd2018-11-22 17:56:39 +01007653 if (isVoiceVolSrc) {
7654 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007655 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007656 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007657 }
Eric Laurent18fba842016-03-31 14:41:26 -07007658 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007659 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7660 mLastVoiceVolume = voiceVolume;
7661 }
7662 }
Eric Laurente552edb2014-03-10 17:42:56 -07007663 return NO_ERROR;
7664}
7665
Eric Laurentc75307b2015-03-17 15:29:32 -07007666void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007667 const DeviceTypeSet& deviceTypes,
7668 int delayMs,
7669 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007670{
jiabincd510522020-01-22 09:40:55 -08007671 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007672 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7673 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7674 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007675 curves.getVolumeIndex(deviceTypes),
7676 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007677 }
7678}
7679
François Gaffiec005e562018-11-06 15:04:49 +01007680void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7681 bool on,
7682 const sp<AudioOutputDescriptor>& outputDesc,
7683 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007684 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007685{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007686 std::vector<VolumeSource> sourcesToMute;
7687 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7688 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7689 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007690 VolumeSource source = toVolumeSource(attributes, false);
7691 if ((source != VOLUME_SOURCE_NONE) &&
7692 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7693 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007694 sourcesToMute.push_back(source);
7695 }
Eric Laurente552edb2014-03-10 17:42:56 -07007696 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007697 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007698 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007699 }
7700
Eric Laurente552edb2014-03-10 17:42:56 -07007701}
7702
François Gaffieaaac0fd2018-11-22 17:56:39 +01007703void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7704 bool on,
7705 const sp<AudioOutputDescriptor>& outputDesc,
7706 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007707 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007708{
jiabin9a3361e2019-10-01 09:38:30 -07007709 if (deviceTypes.empty()) {
7710 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007711 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007712 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007713 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007714 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007715 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007716 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007717 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7718 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007719 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007720 }
7721 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007722 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7723 // ignored
7724 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007725 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007726 if (!outputDesc->isMuted(volumeSource)) {
7727 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007728 return;
7729 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007730 if (outputDesc->decMuteCount(volumeSource) == 0) {
7731 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007732 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007733 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007734 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007735 delayMs);
7736 }
7737 }
7738}
7739
François Gaffie53615e22015-03-19 09:24:12 +01007740bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7741{
François Gaffiec005e562018-11-06 15:04:49 +01007742 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007743 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7744 return true;
7745 }
7746
7747 // has known usage?
7748 switch (paa->usage) {
7749 case AUDIO_USAGE_UNKNOWN:
7750 case AUDIO_USAGE_MEDIA:
7751 case AUDIO_USAGE_VOICE_COMMUNICATION:
7752 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7753 case AUDIO_USAGE_ALARM:
7754 case AUDIO_USAGE_NOTIFICATION:
7755 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7756 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7757 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7758 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7759 case AUDIO_USAGE_NOTIFICATION_EVENT:
7760 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7761 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7762 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7763 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007764 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007765 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007766 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007767 case AUDIO_USAGE_EMERGENCY:
7768 case AUDIO_USAGE_SAFETY:
7769 case AUDIO_USAGE_VEHICLE_STATUS:
7770 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007771 break;
7772 default:
7773 return false;
7774 }
7775 return true;
7776}
7777
François Gaffie2110e042015-03-24 08:41:51 +01007778audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7779{
7780 return mEngine->getForceUse(usage);
7781}
7782
Eric Laurent96d1dda2022-03-14 17:14:19 +01007783bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007784 return isStateInCall(mEngine->getPhoneState());
7785}
7786
Eric Laurent96d1dda2022-03-14 17:14:19 +01007787bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007788 return is_state_in_call(state);
7789}
7790
Eric Laurentf9cccec2022-11-16 19:12:00 +01007791bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007792 audio_mode_t mode = mEngine->getPhoneState();
7793 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007794 || (mode == AUDIO_MODE_CALL_SCREEN)
7795 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007796}
7797
Eric Laurentf9cccec2022-11-16 19:12:00 +01007798bool AudioPolicyManager::isInCallOrScreening() const {
7799 audio_mode_t mode = mEngine->getPhoneState();
7800 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7801}
7802
Eric Laurentd60560a2015-04-10 11:31:20 -07007803void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7804{
7805 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007806 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007807 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007808 sourceDesc->sinkDevice()->equals(deviceDesc))
7809 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007810 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007811 }
7812 }
7813
7814 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7815 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7816 bool release = false;
7817 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7818 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7819 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7820 source->ext.device.type == deviceDesc->type()) {
7821 release = true;
7822 }
7823 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007824 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007825 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7826 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7827 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007828 sink->ext.device.type == deviceDesc->type() &&
7829 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7830 || strncmp(sink->ext.device.address, address,
7831 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007832 release = true;
7833 }
7834 }
7835 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007836 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7837 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007838 }
7839 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007840
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007841 mInputs.clearSessionRoutesForDevice(deviceDesc);
7842
Francois Gaffie716e1432019-01-14 16:58:59 +01007843 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007844}
7845
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007846void AudioPolicyManager::modifySurroundFormats(
7847 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007848 std::unordered_set<audio_format_t> enforcedSurround(
7849 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007850 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7851 for (const auto& pair : mConfig.getSurroundFormats()) {
7852 allSurround.insert(pair.first);
7853 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7854 }
Phil Burk09bc4612016-02-24 15:58:15 -08007855
7856 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7857 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007858 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007859 // This is the resulting set of formats depending on the surround mode:
7860 // 'all surround' = allSurround
7861 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7862 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7863 // 'manual surround' = mManualSurroundFormats
7864 // AUTO: formats v 'enforced surround'
7865 // ALWAYS: formats v 'all surround' v 'enforced surround'
7866 // NEVER: formats ^ 'non-surround'
7867 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007868
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007869 std::unordered_set<audio_format_t> formatSet;
7870 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7871 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007872 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007873 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007874 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007875 formatSet.insert(*formatIter);
7876 }
7877 }
7878 } else {
7879 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7880 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007881 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007882
jiabin81772902018-04-02 17:52:27 -07007883 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007884 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007885 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7886 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7887 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007888 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007889 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7890 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7891 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007892 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007893 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007894 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007895 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007896 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007897 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007898}
7899
jiabin06e4bab2019-07-29 10:13:34 -07007900void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7901 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007902 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7903 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7904
7905 // If NEVER, then remove support for channelMasks > stereo.
7906 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007907 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7908 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007909 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007910 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007911 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007912 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007913 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007914 }
7915 }
jiabin81772902018-04-02 17:52:27 -07007916 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7917 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7918 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007919 bool supports5dot1 = false;
7920 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007921 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007922 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7923 supports5dot1 = true;
7924 break;
7925 }
7926 }
7927 // If not then add 5.1 support.
7928 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007929 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007930 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007931 }
Phil Burk09bc4612016-02-24 15:58:15 -08007932 }
7933}
7934
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007935void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007936 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007937 AudioProfileVector &profiles)
7938{
7939 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007940 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007941
François Gaffie112b0af2015-11-19 16:13:25 +01007942 // Format MUST be checked first to update the list of AudioProfile
7943 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007944 reply = mpClientInterface->getParameters(
7945 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007946 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007947 AudioParameter repliedParameters(reply);
7948 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007949 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007950 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7951 return;
7952 }
Phil Burk09bc4612016-02-24 15:58:15 -08007953 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007954 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007955 if (device == AUDIO_DEVICE_OUT_HDMI
7956 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007957 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007958 }
jiabin3e277cc2019-09-10 14:27:34 -07007959 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007960 }
François Gaffie112b0af2015-11-19 16:13:25 +01007961
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007962 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007963 ChannelMaskSet channelMasks;
7964 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007965 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007966 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007967
7968 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007969 reply = mpClientInterface->getParameters(
7970 ioHandle,
7971 requestedParameters.toString() + ";" +
7972 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007973 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007974 AudioParameter repliedParameters(reply);
7975 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007976 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007977 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007978 }
7979 }
7980 if (profiles.hasDynamicChannelsFor(format)) {
7981 reply = mpClientInterface->getParameters(ioHandle,
7982 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007983 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007984 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007985 AudioParameter repliedParameters(reply);
7986 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007987 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007988 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007989 if (device == AUDIO_DEVICE_OUT_HDMI
7990 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007991 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007992 }
François Gaffie112b0af2015-11-19 16:13:25 +01007993 }
7994 }
jiabin3e277cc2019-09-10 14:27:34 -07007995 addDynamicAudioProfileAndSort(
7996 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007997 }
7998}
Eric Laurentd60560a2015-04-10 11:31:20 -07007999
Mikhail Naganovdc769682018-05-04 15:34:08 -07008000status_t AudioPolicyManager::installPatch(const char *caller,
8001 audio_patch_handle_t *patchHandle,
8002 AudioIODescriptorInterface *ioDescriptor,
8003 const struct audio_patch *patch,
8004 int delayMs)
8005{
8006 ssize_t index = mAudioPatches.indexOfKey(
8007 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8008 *patchHandle : ioDescriptor->getPatchHandle());
8009 sp<AudioPatch> patchDesc;
8010 status_t status = installPatch(
8011 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8012 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008013 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008014 }
8015 return status;
8016}
8017
8018status_t AudioPolicyManager::installPatch(const char *caller,
8019 ssize_t index,
8020 audio_patch_handle_t *patchHandle,
8021 const struct audio_patch *patch,
8022 int delayMs,
8023 uid_t uid,
8024 sp<AudioPatch> *patchDescPtr)
8025{
8026 sp<AudioPatch> patchDesc;
8027 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8028 if (index >= 0) {
8029 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008030 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008031 }
8032
8033 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8034 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8035 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8036 if (status == NO_ERROR) {
8037 if (index < 0) {
8038 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008039 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008040 } else {
8041 patchDesc->mPatch = *patch;
8042 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008043 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008044 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008045 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008046 }
8047 nextAudioPortGeneration();
8048 mpClientInterface->onAudioPatchListUpdate();
8049 }
8050 if (patchDescPtr) *patchDescPtr = patchDesc;
8051 return status;
8052}
8053
jiabinbce0c1d2020-10-05 11:20:18 -07008054bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8055{
8056 const TrackClientVector activeClients = output->getActiveClients();
8057 if (activeClients.empty()) {
8058 return true;
8059 }
8060 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8061 if (index < 0) {
8062 ALOGE("%s, no audio patch found while there are active clients on output %d",
8063 __func__, output->getId());
8064 return false;
8065 }
8066 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8067 DeviceVector routedDevices;
8068 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8069 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8070 patchDesc->mPatch.sinks[i].id);
8071 if (device == nullptr) {
8072 ALOGE("%s, no audio device found with id(%d)",
8073 __func__, patchDesc->mPatch.sinks[i].id);
8074 return false;
8075 }
8076 routedDevices.add(device);
8077 }
8078 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008079 if (client->isInvalid()) {
8080 // No need to take care about invalidated clients.
8081 continue;
8082 }
jiabinbce0c1d2020-10-05 11:20:18 -07008083 sp<DeviceDescriptor> preferredDevice =
8084 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8085 if (mEngine->getOutputDevicesForAttributes(
8086 client->attributes(), preferredDevice, false) == routedDevices) {
8087 return false;
8088 }
8089 }
8090 return true;
8091}
8092
8093sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008094 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008095 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8096 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008097{
8098 for (const auto& device : devices) {
8099 // TODO: This should be checking if the profile supports the device combo.
8100 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008101 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8102 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008103 return nullptr;
8104 }
8105 }
8106 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8107 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008108 status_t status = desc->open(halConfig, mixerConfig, devices,
8109 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008110 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008111 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008112 return nullptr;
8113 }
8114
8115 // Here is where the out_set_parameters() for card & device gets called
8116 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8117 const audio_devices_t deviceType = device->type();
8118 const String8 &address = String8(device->address().c_str());
8119 if (!address.isEmpty()) {
8120 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8121 mpClientInterface->setParameters(output, String8(param));
8122 free(param);
8123 }
8124 updateAudioProfiles(device, output, profile->getAudioProfiles());
8125 if (!profile->hasValidAudioProfile()) {
8126 ALOGW("%s() missing param", __func__);
8127 desc->close();
8128 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008129 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8130 // Reopen the output with the best audio profile picked by APM when the profile supports
8131 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008132 desc->close();
8133 output = AUDIO_IO_HANDLE_NONE;
8134 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8135 profile->pickAudioProfile(
8136 config.sample_rate, config.channel_mask, config.format);
8137 config.offload_info.sample_rate = config.sample_rate;
8138 config.offload_info.channel_mask = config.channel_mask;
8139 config.offload_info.format = config.format;
8140
jiabina84c3d32022-12-02 18:59:55 +00008141 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008142 if (status != NO_ERROR) {
8143 return nullptr;
8144 }
8145 }
8146
8147 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008148
baek.kim -61c20122022-07-27 10:05:32 +00008149 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8150 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8151
jiabinbce0c1d2020-10-05 11:20:18 -07008152 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8153 sp<AudioPolicyMix> policyMix;
8154 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8155 policyMix->setOutput(desc);
8156 desc->mPolicyMix = policyMix;
8157 } else {
8158 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8159 address.string());
8160 }
8161
baek.kim -61c20122022-07-27 10:05:32 +00008162 } else if (hasPrimaryOutput() && speaker != nullptr
8163 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008164 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8165 // no duplicated output for:
8166 // - direct outputs
8167 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008168 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008169 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8170
8171 //TODO: configure audio effect output stage here
8172
8173 // open a duplicating output thread for the new output and the primary output
8174 sp<SwAudioOutputDescriptor> dupOutputDesc =
8175 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8176 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8177 if (status == NO_ERROR) {
8178 // add duplicated output descriptor
8179 addOutput(duplicatedOutput, dupOutputDesc);
8180 } else {
8181 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8182 mPrimaryOutput->mIoHandle, output);
8183 desc->close();
8184 removeOutput(output);
8185 nextAudioPortGeneration();
8186 return nullptr;
8187 }
8188 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008189 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8190 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8191 mPrimaryOutput = desc;
8192 }
jiabinbce0c1d2020-10-05 11:20:18 -07008193 return desc;
8194}
8195
jiabinf1c73972022-04-14 16:28:52 -07008196status_t AudioPolicyManager::getDevicesForAttributes(
8197 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8198 // Devices are determined in the following precedence:
8199 //
8200 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8201 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8202 //
8203 // If no such dynamic policy then
8204 // 2) Devices containing an active client using setPreferredDevice
8205 // with same strategy as the attributes.
8206 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8207 //
8208 // If no corresponding active client with setPreferredDevice then
8209 // 3) Devices associated with the strategy determined by the attributes
8210 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8211 //
8212 // See related getOutputForAttrInt().
8213
8214 // check dynamic policies but only for primary descriptors (secondary not used for audible
8215 // audio routing, only used for duplication for playback capture)
8216 sp<AudioPolicyMix> policyMix;
8217 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02008218 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE, policyMix,
jiabinf1c73972022-04-14 16:28:52 -07008219 nullptr /* secondaryMixes */);
8220 if (status != OK) {
8221 return status;
8222 }
8223
8224 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8225 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8226 // as they are unaffected by device/stream volume
8227 // (per SwAudioOutputDescriptor::isFixedVolume()).
8228 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8229 ) {
8230 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8231 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8232 devices.add(deviceDesc);
8233 } else {
8234 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8235 // which selects setPreferredDevice if active. This means forVolume call
8236 // will take an active setPreferredDevice, if such exists.
8237
8238 devices = mEngine->getOutputDevicesForAttributes(
8239 attr, nullptr /* preferredDevice */, false /* fromCache */);
8240 }
8241
8242 if (forVolume) {
8243 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8244 // for single volume control in AudioService (such relationship should exist if
8245 // SPEAKER_SAFE is present).
8246 //
8247 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8248 DeviceVector speakerSafeDevices =
8249 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8250 if (!speakerSafeDevices.isEmpty()) {
8251 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8252 devices.remove(speakerSafeDevices);
8253 }
8254 }
8255
8256 return NO_ERROR;
8257}
8258
8259status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8260 AudioProfileVector& audioProfiles,
8261 uint32_t flags,
8262 bool isInput) {
8263 for (const auto& hwModule : mHwModules) {
8264 // the MSD module checks for different conditions
8265 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8266 continue;
8267 }
8268 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8269 : hwModule->getOutputProfiles();
8270 for (const auto& profile : ioProfiles) {
8271 if (!profile->areAllDevicesSupported(devices) ||
8272 !profile->isCompatibleProfileForFlags(
8273 flags, false /*exactMatchRequiredForInputFlags*/)) {
8274 continue;
8275 }
8276 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8277 }
8278 }
8279
8280 if (!isInput) {
8281 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8282 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8283 if (msdModule != nullptr) {
8284 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8285 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8286 for (const auto &profile: msdModule->getOutputProfiles()) {
8287 if (!profile->asAudioPort()->isDirectOutput()) {
8288 continue;
8289 }
8290 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8291 }
8292 } else {
8293 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8294 }
8295 }
8296 }
8297
8298 return NO_ERROR;
8299}
8300
jiabin3ff8d7d2022-12-13 06:27:44 +00008301sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8302 const audio_config_t *config,
8303 audio_output_flags_t flags,
8304 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008305 closeOutput(outputDesc->mIoHandle);
8306 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8307 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8308 if (preferredOutput == nullptr) {
8309 ALOGE("%s failed to reopen output device=%d, caller=%s",
8310 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008311 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008312 return preferredOutput;
8313}
8314
8315void AudioPolicyManager::reopenOutputsWithDevices(
8316 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8317 for (const auto& [output, devices] : outputsToReopen) {
8318 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8319 closeOutput(output);
8320 openOutputWithProfileAndDevice(desc->mProfile, devices);
8321 }
jiabina84c3d32022-12-02 18:59:55 +00008322}
8323
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008324} // namespace android