blob: 959dd4f8a909db58b5f62d57463a2560960d7aed [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) {
117 media::AudioPort aidlPort;
118 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) {
175 media::AudioPort aidlPort;
176 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*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700322 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100323 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700324 const DeviceVector activeMediaDevices =
325 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
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));
François Gaffie11d30102018-11-02 16:09:09 +0100339 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700340 }
jiabinbce0c1d2020-10-05 11:20:18 -0700341 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000342 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700343 desc->supportsDevicesForPlayback(activeMediaDevices)) {
344 // Reopen the output to query the dynamic profiles when there is not active
345 // clients or all active clients will be rerouted. Otherwise, set the flag
346 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
347 // can be reopened to query dynamic profiles when all clients are inactive.
348 if (areAllActiveTracksRerouted(desc)) {
349 outputsToReopen.push_back(mOutputs.keyAt(i));
350 } else {
351 desc->mPendingReopenToQueryProfiles = true;
352 }
353 }
354 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
355 // Clear the flag that previously set for re-querying profiles.
356 desc->mPendingReopenToQueryProfiles = false;
357 }
358 }
359 for (const auto& output : outputsToReopen) {
360 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
361 closeOutput(output);
362 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700363 }
364
Eric Laurentd60560a2015-04-10 11:31:20 -0700365 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100366 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700367 }
368
Eric Laurent96d1dda2022-03-14 17:14:19 +0100369 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
370
Eric Laurent72aa32f2014-05-30 18:51:48 -0700371 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700372 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700373 } // end if is output device
374
Eric Laurente552edb2014-03-10 17:42:56 -0700375 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700376 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100377 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700378 switch (state)
379 {
380 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700381 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700382 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700384 return INVALID_OPERATION;
385 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700386
387 if (mAvailableInputDevices.add(device) < 0) {
388 return NO_MEMORY;
389 }
390
François Gaffie44481e72016-04-20 07:49:57 +0200391 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
392 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100393 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200394
Eric Laurent0dd51852019-04-19 18:18:58 -0700395 if (checkInputsForDevice(device, state) != NO_ERROR) {
396 mAvailableInputDevices.remove(device);
397
François Gaffie11d30102018-11-02 16:09:09 +0100398 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100399
400 mHwModules.cleanUpForDevice(device);
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 return INVALID_OPERATION;
403 }
404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700406
407 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700408 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700409 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100410 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700411 return INVALID_OPERATION;
412 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700413
François Gaffie11d30102018-11-02 16:09:09 +0100414 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700415
416 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100417 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700418
François Gaffie11d30102018-11-02 16:09:09 +0100419 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700420
421 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100422
423 // remove device from mReportedFormatsMap cache
424 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700425 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700426
427 default:
François Gaffie11d30102018-11-02 16:09:09 +0100428 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700429 return BAD_VALUE;
430 }
431
Eric Laurent736a1022019-03-27 18:28:46 -0700432 // Propagate device availability to Engine
433 setEngineDeviceConnectionState(device, state);
434
Eric Laurent0dd51852019-04-19 18:18:58 -0700435 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700436 // As the input device list can impact the output device selection, update
437 // getDeviceForStrategy() cache
438 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700439
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100440 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200441 // Reconnect Audio Source
442 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
443 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
444 checkAudioSourceForAttributes(attributes);
445 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700446 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100447 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700448 }
449
Eric Laurentb52c1522014-05-20 11:27:36 -0700450 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700451 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700452 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700453
François Gaffie11d30102018-11-02 16:09:09 +0100454 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700455 return BAD_VALUE;
456}
457
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100458status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
459 const char* device_name,
460 media::AudioPort* aidlPort) {
461 DeviceDescriptorBase devDescr(device, device_address);
462 devDescr.setName(device_name);
463 return devDescr.writeToParcelable(aidlPort);
464}
465
Eric Laurent736a1022019-03-27 18:28:46 -0700466void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
467 audio_policy_dev_state_t state) {
468
469 // the Engine does not have to know about remote submix devices used by dynamic audio policies
470 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
471 return;
472 }
473 mEngine->setDeviceConnectionState(device, state);
474}
475
476
Eric Laurente0720872014-03-11 09:30:41 -0700477audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100478 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700479{
Eric Laurent634b7142016-04-20 13:48:02 -0700480 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800481 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
482 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700483 (strlen(device_address) != 0)/*matchAddress*/);
484
485 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100486 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700487 device, device_address);
488 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
489 }
François Gaffie53615e22015-03-19 09:24:12 +0100490
Eric Laurent3a4311c2014-03-17 12:00:47 -0700491 DeviceVector *deviceVector;
492
Eric Laurente552edb2014-03-10 17:42:56 -0700493 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700494 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700495 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700496 deviceVector = &mAvailableInputDevices;
497 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100498 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700499 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700500 }
Eric Laurent634b7142016-04-20 13:48:02 -0700501
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800502 return (deviceVector->getDevice(
503 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700504 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800505}
506
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800507status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
508 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800509 const char *device_name,
510 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800511{
512 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700513 String8 reply;
514 AudioParameter param;
515 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
518 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800520 // connect/disconnect only 1 device at a time
521 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
522
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700524 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800526 // Nothing to do: device is not connected
527 return NO_ERROR;
528 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800530
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700531 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800532 // configure codecs.
533 // Handle two specific cases by sending a set parameter to
534 // configure A2DP codecs. No need to toggle device state.
535 // Case 1: A2DP active device switches from primary to primary
536 // module
537 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200538 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700539 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800540 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
541 if (availablePrimaryOutputDevices().contains(devDesc) &&
542 (module != 0 && module->getHandle() == primaryHandle)) {
543 reply = mpClientInterface->getParameters(
544 AUDIO_IO_HANDLE_NONE,
545 String8(AudioParameter::keyReconfigA2dpSupported));
546 AudioParameter repliedParameters(reply);
547 repliedParameters.getInt(
548 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
549 if (isReconfigA2dpSupported) {
550 const String8 key(AudioParameter::keyReconfigA2dp);
551 param.add(key, String8("true"));
552 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
553 devDesc->setEncodedFormat(encodedFormat);
554 return NO_ERROR;
555 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700556 }
557 }
cnx421bd2dcc42020-07-11 14:58:44 +0800558 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
559 for (size_t i = 0; i < mOutputs.size(); i++) {
560 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
561 // mute media strategies and delay device switch by the largest
562 // This avoid sending the music tail into the earpiece or headset.
563 setStrategyMute(musicStrategy, true, desc);
564 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
565 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
566 nullptr, true /*fromCache*/).types());
567 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 // Toggle the device state: UNAVAILABLE -> AVAILABLE
569 // This will force reading again the device configuration
570 status = setDeviceConnectionState(device,
571 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800572 device_address, device_name,
573 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800574 if (status != NO_ERROR) {
575 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
576 status);
577 return status;
578 }
579
580 status = setDeviceConnectionState(device,
581 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800582 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800583 if (status != NO_ERROR) {
584 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
585 status);
586 return status;
587 }
588
589 return NO_ERROR;
590}
591
Pattydd807582021-11-04 21:01:03 +0800592status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
593 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800594{
Pattydd807582021-11-04 21:01:03 +0800595 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800596 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800597 std::unordered_set<audio_format_t> formatSet;
598 sp<HwModule> primaryModule =
599 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700600 if (primaryModule == nullptr) {
601 ALOGE("%s() unable to get primary module", __func__);
602 return NO_INIT;
603 }
Pattydd807582021-11-04 21:01:03 +0800604
605 DeviceTypeSet audioDeviceSet;
606
607 switch(device) {
608 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
609 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
610 break;
611 case AUDIO_DEVICE_OUT_BLE_HEADSET:
612 audioDeviceSet = getAudioDeviceOutAllBleSet();
613 break;
614 default:
615 ALOGE("%s() device type 0x%08x not supported", __func__, device);
616 return BAD_VALUE;
617 }
618
jiabin9a3361e2019-10-01 09:38:30 -0700619 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800620 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800621 for (const auto& device : declaredDevices) {
622 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800623 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800624 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800625 return status;
626}
627
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100628DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
629{
630 DeviceVector rxSinkdevices{};
631 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
632 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
633 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
634 auto rxSinkDevice = rxSinkdevices.itemAt(0);
635 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
636 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
637 // retrieve Rx Source device descriptor
638 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
639 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
640
641 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
642 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
643 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
644 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
645 return DeviceVector(rxSinkDevice);
646 }
647 }
648 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
649 // the device returned is not necessarily reachable via this output
650 // (filter later by setOutputDevices())
651 return getNewOutputDevices(mPrimaryOutput, fromCache);
652}
653
654status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
655{
656 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
657 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
658 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
659 }
660 return INVALID_OPERATION;
661}
662
663status_t AudioPolicyManager::updateCallRoutingInternal(
664 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700665{
666 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100667 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700668 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700669 if(!hasPrimaryOutput() ||
670 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100671 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700672 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100673 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100674
Francois Gaffie716e1432019-01-14 16:58:59 +0100675 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100676 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100677 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100678
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100679 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100680 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700681
Francois Gaffie601801d2021-06-22 13:27:39 +0200682 disconnectTelephonyAudioSource(mCallRxSourceClient);
683 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700684
François Gaffie9eb18552018-11-05 10:33:26 +0100685 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700686 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100687 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700688 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100689 // retrieve Rx Source and Tx Sink device descriptors
690 sp<DeviceDescriptor> rxSourceDevice =
691 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
692 String8(),
693 AUDIO_FORMAT_DEFAULT);
694 sp<DeviceDescriptor> txSinkDevice =
695 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
696 String8(),
697 AUDIO_FORMAT_DEFAULT);
698
699 // RX and TX Telephony device are declared by Primary Audio HAL
700 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
701 (telephonyRxModule->getHalVersionMajor() >= 3)) {
702 if (rxSourceDevice == 0 || txSinkDevice == 0) {
703 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100704 ALOGE("%s() no telephony Tx and/or RX device", __func__);
705 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100706 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100707 // createAudioPatchInternal now supports both HW / SW bridging
708 createRxPatch = true;
709 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100710 } else {
711 // If the RX device is on the primary HW module, then use legacy routing method for
712 // voice calls via setOutputDevice() on primary output.
713 // Otherwise, create two audio patches for TX and RX path.
714 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
715 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700716 // If the TX device is also on the primary HW module, setOutputDevice() will take care
717 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100718 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
719 (txSinkDevice != 0);
720 }
721 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
722 // Otherwise, create two audio patches for TX and RX path.
723 if (!createRxPatch) {
724 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700725 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200726 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800727 // If the TX device is on the primary HW module but RX device is
728 // on other HW module, SinkMetaData of telephony input should handle it
729 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700730 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700731 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100732 // terminate active capture if on the same HW module as the call TX source device
733 // FIXME: would be better to refine to only inputs whose profile connects to the
734 // call TX device but this information is not in the audio patch and logic here must be
735 // symmetric to the one in startInput()
736 for (const auto& activeDesc : mInputs.getActiveInputs()) {
737 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
738 closeActiveClients(activeDesc);
739 }
740 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200741 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800742 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100743 if (waitMs != nullptr) {
744 *waitMs = muteWaitMs;
745 }
746 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800747}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700748
Mikhail Naganov100f0122018-11-29 11:22:16 -0800749bool AudioPolicyManager::isDeviceOfModule(
750 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
751 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
752 if (module != 0) {
753 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
754 .indexOf(devDesc) != NAME_NOT_FOUND
755 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
756 .indexOf(devDesc) != NAME_NOT_FOUND;
757 }
758 return false;
759}
760
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200761void AudioPolicyManager::connectTelephonyRxAudioSource()
762{
Francois Gaffie601801d2021-06-22 13:27:39 +0200763 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200764 const struct audio_port_config source = {
765 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
766 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
767 };
768 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200769 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
770 ALOGE_IF(mCallRxSourceClient == nullptr,
771 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200772}
773
Francois Gaffie601801d2021-06-22 13:27:39 +0200774void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200775{
Francois Gaffie601801d2021-06-22 13:27:39 +0200776 if (clientDesc == nullptr) {
777 return;
778 }
779 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
780 "%s error stopping audio source", __func__);
781 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200782}
783
784void AudioPolicyManager::connectTelephonyTxAudioSource(
785 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
786 uint32_t delayMs)
787{
Francois Gaffie601801d2021-06-22 13:27:39 +0200788 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200789 if (srcDevice == nullptr || sinkDevice == nullptr) {
790 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
791 return;
792 }
793 PatchBuilder patchBuilder;
794 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
795 ALOGV("%s between source %s and sink %s", __func__,
796 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200797 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200798 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
799
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200800 struct audio_port_config source = {};
801 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200802 mCallTxSourceClient = new InternalSourceClientDescriptor(
803 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200804 mCommunnicationStrategy, toVolumeSource(aa));
805 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
806 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200807 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
808 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200809 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
810 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200811 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200812 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200813}
814
Eric Laurente0720872014-03-11 09:30:41 -0700815void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700816{
817 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100818 // store previous phone state for management of sonification strategy below
819 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100820 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100821
822 if (mEngine->setPhoneState(state) != NO_ERROR) {
823 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700824 return;
825 }
François Gaffie2110e042015-03-24 08:41:51 +0100826 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700827 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700828 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700829 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800830 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700831 }
832
François Gaffie2110e042015-03-24 08:41:51 +0100833 /**
834 * Switching to or from incall state or switching between telephony and VoIP lead to force
835 * routing command.
836 */
Eric Laurent74b71512019-11-06 17:21:57 -0800837 bool force = ((isStateInCall(oldState) != isStateInCall(state))
838 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700839
840 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700841 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700842
Eric Laurente552edb2014-03-10 17:42:56 -0700843 int delayMs = 0;
844 if (isStateInCall(state)) {
845 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100846 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
847 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700848 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700849 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700850 // mute media and sonification strategies and delay device switch by the largest
851 // latency of any output where either strategy is active.
852 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100853 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
854 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
855 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700856 (delayMs < (int)desc->latency()*2)) {
857 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700858 }
François Gaffiec005e562018-11-06 15:04:49 +0100859 setStrategyMute(musicStrategy, true, desc);
860 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
861 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
862 nullptr, true /*fromCache*/).types());
863 setStrategyMute(sonificationStrategy, true, desc);
864 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
865 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
866 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700867 }
868 }
869
Eric Laurent87ffa392015-05-22 10:32:38 -0700870 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700871 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100872 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700873 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100874 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
875 // force routing command to audio hardware when ending call
876 // even if no device change is needed
877 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
878 rxDevices = mPrimaryOutput->devices();
879 }
880 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200881 disconnectTelephonyAudioSource(mCallRxSourceClient);
882 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100883 }
François Gaffie11d30102018-11-02 16:09:09 +0100884 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700885 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700886 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700887
888 // reevaluate routing on all outputs in case tracks have been started during the call
889 for (size_t i = 0; i < mOutputs.size(); i++) {
890 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100891 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200892 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
893 bool forceRouting = !newDevices.isEmpty();
894 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
895 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700896 }
897 }
898
Eric Laurent96d1dda2022-03-14 17:14:19 +0100899 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
900
Eric Laurente552edb2014-03-10 17:42:56 -0700901 if (isStateInCall(state)) {
902 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700903 // force reevaluating accessibility routing when call starts
904 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700905 }
906
907 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100908 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
909 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700910}
911
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700912audio_mode_t AudioPolicyManager::getPhoneState() {
913 return mEngine->getPhoneState();
914}
915
Eric Laurente0720872014-03-11 09:30:41 -0700916void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100917 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700918{
François Gaffie2110e042015-03-24 08:41:51 +0100919 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700920 if (config == mEngine->getForceUse(usage)) {
921 return;
922 }
Eric Laurente552edb2014-03-10 17:42:56 -0700923
François Gaffie2110e042015-03-24 08:41:51 +0100924 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
925 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
926 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700927 }
François Gaffie2110e042015-03-24 08:41:51 +0100928 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
929 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
930 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700931
932 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700933 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800934
Eric Laurent22fcda22019-05-17 16:28:47 -0700935 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
936 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
937 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
938 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
939 }
940
Eric Laurentdc462862016-07-19 12:29:53 -0700941 //FIXME: workaround for truncated touch sounds
942 // to be removed when the problem is handled by system UI
943 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700944 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
945 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
946 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700947
948 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100949 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700950}
951
Eric Laurente0720872014-03-11 09:30:41 -0700952void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700953{
954 ALOGV("setSystemProperty() property %s, value %s", property, value);
955}
956
Dorin Drimusecc9f422022-03-09 17:57:40 +0100957// Find an MSD output profile compatible with the parameters passed.
958// When "directOnly" is set, restrict search to profiles for direct outputs.
959sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
960 const DeviceVector& devices,
961 uint32_t samplingRate,
962 audio_format_t format,
963 audio_channel_mask_t channelMask,
964 audio_output_flags_t flags,
965 bool directOnly)
966{
967 flags = getRelevantFlags(flags, directOnly);
968
969 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
970 if (msdModule != nullptr) {
971 // for the msd module check if there are patches to the output devices
972 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
973 HwModuleCollection modules;
974 modules.add(msdModule);
975 return searchCompatibleProfileHwModules(
976 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
977 flags, directOnly);
978 }
979 }
980 return nullptr;
981}
982
Michael Chana94fbb22018-04-24 14:31:19 +1000983// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
984// search to profiles for direct outputs.
985sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100986 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000987 uint32_t samplingRate,
988 audio_format_t format,
989 audio_channel_mask_t channelMask,
990 audio_output_flags_t flags,
991 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700992{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100993 flags = getRelevantFlags(flags, directOnly);
994
995 return searchCompatibleProfileHwModules(
996 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
997}
998
999audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1000 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001001 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001002 // only retain flags that will drive the direct output profile selection
1003 // if explicitly requested
1004 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001005 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001006 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1007 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001008 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001009 return flags;
1010}
Eric Laurent861a6282015-05-18 15:40:16 -07001011
Dorin Drimusecc9f422022-03-09 17:57:40 +01001012sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1013 const HwModuleCollection& hwModules,
1014 const DeviceVector& devices,
1015 uint32_t samplingRate,
1016 audio_format_t format,
1017 audio_channel_mask_t channelMask,
1018 audio_output_flags_t flags,
1019 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001020 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001021 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001022 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001023 if (!curProfile->isCompatibleProfile(devices,
1024 samplingRate, NULL /*updatedSamplingRate*/,
1025 format, NULL /*updatedFormat*/,
1026 channelMask, NULL /*updatedChannelMask*/,
1027 flags)) {
1028 continue;
1029 }
1030 // reject profiles not corresponding to a device currently available
1031 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1032 continue;
1033 }
1034 // reject profiles if connected device does not support codec
1035 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1036 continue;
1037 }
1038 if (!directOnly) {
1039 return curProfile;
1040 }
1041
1042 // when searching for direct outputs, if several profiles are compatible, give priority
1043 // to one with offload capability
1044 if (profile != 0 &&
1045 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001046 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001047 }
1048 profile = curProfile;
1049 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1050 break;
1051 }
Eric Laurente552edb2014-03-10 17:42:56 -07001052 }
1053 }
Eric Laurent861a6282015-05-18 15:40:16 -07001054 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001055}
1056
Eric Laurentfa0f6742021-08-17 18:39:44 +02001057sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001058 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001059{
1060 for (const auto& hwModule : mHwModules) {
1061 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001062 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001063 continue;
1064 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001065 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001066 // reject profiles not corresponding to a device currently available
1067 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1068 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1069 continue;
1070 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001071 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1072 != devices.size()) {
1073 continue;
1074 }
1075 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001076 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1077 return curProfile;
1078 }
1079 }
1080 return nullptr;
1081}
1082
Eric Laurentf4e63452017-11-06 19:31:46 +00001083audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001084{
François Gaffiec005e562018-11-06 15:04:49 +01001085 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001086
1087 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1088 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1089 // format, flags, etc. This may result in some discrepancy for functions that utilize
1090 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1091 // and AudioSystem::getOutputSamplingRate().
1092
François Gaffie11d30102018-11-02 16:09:09 +01001093 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001094 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001095
François Gaffie11d30102018-11-02 16:09:09 +01001096 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1097 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001098 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001099}
1100
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001101status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1102 const audio_attributes_t *srcAttr,
1103 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001104{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001105 if (srcAttr != NULL) {
1106 if (!isValidAttributes(srcAttr)) {
1107 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1108 __func__,
1109 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1110 srcAttr->tags);
1111 return BAD_VALUE;
1112 }
1113 *dstAttr = *srcAttr;
1114 } else {
1115 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1116 ALOGE("%s: invalid stream type", __func__);
1117 return BAD_VALUE;
1118 }
François Gaffiec005e562018-11-06 15:04:49 +01001119 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001120 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001121
1122 // Only honor audibility enforced when required. The client will be
1123 // forced to reconnect if the forced usage changes.
1124 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001125 dstAttr->flags = static_cast<audio_flags_mask_t>(
1126 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001127 }
1128
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001129 return NO_ERROR;
1130}
1131
Kevin Rocard153f92d2018-12-18 18:33:28 -08001132status_t AudioPolicyManager::getOutputForAttrInt(
1133 audio_attributes_t *resultAttr,
1134 audio_io_handle_t *output,
1135 audio_session_t session,
1136 const audio_attributes_t *attr,
1137 audio_stream_type_t *stream,
1138 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001139 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001140 audio_output_flags_t *flags,
1141 audio_port_handle_t *selectedDeviceId,
1142 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001143 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001144 output_type_t *outputType,
1145 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001146{
François Gaffiec005e562018-11-06 15:04:49 +01001147 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001148 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001149 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001150 const sp<DeviceDescriptor> requestedDevice =
1151 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1152
Eric Laurent8a1095a2019-11-08 14:44:16 -08001153 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001154 *isSpatialized = false;
1155
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001156 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1157 if (status != NO_ERROR) {
1158 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001159 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001160 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001161 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001162 }
François Gaffiec005e562018-11-06 15:04:49 +01001163 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001164
François Gaffiec005e562018-11-06 15:04:49 +01001165 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1166 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001167
Kevin Rocard153f92d2018-12-18 18:33:28 -08001168 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1169 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1170 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001171 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001172 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1173 .channel_mask = config->channel_mask,
1174 .format = config->format,
1175 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001176 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
1177 primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001178 if (status != OK) {
1179 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001180 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001181
Kevin Rocard153f92d2018-12-18 18:33:28 -08001182 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001183 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001184
1185 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001186 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1187 && !audio_is_linear_pcm(config->format)) {
1188 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001189 return BAD_VALUE;
1190 }
1191 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001192 sp<DeviceDescriptor> deviceDesc =
1193 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1194 primaryMix->mDeviceAddress,
1195 AUDIO_FORMAT_DEFAULT);
1196 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001197 bool tryDirectForFlags = policyDesc == nullptr ||
1198 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1199 // if a direct output can be opened to deliver the track's multi-channel content to the
1200 // output rather than being downmixed by the primary output, then use this direct
1201 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1202 // mix.
1203 bool tryDirectForChannelMask = policyDesc != nullptr
1204 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1205 audio_channel_count_from_out_mask(config->channel_mask));
1206 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001207 audio_io_handle_t newOutput;
1208 status = openDirectOutput(
1209 *stream, session, config,
1210 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1211 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001212 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001213 policyDesc = mOutputs.valueFor(newOutput);
1214 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001215 } else if (tryDirectForFlags) {
1216 policyDesc = nullptr;
1217 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001218 }
1219 if (policyDesc != nullptr) {
1220 policyDesc->mPolicyMix = primaryMix;
1221 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001222 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001223
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001224 ALOGV("getOutputForAttr() returns output %d", *output);
1225 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1226 *outputType = API_OUT_MIX_PLAYBACK;
1227 } else {
1228 *outputType = API_OUTPUT_LEGACY;
1229 }
1230 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001231 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001232 }
François Gaffiec005e562018-11-06 15:04:49 +01001233 // Virtual sources must always be dynamicaly or explicitly routed
1234 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1235 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1236 return BAD_VALUE;
1237 }
1238 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1239 // in order to let the choice of the order to future vendor engine
1240 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001241
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001242 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001243 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001244 }
1245
Nadav Barb2f18162018-07-18 13:01:53 +03001246 // Set incall music only if device was explicitly set, and fallback to the device which is
1247 // chosen by the engine if not.
1248 // FIXME: provide a more generic approach which is not device specific and move this back
1249 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001250 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001251 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001252 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001253 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001254 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001255 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001256 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001257 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001258 }
1259 }
1260
François Gaffiec005e562018-11-06 15:04:49 +01001261 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1262 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1263 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001264
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001265 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001266 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001267 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001268 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001269 ALOGV("%s() Using MSD devices %s instead of devices %s",
1270 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001271 } else {
1272 *output = AUDIO_IO_HANDLE_NONE;
1273 }
1274 }
1275 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001276 sp<PreferredMixerAttributesInfo> info = nullptr;
1277 if (outputDevices.size() == 1) {
1278 info = getPreferredMixerAttributesInfo(
1279 outputDevices.itemAt(0)->getId(),
1280 mEngine->getProductStrategyForAttributes(*resultAttr));
1281 if (info != nullptr && info->getUid() != uid && info->getActiveClientCount() == 0) {
1282 // Only use preferred mixer when the requested uid matched or
1283 // there is active client on preferred mixer.
1284 info = nullptr;
1285 }
1286 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001287 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001288 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001289 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001290 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001291 AudioProfileVector profiles;
1292 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1293 if (ret == NO_ERROR && !profiles.empty()) {
1294 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1295 : *profiles[0]->getChannels().begin();
1296 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1297 : *profiles[0]->getSampleRates().begin();
1298 config->format = profiles[0]->getFormat();
1299 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001300 return INVALID_OPERATION;
1301 }
Paul McLeanaa981192015-03-21 09:55:15 -07001302
François Gaffiec005e562018-11-06 15:04:49 +01001303 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001304 for (auto &outputDevice : outputDevices) {
1305 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1306 *selectedDeviceId = outputDevice->getId();
1307 break;
1308 }
1309 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001310
Eric Laurent8a1095a2019-11-08 14:44:16 -08001311 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1312 *outputType = API_OUTPUT_TELEPHONY_TX;
1313 } else {
1314 *outputType = API_OUTPUT_LEGACY;
1315 }
1316
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001317 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1318
1319 return NO_ERROR;
1320}
1321
1322status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1323 audio_io_handle_t *output,
1324 audio_session_t session,
1325 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001326 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001327 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001328 audio_output_flags_t *flags,
1329 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001330 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001331 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001332 output_type_t *outputType,
1333 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001334{
1335 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1336 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1337 return INVALID_OPERATION;
1338 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001339 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001340 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001341 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001342 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001343 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001344 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001345 const sp<DeviceDescriptor> requestedDevice =
1346 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1347
1348 // Prevent from storing invalid requested device id in clients
1349 const audio_port_handle_t sanitizedRequestedPortId =
1350 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1351 *selectedDeviceId = sanitizedRequestedPortId;
1352
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001353 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001354 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001355 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001356 if (status != NO_ERROR) {
1357 return status;
1358 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001359 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001360 if (secondaryOutputs != nullptr) {
1361 for (auto &secondaryMix : secondaryMixes) {
1362 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1363 if (outputDesc != nullptr &&
1364 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1365 secondaryOutputs->push_back(outputDesc->mIoHandle);
1366 weakSecondaryOutputDescs.push_back(outputDesc);
1367 }
1368 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001369 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001370
Eric Laurent8fc147b2018-07-22 19:13:55 -07001371 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001372 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001373 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001374 };
jiabin4ef93452019-09-10 14:29:54 -07001375 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001376
Eric Laurentc209fe42020-06-05 18:11:23 -07001377 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001378 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001379 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001380 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001381 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001382 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001383 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001384 std::move(weakSecondaryOutputDescs),
1385 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001386 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001387
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001388 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1389 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001390
Eric Laurente83b55d2014-11-14 10:06:21 -08001391 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001392}
1393
Eric Laurentc529cf62020-04-17 18:19:10 -07001394status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1395 audio_session_t session,
1396 const audio_config_t *config,
1397 audio_output_flags_t flags,
1398 const DeviceVector &devices,
1399 audio_io_handle_t *output) {
1400
1401 *output = AUDIO_IO_HANDLE_NONE;
1402
1403 // skip direct output selection if the request can obviously be attached to a mixed output
1404 // and not explicitly requested
1405 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1406 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1407 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1408 return NAME_NOT_FOUND;
1409 }
1410
1411 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1412 // This prevents creating an offloaded track and tearing it down immediately after start
1413 // when audioflinger detects there is an active non offloadable effect.
1414 // FIXME: We should check the audio session here but we do not have it in this context.
1415 // This may prevent offloading in rare situations where effects are left active by apps
1416 // in the background.
1417 sp<IOProfile> profile;
1418 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1419 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1420 profile = getProfileForOutput(
1421 devices, config->sample_rate, config->format, config->channel_mask,
1422 flags, true /* directOnly */);
1423 }
1424
1425 if (profile == nullptr) {
1426 return NAME_NOT_FOUND;
1427 }
1428
1429 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1430 for (size_t i = 0; i < mOutputs.size(); i++) {
1431 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1432 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1433 // reuse direct output if currently open by the same client
1434 // and configured with same parameters
1435 if ((config->sample_rate == desc->getSamplingRate()) &&
1436 (config->format == desc->getFormat()) &&
1437 (config->channel_mask == desc->getChannelMask()) &&
1438 (session == desc->mDirectClientSession)) {
1439 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001440 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001441 mOutputs.keyAt(i), session);
1442 *output = mOutputs.keyAt(i);
1443 return NO_ERROR;
1444 }
1445 }
1446 }
1447
1448 if (!profile->canOpenNewIo()) {
1449 return NAME_NOT_FOUND;
1450 }
1451
1452 sp<SwAudioOutputDescriptor> outputDesc =
1453 new SwAudioOutputDescriptor(profile, mpClientInterface);
1454
Michael Chan6fb34492020-12-08 15:44:49 +11001455 // An MSD patch may be using the only output stream that can service this request. Release
1456 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001457 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001458
Eric Laurentf1f22e72021-07-13 14:04:14 +02001459 status_t status =
1460 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001461
1462 // only accept an output with the requested parameters
1463 if (status != NO_ERROR ||
1464 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1465 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1466 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1467 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1468 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1469 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1470 config->channel_mask, outputDesc->getChannelMask());
1471 if (*output != AUDIO_IO_HANDLE_NONE) {
1472 outputDesc->close();
1473 }
1474 // fall back to mixer output if possible when the direct output could not be open
1475 if (audio_is_linear_pcm(config->format) &&
1476 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1477 return NAME_NOT_FOUND;
1478 }
1479 *output = AUDIO_IO_HANDLE_NONE;
1480 return BAD_VALUE;
1481 }
1482 outputDesc->mDirectOpenCount = 1;
1483 outputDesc->mDirectClientSession = session;
1484
1485 addOutput(*output, outputDesc);
1486 mPreviousOutputs = mOutputs;
1487 ALOGV("%s returns new direct output %d", __func__, *output);
1488 mpClientInterface->onAudioPortListUpdate();
1489 return NO_ERROR;
1490}
1491
François Gaffie11d30102018-11-02 16:09:09 +01001492audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1493 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001494 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001495 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001496 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001497 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001498 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001499 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001500 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001501{
Andy Hungc88b0642018-04-27 15:42:35 -07001502 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001503
jiabine375d412019-02-26 12:54:53 -08001504 // Discard haptic channel mask when forcing muting haptic channels.
1505 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001506 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1507 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001508
Eric Laurente552edb2014-03-10 17:42:56 -07001509 // open a direct output if required by specified parameters
1510 //force direct flag if offload flag is set: offloading implies a direct output stream
1511 // and all common behaviors are driven by checking only the direct flag
1512 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001513 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1514 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001515 }
Nadav Bar766fb022018-01-07 12:18:03 +02001516 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1517 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001518 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001519
1520 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1521
Eric Laurente83b55d2014-11-14 10:06:21 -08001522 // only allow deep buffering for music stream type
1523 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001524 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001525 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001526 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001527 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1528 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001529 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001530 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001531 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001532 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001533 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001534 audio_is_linear_pcm(config->format) &&
1535 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001536 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001537 AUDIO_OUTPUT_FLAG_DIRECT);
1538 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001539 }
Eric Laurente552edb2014-03-10 17:42:56 -07001540
Carter Hsua3abb402021-10-26 11:11:20 +08001541 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1542 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1543 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1544 }
1545
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001546 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001547 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001548 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001549 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001550 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001551 }
1552
Eric Laurentc529cf62020-04-17 18:19:10 -07001553 audio_config_t directConfig = *config;
1554 directConfig.channel_mask = channelMask;
1555 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1556 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001557 return output;
1558 }
1559
Eric Laurent14cbfca2016-03-17 09:42:16 -07001560 // A request for HW A/V sync cannot fallback to a mixed output because time
1561 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001562 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001563 return AUDIO_IO_HANDLE_NONE;
1564 }
1565
Eric Laurente552edb2014-03-10 17:42:56 -07001566 // ignoring channel mask due to downmix capability in mixer
1567
1568 // open a non direct output
1569
1570 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001571 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001572 // get which output is suitable for the specified stream. The actual
1573 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001574 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001575 if (prefMixerConfigInfo != nullptr) {
1576 for (audio_io_handle_t outputHandle : outputs) {
1577 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1578 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1579 output = outputHandle;
1580 break;
1581 }
1582 }
1583 if (output == AUDIO_IO_HANDLE_NONE) {
1584 // No output open with the preferred profile. Open a new one.
1585 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1586 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1587 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1588 config.format = prefMixerConfigInfo->getConfigBase().format;
1589 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1590 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1591 &config, prefMixerConfigInfo->getFlags());
1592 if (preferredOutput == nullptr) {
1593 ALOGE("%s failed to open output with preferred mixer config", __func__);
1594 } else {
1595 output = preferredOutput->mIoHandle;
1596 }
1597 }
1598 } else {
1599 // at this stage we should ignore the DIRECT flag as no direct output could be
1600 // found earlier
1601 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1602 output = selectOutput(
1603 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1604 }
Eric Laurente552edb2014-03-10 17:42:56 -07001605 }
François Gaffie11d30102018-11-02 16:09:09 +01001606 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001607 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001608 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001609
Eric Laurente552edb2014-03-10 17:42:56 -07001610 return output;
1611}
1612
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001613sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001614 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1615 mAvailableInputDevices);
1616 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1617}
1618
1619DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1620 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1621 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622}
1623
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001624const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001625 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001626 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1627 if (msdModule != 0) {
1628 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1629 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1630 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1631 const struct audio_port_config *source = &patch->mPatch.sources[j];
1632 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1633 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001634 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001635 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001636 }
1637 }
1638 }
1639 return msdPatches;
1640}
1641
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001642bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1643 ssize_t index = mAudioPatches.indexOfKey(handle);
1644 if (index < 0) {
1645 return false;
1646 }
1647 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1648 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1649 if (msdModule == nullptr) {
1650 return false;
1651 }
1652 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1653 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1654 return true;
1655 }
1656 index = getMsdOutputPatches().indexOfKey(handle);
1657 if (index < 0) {
1658 return false;
1659 }
1660 return true;
1661}
1662
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001663status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1664 const InputProfileCollection &inputProfiles,
1665 const OutputProfileCollection &outputProfiles,
1666 const sp<DeviceDescriptor> &sourceDevice,
1667 const sp<DeviceDescriptor> &sinkDevice,
1668 AudioProfileVector& sourceProfiles,
1669 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001670 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001671 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001672 return NO_INIT;
1673 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001674 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001675 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001676 return NO_INIT;
1677 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001678 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001679 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1680 inProfile->supportsDevice(sourceDevice)) {
1681 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001682 }
1683 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001684 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001685 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001686 outProfile->supportsDevice(sinkDevice)) {
1687 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001688 }
1689 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001690 return NO_ERROR;
1691}
1692
1693status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1694 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1695 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1696{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001697 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001698 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1699 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1700 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001701 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001702 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1703 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001704 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001705 }
1706 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1707 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1708 sinkConfig->format = bestSinkConfig.format;
1709 // For encoded streams force direct flag to prevent downstream mixing.
1710 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1711 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001712 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1713 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001714 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001715 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1716 // raw and IEC61937 framed streams.
1717 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1718 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1719 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001720 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1721 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1722 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1723 sourceConfig->format = bestSinkConfig.format;
1724 // Copy input stream directly without any processing (e.g. resampling).
1725 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1726 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1727 if (hwAvSync) {
1728 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1729 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1730 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1731 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1732 }
1733 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1734 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1735 sinkConfig->config_mask |= config_mask;
1736 sourceConfig->config_mask |= config_mask;
1737 return NO_ERROR;
1738}
1739
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001740PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1741 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742{
1743 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001744 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1745 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1746 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1747 if (deviceModule == nullptr) {
1748 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1749 return patchBuilder;
1750 }
1751 const InputProfileCollection inputProfiles = msdIsSource ?
1752 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1753 const OutputProfileCollection outputProfiles = msdIsSource ?
1754 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1755
1756 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1757 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1758 device : getMsdAudioOutDevices().itemAt(0);
1759 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1760
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001761 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1762 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001763 AudioProfileVector sourceProfiles;
1764 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001765 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1766 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001767 for (auto hwAvSync : { true, false }) {
1768 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1769 sourceProfiles, sinkProfiles) != NO_ERROR) {
1770 continue;
1771 }
1772 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1773 &sinkConfig) == NO_ERROR) {
1774 // Found a matching config. Re-create PatchBuilder with this config.
1775 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1776 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001777 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001778 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001779 " supporting PCM format conversion.", __func__);
1780 return patchBuilder;
1781}
1782
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001783status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001784 DeviceVector devices;
1785 if (outputDevices != nullptr && outputDevices->size() > 0) {
1786 devices.add(*outputDevices);
1787 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001788 // Use media strategy for unspecified output device. This should only
1789 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1790 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001791 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001792 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001793 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001794 }
Michael Chan6fb34492020-12-08 15:44:49 +11001795 std::vector<PatchBuilder> patchesToCreate;
1796 for (auto i = 0u; i < devices.size(); ++i) {
1797 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001798 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001799 }
1800 // Retain only the MSD patches associated with outputDevices request.
1801 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001802 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001803 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1804 auto retainedPatch = false;
1805 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1806 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1807 patchesToRemove.removeItemsAt(i);
1808 retainedPatch = true;
1809 break;
1810 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001811 }
Michael Chan6fb34492020-12-08 15:44:49 +11001812 if (retainedPatch) {
1813 it = patchesToCreate.erase(it);
1814 continue;
1815 }
1816 ++it;
1817 }
1818 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1819 return NO_ERROR;
1820 }
1821 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1822 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001823 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001824 }
Michael Chan6fb34492020-12-08 15:44:49 +11001825 status_t status = NO_ERROR;
1826 for (const auto &p : patchesToCreate) {
1827 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1828 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1829 char message[256];
1830 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1831 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1832 currStatus == NO_ERROR ? "Success" : "Error",
1833 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1834 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1835 if (currStatus == NO_ERROR) {
1836 ALOGD("%s", message);
1837 } else {
1838 ALOGE("%s", message);
1839 if (status == NO_ERROR) {
1840 status = currStatus;
1841 }
1842 }
1843 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001844 return status;
1845}
1846
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001847void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1848 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001849 for (size_t i = 0; i < msdPatches.size(); i++) {
1850 const auto& patch = msdPatches[i];
1851 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1852 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1853 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1854 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1855 releaseAudioPatch(patch->getHandle(), mUidCached);
1856 break;
1857 }
1858 }
1859 }
1860}
1861
Dorin Drimus94d94412022-02-02 09:05:02 +01001862bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1863 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1864 AudioPatchCollection msdPatches = getMsdOutputPatches();
1865 for (size_t i = 0; i < msdPatches.size(); i++) {
1866 const auto& patch = msdPatches[i];
1867 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1868 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1869 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1870 const auto& foundDevice = devicesToCheck.getDevice(
1871 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1872 if (foundDevice != nullptr) {
1873 devicesToCheck.remove(foundDevice);
1874 if (devicesToCheck.isEmpty()) {
1875 return true;
1876 }
1877 }
1878 }
1879 }
1880 }
1881 return false;
1882}
1883
Eric Laurente0720872014-03-11 09:30:41 -07001884audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001885 audio_output_flags_t flags,
1886 audio_format_t format,
1887 audio_channel_mask_t channelMask,
1888 uint32_t samplingRate,
1889 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001890{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001891 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1892 "%s called with format %#x", __func__, format);
1893
jiabinebb6af42020-06-09 17:31:17 -07001894 // Return the output that haptic-generating attached to when 1) session id is specified,
1895 // 2) haptic-generating effect exists for given session id and 3) the output that
1896 // haptic-generating effect attached to is in given outputs.
1897 if (sessionId != AUDIO_SESSION_NONE) {
1898 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1899 sessionId, FX_IID_HAPTICGENERATOR);
1900 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1901 return hapticGeneratingOutput;
1902 }
1903 }
1904
Eric Laurent16c66dd2019-05-01 17:54:10 -07001905 // Flags disqualifying an output: the match must happen before calling selectOutput()
1906 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1907 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1908
1909 // Flags expressing a functional request: must be honored in priority over
1910 // other criteria
1911 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1912 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001913 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1914 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001915 // Flags expressing a performance request: have lower priority than serving
1916 // requested sampling rate or channel mask
1917 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1918 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1919 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1920
1921 const audio_output_flags_t functionalFlags =
1922 (audio_output_flags_t)(flags & kFunctionalFlags);
1923 const audio_output_flags_t performanceFlags =
1924 (audio_output_flags_t)(flags & kPerformanceFlags);
1925
1926 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1927
Eric Laurente552edb2014-03-10 17:42:56 -07001928 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001929 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001930 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001931 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001932 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001933 // with tiebreak preferring the minimum number of extra functional flags
1934 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001935 // 3: the output supporting the exact channel mask
1936 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001937 // 5: the output with the highest sampling rate if the requested sample rate is
1938 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001939 // 6: the output with the highest number of requested performance flags
1940 // 7: the output with the bit depth the closest to the requested one
1941 // 8: the primary output
1942 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001943
Eric Laurent16c66dd2019-05-01 17:54:10 -07001944 // matching criteria values in priority order for best matching output so far
1945 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001946
Eric Laurent16c66dd2019-05-01 17:54:10 -07001947 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1948 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1949 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001950
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001951 for (audio_io_handle_t output : outputs) {
1952 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953 // matching criteria values in priority order for current output
1954 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001955
Eric Laurent16c66dd2019-05-01 17:54:10 -07001956 if (outputDesc->isDuplicated()) {
1957 continue;
1958 }
1959 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1960 continue;
1961 }
Eric Laurent8838a382014-09-08 16:44:28 -07001962
Eric Laurent16c66dd2019-05-01 17:54:10 -07001963 // If haptic channel is specified, use the haptic output if present.
1964 // When using haptic output, same audio format and sample rate are required.
1965 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001966 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001967 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1968 continue;
1969 }
1970 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001971 && format == outputDesc->getFormat()
1972 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001973 currentMatchCriteria[0] = outputHapticChannelCount;
1974 }
1975
1976 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001977 const int matchingFunctionalFlags =
1978 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1979 const int totalFunctionalFlags =
1980 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1981 // Prefer matching functional flags, but subtract unnecessary functional flags.
1982 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001983
1984 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001985 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1986 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001987 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1988 channelCount <= outputChannelCount) {
1989 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001990 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1991 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001992 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001993 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001994 currentMatchCriteria[3] = outputChannelCount;
1995 }
1996
1997 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00001998 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001999 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002000 }
2001
2002 // performance flags match
2003 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2004
2005 // format match
2006 if (format != AUDIO_FORMAT_INVALID) {
2007 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002008 PolicyAudioPort::kFormatDistanceMax -
2009 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002010 }
2011
2012 // primary output match
2013 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2014
2015 // compare match criteria by priority then value
2016 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2017 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2018 bestMatchCriteria = currentMatchCriteria;
2019 bestOutput = output;
2020
2021 std::stringstream result;
2022 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2023 std::ostream_iterator<int>(result, " "));
2024 ALOGV("%s new bestOutput %d criteria %s",
2025 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002026 }
2027 }
2028
Eric Laurent16c66dd2019-05-01 17:54:10 -07002029 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002030}
2031
Eric Laurent8fc147b2018-07-22 19:13:55 -07002032status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002033{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002034 ALOGV("%s portId %d", __FUNCTION__, portId);
2035
2036 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2037 if (outputDesc == 0) {
2038 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002039 return BAD_VALUE;
2040 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002041 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002042
Eric Laurent8fc147b2018-07-22 19:13:55 -07002043 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002044 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002045
Eric Laurent733ce942017-12-07 12:18:25 -08002046 status_t status = outputDesc->start();
2047 if (status != NO_ERROR) {
2048 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002049 }
2050
Eric Laurent97ac8712018-07-27 18:59:02 -07002051 uint32_t delayMs;
2052 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002053
2054 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002055 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002056 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002057 }
jiabina84c3d32022-12-02 18:59:55 +00002058
2059 // If the client is the first one active on preferred mixer parameters, reopen the output
2060 // if the current mixer parameters doesn't match the preferred one.
2061 if (outputDesc->devices().size() == 1) {
2062 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2063 outputDesc->devices()[0]->getId(), client->strategy());
2064 if (info != nullptr && info->getUid() == client->uid()) {
2065 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2066 info->getConfigBase(), info->getFlags())) {
2067 stopSource(outputDesc, client);
2068 outputDesc->stop();
2069 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2070 config.channel_mask = info->getConfigBase().channel_mask;
2071 config.sample_rate = info->getConfigBase().sample_rate;
2072 config.format = info->getConfigBase().format;
2073 status_t status = reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2074 if (status != NO_ERROR) {
2075 return status;
2076 }
2077 // Intentionally return error to let the client side resending request for
2078 // creating and starting.
2079 return DEAD_OBJECT;
2080 }
2081 info->increaseActiveClient();
2082 }
2083 }
2084
Eric Laurentc75307b2015-03-17 15:29:32 -07002085 if (delayMs != 0) {
2086 usleep(delayMs * 1000);
2087 }
2088
2089 return status;
2090}
2091
Eric Laurent96d1dda2022-03-14 17:14:19 +01002092bool AudioPolicyManager::isLeUnicastActive() const {
2093 if (isInCall()) {
2094 return true;
2095 }
2096 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2097}
2098
2099bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2100 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2101 return false;
2102 }
2103 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2104 ALOGV("%s active %d", __func__, active);
2105 return active;
2106}
2107
Eric Laurent97ac8712018-07-27 18:59:02 -07002108status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2109 const sp<TrackClientDescriptor>& client,
2110 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002111{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002112 // cannot start playback of STREAM_TTS if any other output is being used
2113 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002114
2115 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002116 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002117 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002118 auto clientStrategy = client->strategy();
2119 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002120 if (stream == AUDIO_STREAM_TTS) {
2121 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002122 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002123 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002124 return INVALID_OPERATION;
2125 } else {
2126 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2127 }
2128 } else {
2129 // some playback other than beacon starts
2130 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2131 }
2132
Eric Laurent77305a62016-07-25 16:39:22 -07002133 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002134 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002135 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002136
François Gaffie11d30102018-11-02 16:09:09 +01002137 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002138 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002139 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002140 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002141 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002142 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002143 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002144 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002145 } else {
2146 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002147 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002148 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2149 AUDIO_FORMAT_DEFAULT);
2150 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2151 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002152 }
2153
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002154 // requiresMuteCheck is false when we can bypass mute strategy.
2155 // It covers a common case when there is no materially active audio
2156 // and muting would result in unnecessary delay and dropped audio.
2157 const uint32_t outputLatencyMs = outputDesc->latency();
2158 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002159 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002160
Eric Laurente552edb2014-03-10 17:42:56 -07002161 // increment usage count for this stream on the requested output:
2162 // NOTE that the usage count is the same for duplicated output and hardware output which is
2163 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002164 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002165
2166 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002167 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2168 client->isPreferredDeviceForExclusiveUse()) {
2169 // Preferred device may be exclusive, use only if no other active clients on this output
2170 devices = DeviceVector(
2171 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2172 } else {
2173 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2174 }
François Gaffie11d30102018-11-02 16:09:09 +01002175 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002176 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002177 }
2178 }
Eric Laurente552edb2014-03-10 17:42:56 -07002179
François Gaffiec005e562018-11-06 15:04:49 +01002180 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002181 selectOutputForMusicEffects();
2182 }
2183
François Gaffie1c878552018-11-22 16:53:21 +01002184 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002185 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002186 if (devices.isEmpty()) {
2187 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002188 }
François Gaffiec005e562018-11-06 15:04:49 +01002189 bool shouldWait =
2190 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2191 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2192 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002193 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002194 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002195 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002196 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002197 // An output has a shared device if
2198 // - managed by the same hw module
2199 // - supports the currently selected device
2200 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002201 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002202
Eric Laurent77305a62016-07-25 16:39:22 -07002203 // force a device change if any other output is:
2204 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002205 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002206 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002207 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002208 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002209 // change the device currently selected by the other output.
2210 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002211 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002212 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002213 force = true;
2214 }
2215 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002216 // a notification so that audio focus effect can propagate, or that a mute/unmute
2217 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002218 const uint32_t latencyMs = desc->latency();
2219 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2220
2221 if (shouldWait && isActive && (waitMs < latencyMs)) {
2222 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002223 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002224
2225 // Require mute check if another output is on a shared device
2226 // and currently active to have proper drain and avoid pops.
2227 // Note restoring AudioTracks onto this output needs to invoke
2228 // a volume ramp if there is no mute.
2229 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002230 }
2231 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002232
2233 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002234 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002235
Eric Laurente552edb2014-03-10 17:42:56 -07002236 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002237 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002238 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002239 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002240 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002241 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002242 outputDesc->useHwGain() /*force*/)) {
2243 // request AudioService to reinitialize the volume curves asynchronously
2244 ALOGE("checkAndSetVolume failed, requesting volume range init");
2245 mpClientInterface->onVolumeRangeInitRequest();
2246 };
Eric Laurente552edb2014-03-10 17:42:56 -07002247
2248 // update the outputs if starting an output with a stream that can affect notification
2249 // routing
2250 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002251
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002252 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002253 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002254 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2255 }
Eric Laurentdc462862016-07-19 12:29:53 -07002256
2257 if (waitMs > muteWaitMs) {
2258 *delayMs = waitMs - muteWaitMs;
2259 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002260
2261 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2262 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2263 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2264 // change occurs after the MixerThread starts and causes a stream volume
2265 // glitch.
2266 //
2267 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002268 }
Eric Laurentdc462862016-07-19 12:29:53 -07002269
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002270 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002271 mEngine->getForceUse(
2272 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002273 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002274 }
2275
Eric Laurent97ac8712018-07-27 18:59:02 -07002276 // Automatically enable the remote submix input when output is started on a re routing mix
2277 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002278 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2279 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002280 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2281 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2282 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002283 "remote-submix",
2284 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002285 }
2286
Eric Laurent96d1dda2022-03-14 17:14:19 +01002287 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2288
Eric Laurente552edb2014-03-10 17:42:56 -07002289 return NO_ERROR;
2290}
2291
Eric Laurent96d1dda2022-03-14 17:14:19 +01002292void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2293 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2294 bool isUnicastActive = isLeUnicastActive();
2295
2296 if (wasUnicastActive != isUnicastActive) {
2297 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2298 for (size_t i = 0; i < mOutputs.size(); i++) {
2299 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2300 if (desc != ignoredOutput && desc->isActive()
2301 && ((isUnicastActive &&
2302 !desc->devices().
2303 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2304 || (wasUnicastActive &&
2305 !desc->devices().getDevicesFromTypes(
2306 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2307 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2308 bool force = desc->devices() != newDevices;
2309 setOutputDevices(desc, newDevices, force, delayMs);
2310 // re-apply device specific volume if not done by setOutputDevice()
2311 if (!force) {
2312 applyStreamVolumes(desc, newDevices.types(), delayMs);
2313 }
2314 }
2315 }
2316 }
2317}
2318
Eric Laurent8fc147b2018-07-22 19:13:55 -07002319status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002320{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002321 ALOGV("%s portId %d", __FUNCTION__, portId);
2322
2323 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2324 if (outputDesc == 0) {
2325 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002326 return BAD_VALUE;
2327 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002328 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002329
Eric Laurent97ac8712018-07-27 18:59:02 -07002330 ALOGV("stopOutput() output %d, stream %d, session %d",
2331 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002332
Eric Laurent97ac8712018-07-27 18:59:02 -07002333 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002334
Eric Laurent733ce942017-12-07 12:18:25 -08002335 if (status == NO_ERROR ) {
2336 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002337 } else {
2338 return status;
2339 }
2340
2341 if (outputDesc->devices().size() == 1) {
2342 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2343 outputDesc->devices()[0]->getId(), client->strategy());
2344 if (info != nullptr && info->getUid() == client->uid()) {
2345 info->decreaseActiveClient();
2346 if (info->getActiveClientCount() == 0) {
2347 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2348 }
2349 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002350 }
2351 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002352}
2353
Eric Laurent97ac8712018-07-27 18:59:02 -07002354status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2355 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002356{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002357 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002358 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002359 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002360 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002361
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002362 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2363
François Gaffie1c878552018-11-22 16:53:21 +01002364 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2365 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002366 // Automatically disable the remote submix input when output is stopped on a
2367 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002368 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002369 if (isSingleDeviceType(
2370 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002371 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002372 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002373 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2374 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002375 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002376 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002377 }
2378 }
2379 bool forceDeviceUpdate = false;
2380 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002381 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002382 forceDeviceUpdate = true;
2383 }
2384
Eric Laurente552edb2014-03-10 17:42:56 -07002385 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002386 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002387
Eric Laurente552edb2014-03-10 17:42:56 -07002388 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002389 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002390 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002391 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002392
2393 // If the routing does not change, if an output is routed on a device using HwGain
2394 // (aka setAudioPortConfig) and there are still active clients following different
2395 // volume group(s), force reapply volume
2396 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2397 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2398
Eric Laurente552edb2014-03-10 17:42:56 -07002399 // delay the device switch by twice the latency because stopOutput() is executed when
2400 // the track stop() command is received and at that time the audio track buffer can
2401 // still contain data that needs to be drained. The latency only covers the audio HAL
2402 // and kernel buffers. Also the latency does not always include additional delay in the
2403 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002404 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2405 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002406
2407 // force restoring the device selection on other active outputs if it differs from the
2408 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002409 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002410 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002411 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002412 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002413 desc->isActive() &&
2414 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002415 (newDevices != desc->devices())) {
2416 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2417 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002418
François Gaffie11d30102018-11-02 16:09:09 +01002419 setOutputDevices(desc, newDevices2, force, delayMs);
2420
Eric Laurent57de36c2016-09-28 16:59:11 -07002421 // re-apply device specific volume if not done by setOutputDevice()
2422 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002423 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002424 }
Eric Laurente552edb2014-03-10 17:42:56 -07002425 }
2426 }
2427 // update the outputs if stopping one with a stream that can affect notification routing
2428 handleNotificationRoutingForStream(stream);
2429 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002430
2431 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2432 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002433 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002434 }
2435
François Gaffiec005e562018-11-06 15:04:49 +01002436 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002437 selectOutputForMusicEffects();
2438 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002439
2440 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2441
Eric Laurente552edb2014-03-10 17:42:56 -07002442 return NO_ERROR;
2443 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002444 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002445 return INVALID_OPERATION;
2446 }
2447}
2448
jiabinbce0c1d2020-10-05 11:20:18 -07002449bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002450{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002451 ALOGV("%s portId %d", __FUNCTION__, portId);
2452
2453 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2454 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002455 // If an output descriptor is closed due to a device routing change,
2456 // then there are race conditions with releaseOutput from tracks
2457 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2458 // destroyed shortly thereafter.
2459 //
2460 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002461 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002462 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002463 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002464
2465 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002466
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302467 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2468 if (outputDesc->isClientActive(client)) {
2469 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2470 stopOutput(portId);
2471 }
2472
Eric Laurent8fc147b2018-07-22 19:13:55 -07002473 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2474 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002475 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002476 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002477 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002478 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002479 if (--outputDesc->mDirectOpenCount == 0) {
2480 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002481 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002482 }
2483 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302484
Andy Hung39efb7a2018-09-26 15:39:28 -07002485 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002486 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2487 // The output is pending reopened to query dynamic profiles and
2488 // there is no active clients
2489 closeOutput(outputDesc->mIoHandle);
2490 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2491 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2492 if (newOutputDesc == nullptr) {
2493 ALOGE("%s failed to open output", __func__);
2494 }
2495 return true;
2496 }
2497 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002498}
2499
Eric Laurentcaf7f482014-11-25 17:50:47 -08002500status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2501 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002502 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002503 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002504 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002505 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002506 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002507 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002508 input_type_t *inputType,
2509 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002510{
François Gaffiec005e562018-11-06 15:04:49 +01002511 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002512 "flags %#x attributes=%s requested device ID %d",
2513 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2514 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002515
Eric Laurentad2e7b92017-09-14 20:06:42 -07002516 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002517 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002518 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002519 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002520 sp<AudioInputDescriptor> inputDesc;
2521 sp<RecordClientDescriptor> clientDesc;
2522 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002523 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002524 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002525
2526 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2527 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2528 return INVALID_OPERATION;
2529 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002530
Francois Gaffie716e1432019-01-14 16:58:59 +01002531 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2532 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002533 }
2534
Paul McLean466dc8e2015-04-17 13:15:36 -06002535 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002536 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002537 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002538
Eric Laurentad2e7b92017-09-14 20:06:42 -07002539 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2540 // possible
2541 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2542 *input != AUDIO_IO_HANDLE_NONE) {
2543 ssize_t index = mInputs.indexOfKey(*input);
2544 if (index < 0) {
2545 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2546 status = BAD_VALUE;
2547 goto error;
2548 }
2549 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002550 RecordClientVector clients = inputDesc->getClientsForSession(session);
2551 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002552 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2553 status = BAD_VALUE;
2554 goto error;
2555 }
2556 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2557 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002558 // corresponds to a new client and is only permitted from the same UID.
2559 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002560 if (clients.size() > 1) {
2561 for (const auto& client : clients) {
2562 // The client map is ordered by key values (portId) and portIds are allocated
2563 // incrementaly. So the first client in this list is the one opened by audio flinger
2564 // when the mmap stream is created and should be ignored as it does not correspond
2565 // to an actual client
2566 if (client == *clients.cbegin()) {
2567 continue;
2568 }
2569 if (uid != client->uid() && !client->isSilenced()) {
2570 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2571 uid, client->portId(), client->uid());
2572 status = INVALID_OPERATION;
2573 goto error;
2574 }
Eric Laurent331679c2018-04-16 17:03:16 -07002575 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002576 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002577 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002578 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002579
Eric Laurentfecbceb2021-02-09 14:46:43 +01002580 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002581 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002582 }
2583
2584 *input = AUDIO_IO_HANDLE_NONE;
2585 *inputType = API_INPUT_INVALID;
2586
Francois Gaffie716e1432019-01-14 16:58:59 +01002587 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002588 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002589 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002590 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002591 ALOGW("%s could not find input mix for attr %s",
2592 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002593 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002594 }
jiabinc1de2df2019-05-07 14:26:40 -07002595 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2596 String8(attr->tags + strlen("addr=")),
2597 AUDIO_FORMAT_DEFAULT);
2598 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002599 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002600 __func__, attributes.source, attributes.tags);
2601 status = BAD_VALUE;
2602 goto error;
2603 }
2604
Kevin Rocard25f9b052019-02-27 15:08:54 -08002605 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2606 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2607 } else {
2608 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2609 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002610 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002611 if (explicitRoutingDevice != nullptr) {
2612 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002613 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002614 // Prevent from storing invalid requested device id in clients
2615 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002616 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002617 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2618 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002619 }
François Gaffie11d30102018-11-02 16:09:09 +01002620 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002621 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002622 status = BAD_VALUE;
2623 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002624 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002625 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2626 *inputType = API_INPUT_MIX_CAPTURE;
2627 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002628 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2629 // there is an external policy, but this input is attached to a mix of recorders,
2630 // meaning it receives audio injected into the framework, so the recorder doesn't
2631 // know about it and is therefore considered "legacy"
2632 *inputType = API_INPUT_LEGACY;
2633 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002634 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002635 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002636 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002637 } else {
2638 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002639 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002640
Eric Laurent599c7582015-12-07 18:05:55 -08002641 }
2642
François Gaffiec005e562018-11-06 15:04:49 +01002643 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002644 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002645 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002646 AudioProfileVector profiles;
2647 status_t ret = getProfilesForDevices(
2648 DeviceVector(device), profiles, flags, true /*isInput*/);
2649 if (ret == NO_ERROR && !profiles.empty()) {
2650 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2651 : *profiles[0]->getChannels().begin();
2652 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2653 : *profiles[0]->getSampleRates().begin();
2654 config->format = profiles[0]->getFormat();
2655 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002656 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002657 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002658
Eric Laurent8f42ea12018-08-08 09:08:25 -07002659exit:
2660
François Gaffiec005e562018-11-06 15:04:49 +01002661 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2662 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002663
Francois Gaffie716e1432019-01-14 16:58:59 +01002664 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002665 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002666 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002667
Mikhail Naganov2996f672019-04-18 12:29:59 -07002668 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002669 requestedDeviceId, attributes.source, flags,
2670 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002671 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002672 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002673
2674 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2675 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002676
Eric Laurent599c7582015-12-07 18:05:55 -08002677 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002678
2679error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002680 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002681}
2682
2683
François Gaffie11d30102018-11-02 16:09:09 +01002684audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002685 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002686 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002687 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002688 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002689 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002690{
2691 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002692 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002693 bool isSoundTrigger = false;
2694
François Gaffiec005e562018-11-06 15:04:49 +01002695 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002696 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2697 if (index >= 0) {
2698 input = mSoundTriggerSessions.valueFor(session);
2699 isSoundTrigger = true;
2700 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2701 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2702 } else {
2703 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002704 }
François Gaffiec005e562018-11-06 15:04:49 +01002705 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002706 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002707 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002708 }
2709
Carter Hsua3abb402021-10-26 11:11:20 +08002710 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2711 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2712 }
2713
Eric Laurentfe231122017-11-17 17:48:06 -08002714 // sampling rate and flags may be updated by getInputProfile
2715 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2716 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002717 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002718 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002719 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002720 // find a compatible input profile (not necessarily identical in parameters)
2721 sp<IOProfile> profile = getInputProfile(
2722 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2723 if (profile == nullptr) {
2724 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002725 }
jiabin2fd710d2022-05-02 23:20:22 +00002726
Glenn Kasten05ddca52016-02-11 08:17:12 -08002727 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002728 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002729 if (samplingRate == 0) {
2730 samplingRate = profileSamplingRate;
2731 }
Eric Laurente552edb2014-03-10 17:42:56 -07002732
Eric Laurent322b4d22015-04-03 15:57:54 -07002733 if (profile->getModuleHandle() == 0) {
2734 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002735 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002736 }
2737
Eric Laurentec376dc2021-04-08 20:41:22 +02002738 // Reuse an already opened input if a client with the same session ID already exists
2739 // on that input
2740 for (size_t i = 0; i < mInputs.size(); i++) {
2741 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2742 if (desc->mProfile != profile) {
2743 continue;
2744 }
2745 RecordClientVector clients = desc->clientsList();
2746 for (const auto &client : clients) {
2747 if (session == client->session()) {
2748 return desc->mIoHandle;
2749 }
2750 }
2751 }
2752
Eric Laurent3974e3b2017-12-07 17:58:43 -08002753 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002754 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002755 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002756 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002757 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002758 continue;
2759 }
2760 // if sound trigger, reuse input if used by other sound trigger on same session
2761 // else
2762 // reuse input if active client app is not in IDLE state
2763 //
2764 RecordClientVector clients = desc->clientsList();
2765 bool doClose = false;
2766 for (const auto& client : clients) {
2767 if (isSoundTrigger != client->isSoundTrigger()) {
2768 continue;
2769 }
2770 if (client->isSoundTrigger()) {
2771 if (session == client->session()) {
2772 return desc->mIoHandle;
2773 }
2774 continue;
2775 }
2776 if (client->active() && client->appState() != APP_STATE_IDLE) {
2777 return desc->mIoHandle;
2778 }
2779 doClose = true;
2780 }
2781 if (doClose) {
2782 closeInput(desc->mIoHandle);
2783 } else {
2784 i++;
2785 }
2786 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002787 }
2788
Eric Laurentfe231122017-11-17 17:48:06 -08002789 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002790
Eric Laurentfe231122017-11-17 17:48:06 -08002791 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2792 lConfig.sample_rate = profileSamplingRate;
2793 lConfig.channel_mask = profileChannelMask;
2794 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002795
François Gaffie11d30102018-11-02 16:09:09 +01002796 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002797
2798 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002799 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002800 (profileSamplingRate != lConfig.sample_rate) ||
2801 !audio_formats_match(profileFormat, lConfig.format) ||
2802 (profileChannelMask != lConfig.channel_mask)) {
2803 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002804 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002805 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002806 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002807 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002808 }
Eric Laurent599c7582015-12-07 18:05:55 -08002809 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002810 }
2811
Eric Laurentc722f302014-12-10 11:21:49 -08002812 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002813
Eric Laurent599c7582015-12-07 18:05:55 -08002814 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002815 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002816
Eric Laurent599c7582015-12-07 18:05:55 -08002817 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002818}
2819
Eric Laurent4eb58f12018-12-07 16:41:02 -08002820status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002821{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002822 ALOGV("%s portId %d", __FUNCTION__, portId);
2823
2824 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2825 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002826 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002827 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002828 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002829 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002830 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002831 if (client->active()) {
2832 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2833 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002834 }
2835
Eric Laurent8f42ea12018-08-08 09:08:25 -07002836 audio_session_t session = client->session();
2837
Eric Laurent4eb58f12018-12-07 16:41:02 -08002838 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002839
Eric Laurent4eb58f12018-12-07 16:41:02 -08002840 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002841
Eric Laurent4eb58f12018-12-07 16:41:02 -08002842 status_t status = inputDesc->start();
2843 if (status != NO_ERROR) {
2844 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002845 }
Eric Laurente552edb2014-03-10 17:42:56 -07002846
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002847 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002848 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002849 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002850
Eric Laurent8f42ea12018-08-08 09:08:25 -07002851 // indicate active capture to sound trigger service if starting capture from a mic on
2852 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002853 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002854 if (device != nullptr) {
2855 status = setInputDevice(input, device, true /* force */);
2856 } else {
2857 ALOGW("%s no new input device can be found for descriptor %d",
2858 __FUNCTION__, inputDesc->getId());
2859 status = BAD_VALUE;
2860 }
Eric Laurente552edb2014-03-10 17:42:56 -07002861
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002862 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002863 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002864 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002865 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002866 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2867 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002868 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002869 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002870
François Gaffie11d30102018-11-02 16:09:09 +01002871 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2872 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002873 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002874 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002875 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002876
Eric Laurent8f42ea12018-08-08 09:08:25 -07002877 // automatically enable the remote submix output when input is started if not
2878 // used by a policy mix of type MIX_TYPE_RECORDERS
2879 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002880 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002881 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002882 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002883 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002884 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2885 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002886 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002887 if (address != "") {
2888 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2889 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002890 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002891 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002892 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002893 } else if (status != NO_ERROR) {
2894 // Restore client activity state.
2895 inputDesc->setClientActive(client, false);
2896 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002897 }
2898
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002899 ALOGV("%s input %d source = %d status = %d exit",
2900 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002901
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002902 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002903}
2904
Eric Laurent8fc147b2018-07-22 19:13:55 -07002905status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002906{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002907 ALOGV("%s portId %d", __FUNCTION__, portId);
2908
2909 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2910 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002911 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002912 return BAD_VALUE;
2913 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002914 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002915 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002916 if (!client->active()) {
2917 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002918 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002919 }
Carter Hsue6139d52021-07-08 10:30:20 +08002920 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002921 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002922
Eric Laurent8f42ea12018-08-08 09:08:25 -07002923 inputDesc->stop();
2924 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002925 auto current_source = inputDesc->source();
2926 setInputDevice(input, getNewInputDevice(inputDesc),
2927 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002928 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002929 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002930 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002931 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002932 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2933 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002934 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002935 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002936
2937 // automatically disable the remote submix output when input is stopped if not
2938 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002939 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002940 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002941 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002942 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002943 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2944 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002945 }
2946 if (address != "") {
2947 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2948 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002949 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002950 }
2951 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002952 resetInputDevice(input);
2953
2954 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2955 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002956 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2957 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002958 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002959 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002960 }
2961 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002962 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002963 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002964}
2965
Eric Laurent8fc147b2018-07-22 19:13:55 -07002966void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002967{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002968 ALOGV("%s portId %d", __FUNCTION__, portId);
2969
2970 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2971 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002972 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002973 return;
2974 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002975 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002976 audio_io_handle_t input = inputDesc->mIoHandle;
2977
Eric Laurent8f42ea12018-08-08 09:08:25 -07002978 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002979
Andy Hung39efb7a2018-09-26 15:39:28 -07002980 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002981
Andy Hung39efb7a2018-09-26 15:39:28 -07002982 if (inputDesc->getClientCount() > 0) {
2983 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002984 return;
2985 }
2986
Eric Laurent05b90f82014-08-27 15:32:29 -07002987 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002988 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002989 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002990}
2991
Eric Laurent8f42ea12018-08-08 09:08:25 -07002992void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002993{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002994 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002995
2996 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002997 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002998 }
2999}
3000
Eric Laurent8f42ea12018-08-08 09:08:25 -07003001void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3002{
3003 stopInput(portId);
3004 releaseInput(portId);
3005}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003006
Eric Laurent0dd51852019-04-19 18:18:58 -07003007void AudioPolicyManager::checkCloseInputs() {
3008 // After connecting or disconnecting an input device, close input if:
3009 // - it has no client (was just opened to check profile) OR
3010 // - none of its supported devices are connected anymore OR
3011 // - one of its clients cannot be routed to one of its supported
3012 // devices anymore. Otherwise update device selection
3013 std::vector<audio_io_handle_t> inputsToClose;
3014 for (size_t i = 0; i < mInputs.size(); i++) {
3015 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3016 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003017 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003018 inputsToClose.push_back(mInputs.keyAt(i));
3019 } else {
3020 bool close = false;
3021 for (const auto& client : input->clientsList()) {
3022 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003023 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3024 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003025 if (!input->supportedDevices().contains(device)) {
3026 close = true;
3027 break;
3028 }
3029 }
3030 if (close) {
3031 inputsToClose.push_back(mInputs.keyAt(i));
3032 } else {
3033 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3034 }
3035 }
3036 }
3037
3038 for (const audio_io_handle_t handle : inputsToClose) {
3039 ALOGV("%s closing input %d", __func__, handle);
3040 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003041 }
Eric Laurentd4692962014-05-05 18:13:44 -07003042}
3043
François Gaffie251c7f02018-11-07 10:41:08 +01003044void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003045{
3046 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003047 if (indexMin < 0 || indexMax < 0) {
3048 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3049 return;
3050 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003051 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003052
3053 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003054 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3055 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003056 continue;
3057 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003058 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003059 }
Eric Laurente552edb2014-03-10 17:42:56 -07003060}
3061
Eric Laurente0720872014-03-11 09:30:41 -07003062status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003063 int index,
3064 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003065{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003066 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003067 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3068 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3069 return NO_ERROR;
3070 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003071 ALOGV("%s: stream %s attributes=%s", __func__,
3072 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003073 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003074}
3075
Eric Laurente0720872014-03-11 09:30:41 -07003076status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003077 int *index,
3078 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003079{
François Gaffiec005e562018-11-06 15:04:49 +01003080 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3081 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003082 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003083 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003084 deviceTypes = mEngine->getOutputDevicesForStream(
3085 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003086 }
jiabin9a3361e2019-10-01 09:38:30 -07003087 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003088}
3089
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003090status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003091 int index,
3092 audio_devices_t device)
3093{
3094 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003095 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3096 if (group == VOLUME_GROUP_NONE) {
3097 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003098 return BAD_VALUE;
3099 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003100 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003101 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003102 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003103 VolumeSource vs = toVolumeSource(group);
3104 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3105
3106 status = setVolumeCurveIndex(index, device, curves);
3107 if (status != NO_ERROR) {
3108 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3109 return status;
3110 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003111
jiabin9a3361e2019-10-01 09:38:30 -07003112 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003113 auto curCurvAttrs = curves.getAttributes();
3114 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3115 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003116 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003117 } else if (!curves.getStreamTypes().empty()) {
3118 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003119 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003120 } else {
3121 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3122 return BAD_VALUE;
3123 }
jiabin9a3361e2019-10-01 09:38:30 -07003124 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3125 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003126
François Gaffiecfe17322018-11-07 13:41:29 +01003127 // update volume on all outputs and streams matching the following:
3128 // - The requested stream (or a stream matching for volume control) is active on the output
3129 // - The device (or devices) selected by the engine for this stream includes
3130 // the requested device
3131 // - For non default requested device, currently selected device on the output is either the
3132 // requested device or one of the devices selected by the engine for this stream
3133 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3134 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003135 for (size_t i = 0; i < mOutputs.size(); i++) {
3136 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003137 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003138
jiabin9a3361e2019-10-01 09:38:30 -07003139 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3140 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003141 }
François Gaffieed91f582020-01-31 10:35:37 +01003142 if (!(desc->isActive(vs) || isInCall())) {
3143 continue;
3144 }
3145 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3146 curDevices.find(device) == curDevices.end()) {
3147 continue;
3148 }
3149 bool applyVolume = false;
3150 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3151 curSrcDevices.insert(device);
3152 applyVolume = (curSrcDevices.find(
3153 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3154 } else {
3155 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3156 }
3157 if (!applyVolume) {
3158 continue; // next output
3159 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003160 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3161 // If a higher priority strategy is active, and the output is routed to a device with a
3162 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003163 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003164 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003165 // If the volume source is active with higher priority source, ensure at least Sw Muted
3166 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003167 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3168 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3169 false /*preferredDevice*/);
3170 if (activeClients.empty()) {
3171 continue;
3172 }
3173 bool isPreempted = false;
3174 bool isHigherPriority = productStrategy < strategy;
3175 for (const auto &client : activeClients) {
3176 if (isHigherPriority && (client->volumeSource() != vs)) {
3177 ALOGV("%s: Strategy=%d (\nrequester:\n"
3178 " group %d, volumeGroup=%d attributes=%s)\n"
3179 " higher priority source active:\n"
3180 " volumeGroup=%d attributes=%s) \n"
3181 " on output %zu, bailing out", __func__, productStrategy,
3182 group, group, toString(attributes).c_str(),
3183 client->volumeSource(), toString(client->attributes()).c_str(), i);
3184 applyVolume = false;
3185 isPreempted = true;
3186 break;
3187 }
3188 // However, continue for loop to ensure no higher prio clients running on output
3189 if (client->volumeSource() == vs) {
3190 applyVolume = true;
3191 }
3192 }
3193 if (isPreempted || applyVolume) {
3194 break;
3195 }
3196 }
3197 if (!applyVolume) {
3198 continue; // next output
3199 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003200 }
François Gaffieed91f582020-01-31 10:35:37 +01003201 //FIXME: workaround for truncated touch sounds
3202 // delayed volume change for system stream to be removed when the problem is
3203 // handled by system UI
3204 status_t volStatus = checkAndSetVolume(
3205 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003206 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003207 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3208 if (volStatus != NO_ERROR) {
3209 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003210 }
3211 }
François Gaffiecfe17322018-11-07 13:41:29 +01003212 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3213 return status;
3214}
3215
François Gaffieaaac0fd2018-11-22 17:56:39 +01003216status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003217 audio_devices_t device,
3218 IVolumeCurves &volumeCurves)
3219{
3220 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3221 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003222 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3223 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003224 (index > volumeCurves.getVolumeIndexMax())) {
3225 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3226 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3227 return BAD_VALUE;
3228 }
3229 if (!audio_is_output_device(device)) {
3230 return BAD_VALUE;
3231 }
3232
3233 // Force max volume if stream cannot be muted
3234 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3235
François Gaffieaaac0fd2018-11-22 17:56:39 +01003236 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003237 volumeCurves.addCurrentVolumeIndex(device, index);
3238 return NO_ERROR;
3239}
3240
3241status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3242 int &index,
3243 audio_devices_t device)
3244{
3245 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3246 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003247 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003248 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003249 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003250 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003251 }
jiabin9a3361e2019-10-01 09:38:30 -07003252 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003253}
3254
3255status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3256 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003257 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003258{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003259 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003260 return BAD_VALUE;
3261 }
jiabin9a3361e2019-10-01 09:38:30 -07003262 index = curves.getVolumeIndex(deviceTypes);
3263 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003264 return NO_ERROR;
3265}
3266
3267status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3268 int &index)
3269{
3270 index = getVolumeCurves(attr).getVolumeIndexMin();
3271 return NO_ERROR;
3272}
3273
3274status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3275 int &index)
3276{
3277 index = getVolumeCurves(attr).getVolumeIndexMax();
3278 return NO_ERROR;
3279}
3280
Eric Laurent36829f92017-04-07 19:04:42 -07003281audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003282{
3283 // select one output among several suitable for global effects.
3284 // The priority is as follows:
3285 // 1: An offloaded output. If the effect ends up not being offloadable,
3286 // AudioFlinger will invalidate the track and the offloaded output
3287 // will be closed causing the effect to be moved to a PCM output.
3288 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003289 // 3: The primary output
3290 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003291
François Gaffiec005e562018-11-06 15:04:49 +01003292 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3293 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003294 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003295
Eric Laurent36829f92017-04-07 19:04:42 -07003296 if (outputs.size() == 0) {
3297 return AUDIO_IO_HANDLE_NONE;
3298 }
Eric Laurente552edb2014-03-10 17:42:56 -07003299
Eric Laurent36829f92017-04-07 19:04:42 -07003300 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3301 bool activeOnly = true;
3302
3303 while (output == AUDIO_IO_HANDLE_NONE) {
3304 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3305 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3306 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3307
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003308 for (audio_io_handle_t output : outputs) {
3309 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003310 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003311 continue;
3312 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003313 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3314 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003315 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003316 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003317 }
3318 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003319 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003320 }
3321 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003322 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003323 }
3324 }
3325 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3326 output = outputOffloaded;
3327 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3328 output = outputDeepBuffer;
3329 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3330 output = outputPrimary;
3331 } else {
3332 output = outputs[0];
3333 }
3334 activeOnly = false;
3335 }
3336
3337 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003338 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003339 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3340 mMusicEffectOutput = output;
3341 }
3342
3343 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003344 return output;
3345}
3346
Eric Laurent36829f92017-04-07 19:04:42 -07003347audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3348{
3349 return selectOutputForMusicEffects();
3350}
3351
Eric Laurente0720872014-03-11 09:30:41 -07003352status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003353 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003354 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003355 int session,
3356 int id)
3357{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003358 if (session != AUDIO_SESSION_DEVICE) {
3359 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003360 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003361 index = mInputs.indexOfKey(io);
3362 if (index < 0) {
3363 ALOGW("registerEffect() unknown io %d", io);
3364 return INVALID_OPERATION;
3365 }
Eric Laurente552edb2014-03-10 17:42:56 -07003366 }
3367 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003368 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3369 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3370 || strategy == PRODUCT_STRATEGY_NONE));
3371 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003372}
3373
Eric Laurentc241b0d2018-11-28 09:08:49 -08003374status_t AudioPolicyManager::unregisterEffect(int id)
3375{
3376 if (mEffects.getEffect(id) == nullptr) {
3377 return INVALID_OPERATION;
3378 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003379 if (mEffects.isEffectEnabled(id)) {
3380 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3381 setEffectEnabled(id, false);
3382 }
3383 return mEffects.unregisterEffect(id);
3384}
3385
3386status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3387{
3388 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3389 if (effect == nullptr) {
3390 return INVALID_OPERATION;
3391 }
3392
3393 status_t status = mEffects.setEffectEnabled(id, enabled);
3394 if (status == NO_ERROR) {
3395 mInputs.trackEffectEnabled(effect, enabled);
3396 }
3397 return status;
3398}
3399
Eric Laurent6c796322019-04-09 14:13:17 -07003400
3401status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3402{
3403 mEffects.moveEffects(ids, io);
3404 return NO_ERROR;
3405}
3406
Eric Laurentc75307b2015-03-17 15:29:32 -07003407bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3408{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003409 auto vs = toVolumeSource(stream, false);
3410 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003411}
3412
3413bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3414{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003415 auto vs = toVolumeSource(stream, false);
3416 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003417}
3418
Eric Laurente0720872014-03-11 09:30:41 -07003419bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003420{
3421 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003422 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003423 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003424 return true;
3425 }
3426 }
3427 return false;
3428}
3429
Eric Laurent275e8e92014-11-30 15:14:47 -08003430// Register a list of custom mixes with their attributes and format.
3431// When a mix is registered, corresponding input and output profiles are
3432// added to the remote submix hw module. The profile contains only the
3433// parameters (sampling rate, format...) specified by the mix.
3434// The corresponding input remote submix device is also connected.
3435//
3436// When a remote submix device is connected, the address is checked to select the
3437// appropriate profile and the corresponding input or output stream is opened.
3438//
3439// When capture starts, getInputForAttr() will:
3440// - 1 look for a mix matching the address passed in attribtutes tags if any
3441// - 2 if none found, getDeviceForInputSource() will:
3442// - 2.1 look for a mix matching the attributes source
3443// - 2.2 if none found, default to device selection by policy rules
3444// At this time, the corresponding output remote submix device is also connected
3445// and active playback use cases can be transferred to this mix if needed when reconnecting
3446// after AudioTracks are invalidated
3447//
3448// When playback starts, getOutputForAttr() will:
3449// - 1 look for a mix matching the address passed in attribtutes tags if any
3450// - 2 if none found, look for a mix matching the attributes usage
3451// - 3 if none found, default to device and output selection by policy rules.
3452
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003453status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003454{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003455 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3456 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003457 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003458 sp<HwModule> rSubmixModule;
3459 // examine each mix's route type
3460 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003461 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003462 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3463 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3464 ALOGE("Unsupported Policy Mix %zu of %zu: "
3465 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3466 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003467 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003468 break;
3469 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003470 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3471 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003472 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003473 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3474 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003475 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003476 rSubmixModule = mHwModules.getModuleFromName(
3477 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3478 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003479 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003480 i);
3481 res = INVALID_OPERATION;
3482 break;
3483 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003484 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003485
Eric Laurent97ac8712018-07-27 18:59:02 -07003486 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003487 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003488 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003489 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003490 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3491 } else {
3492 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3493 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003494 }
François Gaffie036e1e92015-03-19 10:16:24 +01003495
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003496 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003497 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003498 res = INVALID_OPERATION;
3499 break;
3500 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003501 audio_config_t outputConfig = mix.mFormat;
3502 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003503 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3504 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003505 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3506 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003507 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003508 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003509 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003510 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003511
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003512 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003513 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3514 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3515 ALOGE("Failed to set remote submix device available, type %u, address %s",
3516 mix.mDeviceType, address.string());
3517 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003518 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003519 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3520 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003521 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003522 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003523 i, mixes.size(), type, address.string());
3524
3525 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3526 mix.mDeviceType, mix.mDeviceAddress,
3527 String8(), AUDIO_FORMAT_DEFAULT);
3528 if (device == nullptr) {
3529 res = INVALID_OPERATION;
3530 break;
3531 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003532
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003533 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003534 // First try to find an already opened output supporting the device
3535 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003536 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003537
Eric Laurentc529cf62020-04-17 18:19:10 -07003538 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003539 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003540 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3541 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003542 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003543 } else {
3544 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003545 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003546 }
3547 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003548 // If no output found, try to find a direct output profile supporting the device
3549 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3550 sp<HwModule> module = mHwModules[i];
3551 for (size_t j = 0;
3552 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3553 j++) {
3554 sp<IOProfile> profile = module->getOutputProfiles()[j];
3555 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3556 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3557 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3558 address.string());
3559 res = INVALID_OPERATION;
3560 } else {
3561 foundOutput = true;
3562 }
3563 }
3564 }
3565 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003566 if (res != NO_ERROR) {
3567 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003568 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003569 res = INVALID_OPERATION;
3570 break;
3571 } else if (!foundOutput) {
3572 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003573 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003574 res = INVALID_OPERATION;
3575 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003576 } else {
3577 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003578 }
Eric Laurentc722f302014-12-10 11:21:49 -08003579 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003580 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003581 if (res != NO_ERROR) {
3582 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003583 } else if (checkOutputs) {
3584 checkForDeviceAndOutputChanges();
3585 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003586 }
3587 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003588}
3589
3590status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3591{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003592 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003593 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003594 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003595 sp<HwModule> rSubmixModule;
3596 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003597 for (const auto& mix : mixes) {
3598 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003599
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003600 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003601 rSubmixModule = mHwModules.getModuleFromName(
3602 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3603 if (rSubmixModule == 0) {
3604 res = INVALID_OPERATION;
3605 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003606 }
3607 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003608
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003609 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003610
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003611 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003612 res = INVALID_OPERATION;
3613 continue;
3614 }
3615
Kevin Rocard04ed0462019-05-02 17:53:24 -07003616 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3617 if (getDeviceConnectionState(device, address.string()) ==
3618 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3619 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3620 address.string(), "remote-submix",
3621 AUDIO_FORMAT_DEFAULT);
3622 if (res != OK) {
3623 ALOGE("Error making RemoteSubmix device unavailable for mix "
3624 "with type %d, address %s", device, address.string());
3625 }
3626 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003627 }
jiabin5740f082019-08-19 15:08:30 -07003628 rSubmixModule->removeOutputProfile(address.c_str());
3629 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003630
Kevin Rocard153f92d2018-12-18 18:33:28 -08003631 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003632 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003633 res = INVALID_OPERATION;
3634 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003635 } else {
3636 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003637 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003638 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003639 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003640 if (res == NO_ERROR && checkOutputs) {
3641 checkForDeviceAndOutputChanges();
3642 updateCallAndOutputRouting();
3643 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003644 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003645}
3646
Mikhail Naganov100f0122018-11-29 11:22:16 -08003647void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3648{
3649 size_t i = 0;
3650 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3651 for (const auto& fmt : mManualSurroundFormats) {
3652 if (i++ != 0) dst->append(", ");
3653 std::string sfmt;
3654 FormatConverter::toString(fmt, sfmt);
3655 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3656 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3657 }
3658}
3659
Eric Laurentc529cf62020-04-17 18:19:10 -07003660// Returns true if all devices types match the predicate and are supported by one HW module
3661bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003662 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003663 std::function<bool(audio_devices_t)> predicate,
3664 const char *context) {
3665 for (size_t i = 0; i < devices.size(); i++) {
3666 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003667 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003668 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003669 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003670 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003671 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003672 return false;
3673 }
3674 }
3675 return true;
3676}
3677
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003678status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003679 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003680 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003681 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3682 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003683 }
3684 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003685 if (res != NO_ERROR) {
3686 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3687 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003688 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003689
3690 checkForDeviceAndOutputChanges();
3691 updateCallAndOutputRouting();
3692
3693 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003694}
3695
3696status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3697 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003698 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3699 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003700 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003701 __FUNCTION__, uid);
3702 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003703 }
3704
Eric Laurentc529cf62020-04-17 18:19:10 -07003705 checkForDeviceAndOutputChanges();
3706 updateCallAndOutputRouting();
3707
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003708 return res;
3709}
3710
Eric Laurent2517af32020-11-25 15:31:27 +01003711
jiabin0a488932020-08-07 17:32:40 -07003712status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3713 device_role_t role,
3714 const AudioDeviceTypeAddrVector &devices) {
3715 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3716 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003717
Eric Laurentc529cf62020-04-17 18:19:10 -07003718 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003719 return BAD_VALUE;
3720 }
jiabin0a488932020-08-07 17:32:40 -07003721 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003722 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003723 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3724 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003725 return status;
3726 }
3727
3728 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003729
3730 bool forceVolumeReeval = false;
3731 // FIXME: workaround for truncated touch sounds
3732 // to be removed when the problem is handled by system UI
3733 uint32_t delayMs = 0;
3734 if (strategy == mCommunnicationStrategy) {
3735 forceVolumeReeval = true;
3736 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3737 updateInputRouting();
3738 }
3739 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003740
3741 return NO_ERROR;
3742}
3743
3744void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3745{
3746 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003747 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003748 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003749 // Only apply special touch sound delay once
3750 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003751 }
3752 for (size_t i = 0; i < mOutputs.size(); i++) {
3753 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3754 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003755 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3756 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003757 // As done in setDeviceConnectionState, we could also fix default device issue by
3758 // preventing the force re-routing in case of default dev that distinguishes on address.
3759 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003760 bool forceRouting = !newDevices.isEmpty();
3761 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3762 true /*requiresMuteCheck*/,
3763 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003764 // Only apply special touch sound delay once
3765 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003766 }
3767 if (forceVolumeReeval && !newDevices.isEmpty()) {
3768 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3769 }
3770 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003771 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003772}
3773
Eric Laurent2517af32020-11-25 15:31:27 +01003774void AudioPolicyManager::updateInputRouting() {
3775 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303776 // Skip for hotword recording as the input device switch
3777 // is handled within sound trigger HAL
3778 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3779 continue;
3780 }
Eric Laurent2517af32020-11-25 15:31:27 +01003781 auto newDevice = getNewInputDevice(activeDesc);
3782 // Force new input selection if the new device can not be reached via current input
3783 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3784 setInputDevice(activeDesc->mIoHandle, newDevice);
3785 } else {
3786 closeInput(activeDesc->mIoHandle);
3787 }
3788 }
3789}
3790
jiabin0a488932020-08-07 17:32:40 -07003791status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3792 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003793{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003794 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003795
jiabin0a488932020-08-07 17:32:40 -07003796 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003797 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003798 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3799 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003800 return status;
3801 }
3802
3803 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003804
3805 bool forceVolumeReeval = false;
3806 // FIXME: workaround for truncated touch sounds
3807 // to be removed when the problem is handled by system UI
3808 uint32_t delayMs = 0;
3809 if (strategy == mCommunnicationStrategy) {
3810 forceVolumeReeval = true;
3811 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3812 updateInputRouting();
3813 }
3814 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003815
3816 return NO_ERROR;
3817}
3818
jiabin0a488932020-08-07 17:32:40 -07003819status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3820 device_role_t role,
3821 AudioDeviceTypeAddrVector &devices) {
3822 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003823}
3824
Jiabin Huang3b98d322020-09-03 17:54:16 +00003825status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3826 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3827 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3828 dumpAudioDeviceTypeAddrVector(devices).c_str());
3829
Mikhail Naganov55773032020-10-01 15:08:13 -07003830 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003831 return BAD_VALUE;
3832 }
3833 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3834 ALOGW_IF(status != NO_ERROR,
3835 "Engine could not set preferred devices %s for audio source %d role %d",
3836 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3837
3838 return status;
3839}
3840
3841status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3842 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3843 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3844 dumpAudioDeviceTypeAddrVector(devices).c_str());
3845
Mikhail Naganov55773032020-10-01 15:08:13 -07003846 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003847 return BAD_VALUE;
3848 }
3849 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3850 ALOGW_IF(status != NO_ERROR,
3851 "Engine could not add preferred devices %s for audio source %d role %d",
3852 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3853
Eric Laurent2517af32020-11-25 15:31:27 +01003854 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003855 return status;
3856}
3857
3858status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3859 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3860{
3861 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3862 dumpAudioDeviceTypeAddrVector(devices).c_str());
3863
Mikhail Naganov55773032020-10-01 15:08:13 -07003864 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003865 return BAD_VALUE;
3866 }
3867
3868 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3869 audioSource, role, devices);
3870 ALOGW_IF(status != NO_ERROR,
3871 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3872
Eric Laurent2517af32020-11-25 15:31:27 +01003873 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003874 return status;
3875}
3876
3877status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3878 device_role_t role) {
3879 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3880
3881 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3882 ALOGW_IF(status != NO_ERROR,
3883 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3884
Eric Laurent2517af32020-11-25 15:31:27 +01003885 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003886 return status;
3887}
3888
3889status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3890 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3891 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3892}
3893
Oscar Azucena90e77632019-11-27 17:12:28 -08003894status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003895 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003896 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003897 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3898 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003899 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003900 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3901 if (status != NO_ERROR) {
3902 ALOGE("%s() could not set device affinity for userId %d",
3903 __FUNCTION__, userId);
3904 return status;
3905 }
3906
3907 // reevaluate outputs for all devices
3908 checkForDeviceAndOutputChanges();
3909 updateCallAndOutputRouting();
3910
3911 return NO_ERROR;
3912}
3913
3914status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003915 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003916 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3917 if (status != NO_ERROR) {
3918 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3919 __FUNCTION__, userId);
3920 return status;
3921 }
3922
3923 // reevaluate outputs for all devices
3924 checkForDeviceAndOutputChanges();
3925 updateCallAndOutputRouting();
3926
3927 return NO_ERROR;
3928}
3929
Andy Hungc29d82b2018-10-05 12:23:17 -07003930void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003931{
Andy Hungc29d82b2018-10-05 12:23:17 -07003932 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003933 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003934 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003935 std::string stateLiteral;
3936 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003937 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003938 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3939 "communications", "media", "record", "dock", "system",
3940 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3941 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3942 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003943 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3944 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3945 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3946 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3947 dst->append(" (MANUAL: ");
3948 dumpManualSurroundFormats(dst);
3949 dst->append(")");
3950 }
3951 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003952 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003953 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3954 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003955 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003956 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003957
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003958 dst->append("\n");
3959 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3960 dst->append("\n");
3961 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003962 mHwModulesAll.dump(dst);
3963 mOutputs.dump(dst);
3964 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003965 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003966 mAudioPatches.dump(dst);
3967 mPolicyMixes.dump(dst);
3968 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003969
Kevin Rocardb99cc752019-03-21 20:52:24 -07003970 dst->appendFormat(" AllowedCapturePolicies:\n");
3971 for (auto& policy : mAllowedCapturePolicies) {
3972 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3973 }
3974
jiabina84c3d32022-12-02 18:59:55 +00003975 dst->appendFormat(" Preferred mixer audio configuration:\n");
3976 for (const auto it : mPreferredMixerAttrInfos) {
3977 dst->appendFormat(" - device port id: %d\n", it.first);
3978 for (const auto preferredMixerInfoIt : it.second) {
3979 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
3980 preferredMixerInfoIt.second->dump(dst);
3981 }
3982 }
3983
François Gaffiec005e562018-11-06 15:04:49 +01003984 dst->appendFormat("\nPolicy Engine dump:\n");
3985 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003986}
3987
3988status_t AudioPolicyManager::dump(int fd)
3989{
3990 String8 result;
3991 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003992 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003993 return NO_ERROR;
3994}
3995
Kevin Rocardb99cc752019-03-21 20:52:24 -07003996status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3997{
3998 mAllowedCapturePolicies[uid] = capturePolicy;
3999 return NO_ERROR;
4000}
4001
Eric Laurente552edb2014-03-10 17:42:56 -07004002// This function checks for the parameters which can be offloaded.
4003// This can be enhanced depending on the capability of the DSP and policy
4004// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004005audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004006{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004007 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004008 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004009 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004010 offloadInfo.format,
4011 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4012 offloadInfo.has_video);
4013
jiabin2b9d5a12021-12-10 01:06:29 +00004014 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004015 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004016 }
4017
4018 // See if there is a profile to support this.
4019 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004020 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004021 offloadInfo.sample_rate,
4022 offloadInfo.format,
4023 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004024 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4025 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004026 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4027 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4028 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004029 if (profile == nullptr) {
4030 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4031 }
4032 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4033 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4034 }
4035 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004036}
4037
Michael Chana94fbb22018-04-24 14:31:19 +10004038bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4039 const audio_attributes_t& attributes) {
4040 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004041 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004042 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4043 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004044 config.sample_rate,
4045 config.format,
4046 config.channel_mask,
4047 output_flags,
4048 true /* directOnly */);
4049 ALOGV("%s() profile %sfound with name: %s, "
4050 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4051 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004052 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004053 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004054
4055 // also try the MSD module if compatible profile not found
4056 if (profile == nullptr) {
4057 profile = getMsdProfileForOutput(outputDevices,
4058 config.sample_rate,
4059 config.format,
4060 config.channel_mask,
4061 output_flags,
4062 true /* directOnly */);
4063 ALOGV("%s() MSD profile %sfound with name: %s, "
4064 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4065 __FUNCTION__, profile != 0 ? "" : "NOT ",
4066 (profile != 0 ? profile->getTagName().c_str() : "null"),
4067 config.sample_rate, config.format, config.channel_mask, output_flags);
4068 }
4069 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004070}
4071
jiabin2b9d5a12021-12-10 01:06:29 +00004072bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4073 bool durationIgnored) {
4074 if (mMasterMono) {
4075 return false; // no offloading if mono is set.
4076 }
4077
4078 // Check if offload has been disabled
4079 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4080 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4081 return false;
4082 }
4083
4084 // Check if stream type is music, then only allow offload as of now.
4085 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4086 {
4087 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4088 return false;
4089 }
4090
4091 //TODO: enable audio offloading with video when ready
4092 const bool allowOffloadWithVideo =
4093 property_get_bool("audio.offload.video", false /* default_value */);
4094 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4095 ALOGV("%s: has_video == true, returning false", __func__);
4096 return false;
4097 }
4098
4099 //If duration is less than minimum value defined in property, return false
4100 const int min_duration_secs = property_get_int32(
4101 "audio.offload.min.duration.secs", -1 /* default_value */);
4102 if (!durationIgnored) {
4103 if (min_duration_secs >= 0) {
4104 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4105 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4106 __func__, min_duration_secs);
4107 return false;
4108 }
4109 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4110 ALOGV("%s: Offload denied by duration < default min(=%u)",
4111 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4112 return false;
4113 }
4114 }
4115
4116 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4117 // creating an offloaded track and tearing it down immediately after start when audioflinger
4118 // detects there is an active non offloadable effect.
4119 // FIXME: We should check the audio session here but we do not have it in this context.
4120 // This may prevent offloading in rare situations where effects are left active by apps
4121 // in the background.
4122 if (mEffects.isNonOffloadableEffectEnabled()) {
4123 return false;
4124 }
4125
4126 return true;
4127}
4128
4129audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4130 const audio_config_t *config) {
4131 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4132 offloadInfo.format = config->format;
4133 offloadInfo.sample_rate = config->sample_rate;
4134 offloadInfo.channel_mask = config->channel_mask;
4135 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4136 offloadInfo.has_video = false;
4137 offloadInfo.is_streaming = false;
4138 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4139
4140 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4141 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4142 audio_flags_to_audio_output_flags(attr->flags, &flags);
4143 // only retain flags that will drive compressed offload or passthrough
4144 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4145 if (offloadPossible) {
4146 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4147 }
4148 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4149
Dorin Drimusfae3c642022-03-17 18:36:30 +01004150 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004151 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004152 DeviceVector outputDevices = engineOutputDevices;
4153 // the MSD module checks for different conditions and output devices
4154 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4155 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4156 continue;
4157 }
4158 outputDevices = getMsdAudioOutDevices();
4159 }
jiabin2b9d5a12021-12-10 01:06:29 +00004160 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004161 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004162 config->sample_rate, nullptr /*updatedSamplingRate*/,
4163 config->format, nullptr /*updatedFormat*/,
4164 config->channel_mask, nullptr /*updatedChannelMask*/,
4165 flags)) {
4166 continue;
4167 }
4168 // reject profiles not corresponding to a device currently available
4169 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4170 continue;
4171 }
4172 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4173 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004174 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004175 != AUDIO_DIRECT_NOT_SUPPORTED) {
4176 // Already reports offload gapless supported. No need to report offload support.
4177 continue;
4178 }
4179 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4180 != AUDIO_OUTPUT_FLAG_NONE) {
4181 // If offload gapless is reported, no need to report offload support.
4182 directMode = (audio_direct_mode_t) ((directMode &
4183 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4184 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4185 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004186 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004187 }
4188 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004189 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004190 }
4191 }
4192 }
4193 return directMode;
4194}
4195
Dorin Drimusf2196d82022-01-03 12:11:18 +01004196status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4197 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004198 if (mEffects.isNonOffloadableEffectEnabled()) {
4199 return OK;
4200 }
jiabinf1c73972022-04-14 16:28:52 -07004201 DeviceVector devices;
4202 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004203 if (status != OK) {
4204 return status;
4205 }
4206 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4207 if (devices.empty()) {
4208 return OK; // no output devices for the attributes
4209 }
jiabinf1c73972022-04-14 16:28:52 -07004210 return getProfilesForDevices(devices, audioProfilesVector,
4211 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004212}
4213
jiabina84c3d32022-12-02 18:59:55 +00004214status_t AudioPolicyManager::getSupportedMixerAttributes(
4215 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4216 ALOGV("%s, portId=%d", __func__, portId);
4217 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4218 if (deviceDescriptor == nullptr) {
4219 ALOGE("%s the requested device is currently unavailable", __func__);
4220 return BAD_VALUE;
4221 }
4222 for (const auto& hwModule : mHwModules) {
4223 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4224 if (curProfile->supportsDevice(deviceDescriptor)) {
4225 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4226 }
4227 }
4228 }
4229 return NO_ERROR;
4230}
4231
4232status_t AudioPolicyManager::setPreferredMixerAttributes(
4233 const audio_attributes_t *attr,
4234 audio_port_handle_t portId,
4235 uid_t uid,
4236 const audio_mixer_attributes_t *mixerAttributes) {
4237 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4238 "mixerBehavior=%d}, uid=%d, portId=%u",
4239 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4240 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4241 mixerAttributes->mixer_behavior, uid, portId);
4242 if (attr->usage != AUDIO_USAGE_MEDIA) {
4243 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4244 return BAD_VALUE;
4245 }
4246 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4247 if (deviceDescriptor == nullptr) {
4248 ALOGE("%s the requested device is currently unavailable", __func__);
4249 return BAD_VALUE;
4250 }
4251 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4252 ALOGE("%s(%d), type=%d, is not a usb output device",
4253 __func__, portId, deviceDescriptor->type());
4254 return BAD_VALUE;
4255 }
4256
4257 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4258 audio_flags_to_audio_output_flags(attr->flags, &flags);
4259 flags = (audio_output_flags_t) (flags |
4260 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4261 sp<IOProfile> profile = nullptr;
4262 DeviceVector devices(deviceDescriptor);
4263 for (const auto& hwModule : mHwModules) {
4264 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4265 if (curProfile->hasDynamicAudioProfile()
4266 && curProfile->isCompatibleProfile(devices,
4267 mixerAttributes->config.sample_rate,
4268 nullptr /*updatedSamplingRate*/,
4269 mixerAttributes->config.format,
4270 nullptr /*updatedFormat*/,
4271 mixerAttributes->config.channel_mask,
4272 nullptr /*updatedChannelMask*/,
4273 flags,
4274 false /*exactMatchRequiredForInputFlags*/)) {
4275 profile = curProfile;
4276 break;
4277 }
4278 }
4279 }
4280 if (profile == nullptr) {
4281 ALOGE("%s, there is no compatible profile found", __func__);
4282 return BAD_VALUE;
4283 }
4284
4285 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4286 sp<PreferredMixerAttributesInfo>::make(
4287 uid, portId, profile, flags, *mixerAttributes);
4288 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4289 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4290
4291 // If 1) there is any client from the preferred mixer configuration owner that is currently
4292 // active and matches the strategy and 2) current output is on the preferred device and the
4293 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4294 // configuration.
4295 std::vector<audio_io_handle_t> outputsToReopen;
4296 for (size_t i = 0; i < mOutputs.size(); i++) {
4297 const auto output = mOutputs.valueAt(i);
4298 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)
4299 && !output->isConfigurationMatched(mixerAttributes->config, flags)) {
4300 for (const auto& client : output->getActiveClients()) {
4301 if (client->uid() == uid && client->strategy() == strategy) {
4302 client->setIsInvalid();
4303 outputsToReopen.push_back(output->mIoHandle);
4304 }
4305 }
4306 }
4307 }
4308 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4309 config.sample_rate = mixerAttributes->config.sample_rate;
4310 config.channel_mask = mixerAttributes->config.channel_mask;
4311 config.format = mixerAttributes->config.format;
4312 for (const auto output : outputsToReopen) {
4313 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4314 }
4315
4316 return NO_ERROR;
4317}
4318
4319sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4320 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4321 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4322 if (it == mPreferredMixerAttrInfos.end()) {
4323 return nullptr;
4324 }
4325 auto mixerAttrInfoIt = it->second.find(strategy);
4326 if (mixerAttrInfoIt == it->second.end()) {
4327 return nullptr;
4328 }
4329 return mixerAttrInfoIt->second;
4330}
4331
4332status_t AudioPolicyManager::getPreferredMixerAttributes(
4333 const audio_attributes_t *attr,
4334 audio_port_handle_t portId,
4335 audio_mixer_attributes_t* mixerAttributes) {
4336 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4337 portId, mEngine->getProductStrategyForAttributes(*attr));
4338 if (info == nullptr) {
4339 return NAME_NOT_FOUND;
4340 }
4341 *mixerAttributes = info->getMixerAttributes();
4342 return NO_ERROR;
4343}
4344
4345status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4346 audio_port_handle_t portId,
4347 uid_t uid) {
4348 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4349 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4350 if (preferredMixerAttrInfo == nullptr) {
4351 return NAME_NOT_FOUND;
4352 }
4353 if (preferredMixerAttrInfo->getUid() != uid) {
4354 ALOGE("%s, requested uid=%d, owned uid=%d",
4355 __func__, uid, preferredMixerAttrInfo->getUid());
4356 return PERMISSION_DENIED;
4357 }
4358 mPreferredMixerAttrInfos[portId].erase(strategy);
4359 if (mPreferredMixerAttrInfos[portId].empty()) {
4360 mPreferredMixerAttrInfos.erase(portId);
4361 }
4362
4363 // Reconfig existing output
4364 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4365 for (size_t i = 0; i < mOutputs.size(); i++) {
4366 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4367 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4368 }
4369 }
4370 for (const auto output : potentialOutputsToReopen) {
4371 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4372 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4373 preferredMixerAttrInfo->getFlags())) {
4374 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4375 }
4376 }
4377 return NO_ERROR;
4378}
4379
Eric Laurent6a94d692014-05-20 11:18:06 -07004380status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4381 audio_port_type_t type,
4382 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004383 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004384 unsigned int *generation)
4385{
jiabin19cdba52020-11-24 11:28:58 -08004386 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4387 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004388 return BAD_VALUE;
4389 }
4390 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004391 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004392 *num_ports = 0;
4393 }
4394
4395 size_t portsWritten = 0;
4396 size_t portsMax = *num_ports;
4397 *num_ports = 0;
4398 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004399 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4400 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004401 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004402 for (const auto& dev : mAvailableOutputDevices) {
4403 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004404 continue;
4405 }
4406 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004407 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004408 }
4409 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004410 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004411 }
4412 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004413 for (const auto& dev : mAvailableInputDevices) {
4414 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004415 continue;
4416 }
4417 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004418 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004419 }
4420 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004421 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004422 }
4423 }
4424 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4425 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4426 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4427 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4428 }
4429 *num_ports += mInputs.size();
4430 }
4431 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004432 size_t numOutputs = 0;
4433 for (size_t i = 0; i < mOutputs.size(); i++) {
4434 if (!mOutputs[i]->isDuplicated()) {
4435 numOutputs++;
4436 if (portsWritten < portsMax) {
4437 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4438 }
4439 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004440 }
Eric Laurent84c70242014-06-23 08:46:27 -07004441 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004442 }
4443 }
jiabina84c3d32022-12-02 18:59:55 +00004444
Eric Laurent6a94d692014-05-20 11:18:06 -07004445 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004446 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004447 return NO_ERROR;
4448}
4449
jiabin19cdba52020-11-24 11:28:58 -08004450status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004451{
Eric Laurent99fcae42018-05-17 16:59:18 -07004452 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4453 return BAD_VALUE;
4454 }
4455 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4456 if (dev != 0) {
4457 dev->toAudioPort(port);
4458 return NO_ERROR;
4459 }
4460 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4461 if (dev != 0) {
4462 dev->toAudioPort(port);
4463 return NO_ERROR;
4464 }
4465 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4466 if (out != 0) {
4467 out->toAudioPort(port);
4468 return NO_ERROR;
4469 }
4470 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4471 if (in != 0) {
4472 in->toAudioPort(port);
4473 return NO_ERROR;
4474 }
4475 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004476}
4477
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004478status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4479 audio_patch_handle_t *handle,
4480 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004481{
François Gaffieafd4cea2019-11-18 15:50:22 +01004482 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004483 if (handle == NULL || patch == NULL) {
4484 return BAD_VALUE;
4485 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004486 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004487 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004488 return BAD_VALUE;
4489 }
4490 // only one source per audio patch supported for now
4491 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004492 return INVALID_OPERATION;
4493 }
Eric Laurent874c42872014-08-08 15:13:39 -07004494 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004495 return INVALID_OPERATION;
4496 }
Eric Laurent874c42872014-08-08 15:13:39 -07004497 for (size_t i = 0; i < patch->num_sinks; i++) {
4498 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4499 return INVALID_OPERATION;
4500 }
4501 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004502
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004503 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4504 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4505 if (srcDevice == nullptr || sinkDevice == nullptr) {
4506 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4507 return BAD_VALUE;
4508 }
4509 ALOGV("%s between source %s and sink %s", __func__,
4510 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4511 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4512 // Default attributes, default volume priority, not to infer with non raw audio patches.
4513 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4514 const struct audio_port_config *source = &patch->sources[0];
4515 sp<SourceClientDescriptor> sourceDesc =
4516 new InternalSourceClientDescriptor(
4517 portId, uid, attributes, *source, srcDevice, sinkDevice,
4518 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4519
4520 status_t status =
4521 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4522
4523 if (status != NO_ERROR) {
4524 return INVALID_OPERATION;
4525 }
4526 mAudioSources.add(portId, sourceDesc);
4527 return NO_ERROR;
4528}
4529
4530status_t AudioPolicyManager::connectAudioSourceToSink(
4531 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4532 const struct audio_patch *patch,
4533 audio_patch_handle_t &handle,
4534 uid_t uid, uint32_t delayMs)
4535{
4536 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4537 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4538 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4539 return INVALID_OPERATION;
4540 }
4541 sourceDesc->connect(handle, sinkDevice);
4542 if (isMsdPatch(handle)) {
4543 return NO_ERROR;
4544 }
4545 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4546 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4547 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4548 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4549 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4550 goto FailurePatchAdded;
4551 }
4552 status = swOutput->start();
4553 if (status != NO_ERROR) {
4554 goto FailureSourceAdded;
4555 }
4556 swOutput->addClient(sourceDesc);
4557 status = startSource(swOutput, sourceDesc, &delayMs);
4558 if (status != NO_ERROR) {
4559 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4560 goto FailureSourceActive;
4561 }
4562 if (delayMs != 0) {
4563 usleep(delayMs * 1000);
4564 }
4565 return NO_ERROR;
4566
4567FailureSourceActive:
4568 swOutput->stop();
4569 releaseOutput(sourceDesc->portId());
4570FailureSourceAdded:
4571 sourceDesc->setSwOutput(nullptr);
4572FailurePatchAdded:
4573 releaseAudioPatchInternal(handle);
4574 return INVALID_OPERATION;
4575}
4576
4577status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4578 audio_patch_handle_t *handle,
4579 uid_t uid, uint32_t delayMs,
4580 const sp<SourceClientDescriptor>& sourceDesc)
4581{
4582 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004583 sp<AudioPatch> patchDesc;
4584 ssize_t index = mAudioPatches.indexOfKey(*handle);
4585
François Gaffieafd4cea2019-11-18 15:50:22 +01004586 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4587 patch->sources[0].role,
4588 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004589#if LOG_NDEBUG == 0
4590 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004591 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4592 patch->sinks[i].role,
4593 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004594 }
4595#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004596
4597 if (index >= 0) {
4598 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004599 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4600 __func__, mUidCached, patchDesc->getUid(), uid);
4601 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004602 return INVALID_OPERATION;
4603 }
4604 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004605 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004606 }
4607
4608 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004609 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004610 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004611 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004612 return BAD_VALUE;
4613 }
Eric Laurent84c70242014-06-23 08:46:27 -07004614 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4615 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004616 if (patchDesc != 0) {
4617 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004618 ALOGV("%s source id differs for patch current id %d new id %d",
4619 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004620 return BAD_VALUE;
4621 }
4622 }
Eric Laurent874c42872014-08-08 15:13:39 -07004623 DeviceVector devices;
4624 for (size_t i = 0; i < patch->num_sinks; i++) {
4625 // Only support mix to devices connection
4626 // TODO add support for mix to mix connection
4627 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004628 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004629 return INVALID_OPERATION;
4630 }
4631 sp<DeviceDescriptor> devDesc =
4632 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4633 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004634 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004635 return BAD_VALUE;
4636 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004637
François Gaffie11d30102018-11-02 16:09:09 +01004638 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004639 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004640 NULL, // updatedSamplingRate
4641 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004642 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004643 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004644 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004645 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004646 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004647 return INVALID_OPERATION;
4648 }
4649 devices.add(devDesc);
4650 }
4651 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004652 return INVALID_OPERATION;
4653 }
Eric Laurent874c42872014-08-08 15:13:39 -07004654
Eric Laurent6a94d692014-05-20 11:18:06 -07004655 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004656 ALOGV("%s setting device %s on output %d",
4657 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004658 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004659 index = mAudioPatches.indexOfKey(*handle);
4660 if (index >= 0) {
4661 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004662 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004663 }
4664 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004665 patchDesc->setUid(uid);
4666 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004667 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004668 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004669 return INVALID_OPERATION;
4670 }
4671 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4672 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4673 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004674 // only one sink supported when connecting an input device to a mix
4675 if (patch->num_sinks > 1) {
4676 return INVALID_OPERATION;
4677 }
François Gaffie53615e22015-03-19 09:24:12 +01004678 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004679 if (inputDesc == NULL) {
4680 return BAD_VALUE;
4681 }
4682 if (patchDesc != 0) {
4683 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4684 return BAD_VALUE;
4685 }
4686 }
François Gaffie11d30102018-11-02 16:09:09 +01004687 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004689 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004690 return BAD_VALUE;
4691 }
4692
François Gaffie11d30102018-11-02 16:09:09 +01004693 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004694 patch->sinks[0].sample_rate,
4695 NULL, /*updatedSampleRate*/
4696 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004697 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004698 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004699 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004700 // FIXME for the parameter type,
4701 // and the NONE
4702 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004703 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004704 return INVALID_OPERATION;
4705 }
4706 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004707 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004708 device->toString().c_str(), inputDesc->mIoHandle);
4709 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004710 index = mAudioPatches.indexOfKey(*handle);
4711 if (index >= 0) {
4712 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004713 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004714 }
4715 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004716 patchDesc->setUid(uid);
4717 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004718 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004719 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004720 return INVALID_OPERATION;
4721 }
4722 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4723 // device to device connection
4724 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004725 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 return BAD_VALUE;
4727 }
4728 }
François Gaffie11d30102018-11-02 16:09:09 +01004729 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004730 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004731 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004732 return BAD_VALUE;
4733 }
Eric Laurent874c42872014-08-08 15:13:39 -07004734
Eric Laurent6a94d692014-05-20 11:18:06 -07004735 //update source and sink with our own data as the data passed in the patch may
4736 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004737 PatchBuilder patchBuilder;
4738 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004739
4740 // if first sink is to MSD, establish single MSD patch
4741 if (getMsdAudioOutDevices().contains(
4742 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4743 ALOGV("%s patching to MSD", __FUNCTION__);
4744 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4745 goto installPatch;
4746 }
4747
François Gaffieafd4cea2019-11-18 15:50:22 +01004748 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4749 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004750
Eric Laurent874c42872014-08-08 15:13:39 -07004751 for (size_t i = 0; i < patch->num_sinks; i++) {
4752 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004753 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004754 return INVALID_OPERATION;
4755 }
François Gaffie11d30102018-11-02 16:09:09 +01004756 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004757 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004758 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004759 return BAD_VALUE;
4760 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004761 audio_port_config sinkPortConfig = {};
4762 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4763 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004764
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004765 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4766 // volume management purpose (tracking activity)
4767 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4768 // in config XML to reach the sink so that is can be declared as available.
4769 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004770 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004771 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004772 // take care of dynamic routing for SwOutput selection,
4773 audio_attributes_t attributes = sourceDesc->attributes();
4774 audio_stream_type_t stream = sourceDesc->stream();
4775 audio_attributes_t resultAttr;
4776 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4777 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004778 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4779 config.channel_mask =
4780 (audio_channel_mask_get_representation(sourceMask)
4781 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4782 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004783 config.format = sourceDesc->config().format;
4784 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4785 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4786 bool isRequestedDeviceForExclusiveUse = false;
4787 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004788 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004789 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4790 &stream, sourceDesc->uid(), &config, &flags,
4791 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004792 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004793 if (output == AUDIO_IO_HANDLE_NONE) {
4794 ALOGV("%s no output for device %s",
4795 __FUNCTION__, sinkDevice->toString().c_str());
4796 return INVALID_OPERATION;
4797 }
4798 outputDesc = mOutputs.valueFor(output);
4799 if (outputDesc->isDuplicated()) {
4800 ALOGE("%s output is duplicated", __func__);
4801 return INVALID_OPERATION;
4802 }
François Gaffie7e39df22022-04-26 12:48:49 +02004803 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4804 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004805 } else {
4806 // Same for "raw patches" aka created from createAudioPatch API
4807 SortedVector<audio_io_handle_t> outputs =
4808 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4809 // if the sink device is reachable via an opened output stream, request to
4810 // go via this output stream by adding a second source to the patch
4811 // description
4812 output = selectOutput(outputs);
4813 if (output == AUDIO_IO_HANDLE_NONE) {
4814 ALOGE("%s no output available for internal patch sink", __func__);
4815 return INVALID_OPERATION;
4816 }
4817 outputDesc = mOutputs.valueFor(output);
4818 if (outputDesc->isDuplicated()) {
4819 ALOGV("%s output for device %s is duplicated",
4820 __func__, sinkDevice->toString().c_str());
4821 return INVALID_OPERATION;
4822 }
François Gaffie7e39df22022-04-26 12:48:49 +02004823 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004824 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004825 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004826 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004827 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004828 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004829 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4830 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004831 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4832 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004833 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004834 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004835 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004836 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004837 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004838 return INVALID_OPERATION;
4839 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004840 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004841 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004842 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004843 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004844 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004845 srcMixPortConfig.ext.mix.usecase.stream =
4846 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004847 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4848 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004849 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004850 }
Eric Laurent83b88082014-06-20 18:31:16 -07004851 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004852 }
4853 // TODO: check from routing capabilities in config file and other conflicting patches
4854
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004855installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004856 status_t status = installPatch(
4857 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004858 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004859 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004860 return INVALID_OPERATION;
4861 }
4862 } else {
4863 return BAD_VALUE;
4864 }
4865 } else {
4866 return BAD_VALUE;
4867 }
4868 return NO_ERROR;
4869}
4870
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004871status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004872{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004873 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004874 ssize_t index = mAudioPatches.indexOfKey(handle);
4875
4876 if (index < 0) {
4877 return BAD_VALUE;
4878 }
4879 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004880 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4881 __func__, mUidCached, patchDesc->getUid(), uid);
4882 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004883 return INVALID_OPERATION;
4884 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004885 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4886 for (size_t i = 0; i < mAudioSources.size(); i++) {
4887 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4888 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4889 portId = sourceDesc->portId();
4890 break;
4891 }
4892 }
4893 return portId != AUDIO_PORT_HANDLE_NONE ?
4894 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004895}
Eric Laurent6a94d692014-05-20 11:18:06 -07004896
François Gaffieafd4cea2019-11-18 15:50:22 +01004897status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004898 uint32_t delayMs,
4899 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004900{
4901 ALOGV("%s patch %d", __func__, handle);
4902 if (mAudioPatches.indexOfKey(handle) < 0) {
4903 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4904 return BAD_VALUE;
4905 }
4906 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004907 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004908 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004910 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004911 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004912 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004913 return BAD_VALUE;
4914 }
4915
François Gaffie11d30102018-11-02 16:09:09 +01004916 setOutputDevices(outputDesc,
4917 getNewOutputDevices(outputDesc, true /*fromCache*/),
4918 true,
4919 0,
4920 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004921 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4922 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004923 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004924 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004925 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004926 return BAD_VALUE;
4927 }
4928 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004929 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004930 true,
4931 NULL);
4932 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004933 status_t status =
4934 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4935 ALOGV("%s patch panel returned %d patchHandle %d",
4936 __func__, status, patchDesc->getAfHandle());
4937 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004938 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004939 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004940 // SW or HW Bridge
4941 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4942 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004943 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004944 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4945 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4946 outputDesc = sourceDesc->swOutput().promote();
4947 }
4948 if (outputDesc == nullptr) {
4949 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4950 // releaseOutput has already called closeOutput in case of direct output
4951 return NO_ERROR;
4952 }
François Gaffie7e39df22022-04-26 12:48:49 +02004953 patchHandle = outputDesc->getPatchHandle();
4954 // When a Sw bridge is released, the mixer used by this bridge will release its
4955 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4956 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4957 // updating hal patch handle (prevent leaks).
4958 // While using a HwBridge, force reconsidering device only if not reusing an existing
4959 // output and no more activity on output (will force to close).
4960 bool force = sourceDesc->useSwBridge() ||
4961 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4962 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4963 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4964 // Reconsider device only for cases:
4965 // 1 / Active Output
4966 // 2 / Inactive Output previously hosting HwBridge
4967 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4968 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4969 sourceDesc->canCloseOutput();
4970 setOutputDevices(outputDesc,
4971 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4972 outputDesc->devices(),
4973 force,
4974 0,
4975 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004976 } else {
4977 return BAD_VALUE;
4978 }
4979 } else {
4980 return BAD_VALUE;
4981 }
4982 return NO_ERROR;
4983}
4984
4985status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4986 struct audio_patch *patches,
4987 unsigned int *generation)
4988{
François Gaffie53615e22015-03-19 09:24:12 +01004989 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004990 return BAD_VALUE;
4991 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004993 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004994}
4995
Eric Laurente1715a42014-05-20 11:30:42 -07004996status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004997{
Eric Laurente1715a42014-05-20 11:30:42 -07004998 ALOGV("setAudioPortConfig()");
4999
5000 if (config == NULL) {
5001 return BAD_VALUE;
5002 }
5003 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5004 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005005 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5006 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005007 }
5008
Eric Laurenta121f902014-06-03 13:32:54 -07005009 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005010 if (config->type == AUDIO_PORT_TYPE_MIX) {
5011 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005012 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005013 if (outputDesc == NULL) {
5014 return BAD_VALUE;
5015 }
Eric Laurent84c70242014-06-23 08:46:27 -07005016 ALOG_ASSERT(!outputDesc->isDuplicated(),
5017 "setAudioPortConfig() called on duplicated output %d",
5018 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005019 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005020 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005021 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005022 if (inputDesc == NULL) {
5023 return BAD_VALUE;
5024 }
Eric Laurenta121f902014-06-03 13:32:54 -07005025 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005026 } else {
5027 return BAD_VALUE;
5028 }
5029 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5030 sp<DeviceDescriptor> deviceDesc;
5031 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5032 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5033 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5034 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5035 } else {
5036 return BAD_VALUE;
5037 }
5038 if (deviceDesc == NULL) {
5039 return BAD_VALUE;
5040 }
Eric Laurenta121f902014-06-03 13:32:54 -07005041 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005042 } else {
5043 return BAD_VALUE;
5044 }
5045
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005046 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005047 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5048 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005049 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005050 audioPortConfig->toAudioPortConfig(&newConfig, config);
5051 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005052 }
Eric Laurenta121f902014-06-03 13:32:54 -07005053 if (status != NO_ERROR) {
5054 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005055 }
Eric Laurente1715a42014-05-20 11:30:42 -07005056
5057 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005058}
5059
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005060void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5061{
Eric Laurentd60560a2015-04-10 11:31:20 -07005062 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005063 clearAudioPatches(uid);
5064 clearSessionRoutes(uid);
5065}
5066
Eric Laurent6a94d692014-05-20 11:18:06 -07005067void AudioPolicyManager::clearAudioPatches(uid_t uid)
5068{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005069 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005070 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005071 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005072 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005073 }
5074 }
5075}
5076
François Gaffiec005e562018-11-06 15:04:49 +01005077void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005078{
François Gaffiec005e562018-11-06 15:04:49 +01005079 // Take the first attributes following the product strategy as it is used to retrieve the routed
5080 // device. All attributes wihin a strategy follows the same "routing strategy"
5081 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5082 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005083 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005084 for (size_t j = 0; j < mOutputs.size(); j++) {
5085 if (mOutputs.keyAt(j) == ouptutToSkip) {
5086 continue;
5087 }
5088 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005089 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005090 continue;
5091 }
5092 // If the default device for this strategy is on another output mix,
5093 // invalidate all tracks in this strategy to force re connection.
5094 // Otherwise select new device on the output mix.
5095 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01005096 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
5097 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005098 }
5099 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005100 setOutputDevices(
5101 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005102 }
5103 }
5104}
5105
5106void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5107{
5108 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005109 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005110 for (size_t i = 0; i < mOutputs.size(); i++) {
5111 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005112 for (const auto& client : outputDesc->getClientIterable()) {
5113 if (client->hasPreferredDevice() && client->uid() == uid) {
5114 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005115 auto clientStrategy = client->strategy();
5116 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5117 end(affectedStrategies)) {
5118 continue;
5119 }
5120 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005121 }
5122 }
5123 }
5124 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005125 for (const auto& strategy : affectedStrategies) {
5126 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005127 }
5128
5129 // remove input routes associated with this uid
5130 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005131 for (size_t i = 0; i < mInputs.size(); i++) {
5132 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005133 for (const auto& client : inputDesc->getClientIterable()) {
5134 if (client->hasPreferredDevice() && client->uid() == uid) {
5135 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5136 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005137 }
5138 }
5139 }
5140 // reroute inputs if necessary
5141 SortedVector<audio_io_handle_t> inputsToClose;
5142 for (size_t i = 0; i < mInputs.size(); i++) {
5143 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005144 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005145 inputsToClose.add(inputDesc->mIoHandle);
5146 }
5147 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005148 for (const auto& input : inputsToClose) {
5149 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005150 }
5151}
5152
Eric Laurentd60560a2015-04-10 11:31:20 -07005153void AudioPolicyManager::clearAudioSources(uid_t uid)
5154{
5155 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005156 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5157 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005158 stopAudioSource(mAudioSources.keyAt(i));
5159 }
5160 }
5161}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005162
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005163status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5164 audio_io_handle_t *ioHandle,
5165 audio_devices_t *device)
5166{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005167 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5168 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005169 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005170 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005171
François Gaffiedf372692015-03-19 10:43:27 +01005172 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005173}
5174
Eric Laurentd60560a2015-04-10 11:31:20 -07005175status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005176 const audio_attributes_t *attributes,
5177 audio_port_handle_t *portId,
5178 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005179{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005180 ALOGV("%s", __FUNCTION__);
5181 *portId = AUDIO_PORT_HANDLE_NONE;
5182
5183 if (source == NULL || attributes == NULL || portId == NULL) {
5184 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5185 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005186 return BAD_VALUE;
5187 }
5188
Eric Laurentd60560a2015-04-10 11:31:20 -07005189 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5190 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005191 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5192 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005193 return INVALID_OPERATION;
5194 }
5195
François Gaffie11d30102018-11-02 16:09:09 +01005196 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005197 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005198 String8(source->ext.device.address),
5199 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005200 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005201 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005202 return BAD_VALUE;
5203 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005204
jiabin4ef93452019-09-10 14:29:54 -07005205 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005206
François Gaffieaaac0fd2018-11-22 17:56:39 +01005207 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005208 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005209 mEngine->getStreamTypeForAttributes(*attributes),
5210 mEngine->getProductStrategyForAttributes(*attributes),
5211 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005212
5213 status_t status = connectAudioSource(sourceDesc);
5214 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005215 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005216 }
5217 return status;
5218}
5219
Francois Gaffie601801d2021-06-22 13:27:39 +02005220sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5221 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5222{
5223 ALOGV("%s", __FUNCTION__);
5224 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5225
5226 status_t status = startAudioSource(source, attributes, &portId, uid);
5227 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5228 return mAudioSources.valueFor(portId);
5229}
5230
5231
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005232status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005233{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005234 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005235
5236 // make sure we only have one patch per source.
5237 disconnectAudioSource(sourceDesc);
5238
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005239 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005240 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5241 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5242 sourceDesc->srcDevice()->type(),
5243 String8(sourceDesc->srcDevice()->address().c_str()),
5244 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005245 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005246 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005247 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005248 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005249 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5250 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5251 return INVALID_OPERATION;
5252 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005253 PatchBuilder patchBuilder;
5254 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5255 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005256
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005257 return connectAudioSourceToSink(
5258 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005259}
5260
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005261status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005262{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005263 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5264 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005265 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005266 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005267 return BAD_VALUE;
5268 }
5269 status_t status = disconnectAudioSource(sourceDesc);
5270
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005271 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005272 return status;
5273}
5274
Andy Hung2ddee192015-12-18 17:34:44 -08005275status_t AudioPolicyManager::setMasterMono(bool mono)
5276{
5277 if (mMasterMono == mono) {
5278 return NO_ERROR;
5279 }
5280 mMasterMono = mono;
5281 // if enabling mono we close all offloaded devices, which will invalidate the
5282 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5283 // for recreating the new AudioTrack as non-offloaded PCM.
5284 //
5285 // If disabling mono, we leave all tracks as is: we don't know which clients
5286 // and tracks are able to be recreated as offloaded. The next "song" should
5287 // play back offloaded.
5288 if (mMasterMono) {
5289 Vector<audio_io_handle_t> offloaded;
5290 for (size_t i = 0; i < mOutputs.size(); ++i) {
5291 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5292 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5293 offloaded.push(desc->mIoHandle);
5294 }
5295 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005296 for (const auto& handle : offloaded) {
5297 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005298 }
5299 }
5300 // update master mono for all remaining outputs
5301 for (size_t i = 0; i < mOutputs.size(); ++i) {
5302 updateMono(mOutputs.keyAt(i));
5303 }
5304 return NO_ERROR;
5305}
5306
5307status_t AudioPolicyManager::getMasterMono(bool *mono)
5308{
5309 *mono = mMasterMono;
5310 return NO_ERROR;
5311}
5312
Eric Laurentac9cef52017-06-09 15:46:26 -07005313float AudioPolicyManager::getStreamVolumeDB(
5314 audio_stream_type_t stream, int index, audio_devices_t device)
5315{
jiabin9a3361e2019-10-01 09:38:30 -07005316 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005317}
5318
jiabin81772902018-04-02 17:52:27 -07005319status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5320 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005321 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005322{
Kriti Dang6537def2021-03-02 13:46:59 +01005323 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5324 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005325 return BAD_VALUE;
5326 }
Kriti Dang6537def2021-03-02 13:46:59 +01005327 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5328 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005329
5330 size_t formatsWritten = 0;
5331 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005332
Kriti Dang6537def2021-03-02 13:46:59 +01005333 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005334 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5335 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005336 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005337 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005338 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005339 bool formatEnabled = true;
5340 switch (forceUse) {
5341 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005342 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005343 break;
5344 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5345 formatEnabled = false;
5346 break;
5347 default: // AUTO or ALWAYS => true
5348 break;
jiabin81772902018-04-02 17:52:27 -07005349 }
5350 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5351 }
jiabin81772902018-04-02 17:52:27 -07005352 }
5353 return NO_ERROR;
5354}
5355
Kriti Dang6537def2021-03-02 13:46:59 +01005356status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5357 audio_format_t *surroundFormats) {
5358 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5359 return BAD_VALUE;
5360 }
5361 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5362 __func__, *numSurroundFormats, surroundFormats);
5363
5364 size_t formatsWritten = 0;
5365 size_t formatsMax = *numSurroundFormats;
5366 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5367
5368 // Return formats from all device profiles that have already been resolved by
5369 // checkOutputsForDevice().
5370 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5371 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5372 audio_devices_t deviceType = device->type();
5373 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5374 // returns formats reported by HDMI devices.
5375 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5376 continue;
5377 }
5378 // Formats reported by sink devices
5379 std::unordered_set<audio_format_t> formatset;
5380 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5381 formatset.insert(it->second.begin(), it->second.end());
5382 }
5383
5384 // Formats hard-coded in the in policy configuration file (if any).
5385 FormatVector encodedFormats = device->encodedFormats();
5386 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5387 // Filter the formats which are supported by the vendor hardware.
5388 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5389 if (mConfig.getSurroundFormats().count(*it) != 0) {
5390 formats.insert(*it);
5391 } else {
5392 for (const auto& pair : mConfig.getSurroundFormats()) {
5393 if (pair.second.count(*it) != 0) {
5394 formats.insert(pair.first);
5395 break;
5396 }
5397 }
5398 }
5399 }
5400 }
5401 *numSurroundFormats = formats.size();
5402 for (const auto& format: formats) {
5403 if (formatsWritten < formatsMax) {
5404 surroundFormats[formatsWritten++] = format;
5405 }
5406 }
5407 return NO_ERROR;
5408}
5409
jiabin81772902018-04-02 17:52:27 -07005410status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5411{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005412 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005413 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5414 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005415 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005416 return BAD_VALUE;
5417 }
5418
Mikhail Naganov100f0122018-11-29 11:22:16 -08005419 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5420 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005421 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005422 return INVALID_OPERATION;
5423 }
5424
Mikhail Naganov100f0122018-11-29 11:22:16 -08005425 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005426 return NO_ERROR;
5427 }
5428
Mikhail Naganov100f0122018-11-29 11:22:16 -08005429 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005430 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005431 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005432 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005433 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005434 }
5435 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005436 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005437 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005438 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005439 }
5440 }
5441
5442 sp<SwAudioOutputDescriptor> outputDesc;
5443 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005444 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5445 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005446 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5447 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005448 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005449 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005450 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5451 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5452 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005453 name.c_str(),
5454 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005455 if (status != NO_ERROR) {
5456 continue;
5457 }
5458 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5459 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5460 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005461 name.c_str(),
5462 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005463 profileUpdated |= (status == NO_ERROR);
5464 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005465 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005466 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005467 AUDIO_DEVICE_IN_HDMI);
5468 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5469 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005470 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005471 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005472 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5473 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5474 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005475 name.c_str(),
5476 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005477 if (status != NO_ERROR) {
5478 continue;
5479 }
5480 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5481 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5482 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005483 name.c_str(),
5484 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005485 profileUpdated |= (status == NO_ERROR);
5486 }
5487
jiabin81772902018-04-02 17:52:27 -07005488 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005489 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005490 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005491 }
5492
5493 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5494}
5495
Eric Laurent5ada82e2019-08-29 17:53:54 -07005496void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005497{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005498 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005499 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005500 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005501 }
5502}
5503
jiabin6012f912018-11-02 17:06:30 -07005504bool AudioPolicyManager::isHapticPlaybackSupported()
5505{
5506 for (const auto& hwModule : mHwModules) {
5507 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5508 for (const auto &outProfile : outputProfiles) {
5509 struct audio_port audioPort;
5510 outProfile->toAudioPort(&audioPort);
5511 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5512 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5513 return true;
5514 }
5515 }
5516 }
5517 }
5518 return false;
5519}
5520
Carter Hsu325a8eb2022-01-19 19:56:51 +08005521bool AudioPolicyManager::isUltrasoundSupported()
5522{
5523 bool hasUltrasoundOutput = false;
5524 bool hasUltrasoundInput = false;
5525 for (const auto& hwModule : mHwModules) {
5526 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5527 if (!hasUltrasoundOutput) {
5528 for (const auto &outProfile : outputProfiles) {
5529 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5530 hasUltrasoundOutput = true;
5531 break;
5532 }
5533 }
5534 }
5535
5536 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5537 if (!hasUltrasoundInput) {
5538 for (const auto &inputProfile : inputProfiles) {
5539 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5540 hasUltrasoundInput = true;
5541 break;
5542 }
5543 }
5544 }
5545
5546 if (hasUltrasoundOutput && hasUltrasoundInput)
5547 return true;
5548 }
5549 return false;
5550}
5551
Eric Laurent8340e672019-11-06 11:01:08 -08005552bool AudioPolicyManager::isCallScreenModeSupported()
5553{
5554 return getConfig().isCallScreenModeSupported();
5555}
5556
5557
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005558status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005559{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005560 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005561 if (!sourceDesc->isConnected()) {
5562 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5563 return NO_ERROR;
5564 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005565 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5566 if (swOutput != 0) {
5567 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005568 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005569 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005570 }
jiabinbce0c1d2020-10-05 11:20:18 -07005571 if (releaseOutput(sourceDesc->portId())) {
5572 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5573 // no need to release audio patch here but just return NO_ERROR.
5574 return NO_ERROR;
5575 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005576 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005577 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005578 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005579 // close Hwoutput and remove from mHwOutputs
5580 } else {
5581 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5582 }
5583 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005584 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005585 sourceDesc->disconnect();
5586 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005587}
5588
François Gaffiec005e562018-11-06 15:04:49 +01005589sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5590 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005591{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005592 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005593 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005594 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005595 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005596 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5597 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005598 source = sourceDesc;
5599 break;
5600 }
5601 }
5602 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005603}
5604
Eric Laurentb4f42a92022-01-17 17:37:31 +01005605bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005606 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005607 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005608{
5609 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5610 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005611 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005612 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005613 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5614 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5615 return false;
5616 }
5617 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5618 return false;
5619 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005620 }
5621
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005622 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005623 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005624 if (profile == nullptr) {
5625 return false;
5626 }
5627
5628 // The caller can have the audio config criteria ignored by either passing a null ptr or
5629 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005630 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005631 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005632
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005633 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005634 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005635 return false;
5636 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005637 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005638 return true;
5639}
5640
5641void AudioPolicyManager::checkVirtualizerClientRoutes() {
5642 std::set<audio_stream_type_t> streamsToInvalidate;
5643 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005644 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5645 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005646 audio_attributes_t attr = client->attributes();
5647 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5648 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5649 audio_config_base_t clientConfig = client->config();
5650 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005651 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005652 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005653 streamsToInvalidate.insert(client->stream());
5654 }
5655 }
5656 }
5657
5658 for (audio_stream_type_t stream : streamsToInvalidate) {
5659 mpClientInterface->invalidateStream(stream);
5660 }
5661}
5662
Eric Laurente191d1b2022-04-15 11:59:25 +02005663
5664bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5665 const sp<SwAudioOutputDescriptor>& outputDesc) {
5666 if (outputDesc->isDuplicated()) {
5667 return false;
5668 }
5669 DeviceVector devices = outputDesc->supportedDevices();
5670 for (size_t i = 0; i < mOutputs.size(); i++) {
5671 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5672 if (desc == outputDesc || desc->isDuplicated()) {
5673 continue;
5674 }
5675 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5676 if (!sharedDevices.isEmpty()
5677 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5678 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5679 return false;
5680 }
5681 }
5682 return true;
5683}
5684
5685
Eric Laurentfa0f6742021-08-17 18:39:44 +02005686status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005687 const audio_attributes_t *attr,
5688 audio_io_handle_t *output) {
5689 *output = AUDIO_IO_HANDLE_NONE;
5690
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005691 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5692 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5693 audio_config_t *configPtr = nullptr;
5694 audio_config_t config;
5695 if (mixerConfig != nullptr) {
5696 config = audio_config_initializer(mixerConfig);
5697 configPtr = &config;
5698 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005699 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005700 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005701 return BAD_VALUE;
5702 }
5703
5704 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005705 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005706 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005707 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005708 return BAD_VALUE;
5709 }
5710
Eric Laurente191d1b2022-04-15 11:59:25 +02005711 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005712 for (size_t i = 0; i < mOutputs.size(); i++) {
5713 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005714 if (!desc->isDuplicated()
5715 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5716 spatializerOutputs.push_back(desc);
5717 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005718 }
5719 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005720 mSpatializerOutput.clear();
5721 bool outputsChanged = false;
5722 for (const auto& desc : spatializerOutputs) {
5723 if (desc->mProfile == profile
5724 && (configPtr == nullptr
5725 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5726 mSpatializerOutput = desc;
5727 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5728 } else {
5729 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5730 " and devices %s", __func__, desc->mIoHandle,
5731 configPtr != nullptr ? configPtr->channel_mask : 0,
5732 devices.toString().c_str());
5733 closeOutput(desc->mIoHandle);
5734 outputsChanged = true;
5735 }
Eric Laurent39095982021-08-24 18:29:27 +02005736 }
5737
Eric Laurente191d1b2022-04-15 11:59:25 +02005738 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005739 sp<SwAudioOutputDescriptor> desc =
5740 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005741 if (desc != nullptr) {
5742 mSpatializerOutput = desc;
5743 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005744 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005745 }
5746
5747 checkVirtualizerClientRoutes();
5748
Eric Laurente191d1b2022-04-15 11:59:25 +02005749 if (outputsChanged) {
5750 mPreviousOutputs = mOutputs;
5751 mpClientInterface->onAudioPortListUpdate();
5752 }
5753
5754 if (mSpatializerOutput == nullptr) {
5755 ALOGV("%s could not open spatializer output with requested config", __func__);
5756 return BAD_VALUE;
5757 }
Eric Laurent39095982021-08-24 18:29:27 +02005758 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005759 ALOGV("%s returning new spatializer output %d", __func__, *output);
5760 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005761}
5762
Eric Laurentfa0f6742021-08-17 18:39:44 +02005763status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5764 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005765 return INVALID_OPERATION;
5766 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005767 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005768 return BAD_VALUE;
5769 }
Eric Laurent39095982021-08-24 18:29:27 +02005770
Eric Laurente191d1b2022-04-15 11:59:25 +02005771 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5772 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5773 closeOutput(mSpatializerOutput->mIoHandle);
5774 //from now on mSpatializerOutput is null
5775 checkVirtualizerClientRoutes();
5776 }
Eric Laurent39095982021-08-24 18:29:27 +02005777
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005778 return NO_ERROR;
5779}
5780
Eric Laurente552edb2014-03-10 17:42:56 -07005781// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005782// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005783// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005784uint32_t AudioPolicyManager::nextAudioPortGeneration()
5785{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005786 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005787}
5788
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005789static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005790 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5791 !audioPolicyXmlConfigFile.empty()) {
5792 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5793 if (ret == NO_ERROR) {
5794 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005795 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005796 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005797 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005798 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005799}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005800
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005801AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5802 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005803 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005804 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005805 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005806 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005807 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005808 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005809 mAudioPortGeneration(1),
5810 mBeaconMuteRefCount(0),
5811 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005812 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005813 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005814 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005815 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005816{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005817}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005818
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005819AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5820 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5821{
5822 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005823}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005824
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005825void AudioPolicyManager::loadConfig() {
5826 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005827 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005828 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005829 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005830}
5831
5832status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005833 {
5834 auto engLib = EngineLibrary::load(
5835 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5836 if (!engLib) {
5837 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5838 return NO_INIT;
5839 }
5840 mEngine = engLib->createEngine();
5841 if (mEngine == nullptr) {
5842 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5843 return NO_INIT;
5844 }
François Gaffie2110e042015-03-24 08:41:51 +01005845 }
5846 mEngine->setObserver(this);
5847 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005848 if (status != NO_ERROR) {
5849 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5850 return status;
5851 }
François Gaffie2110e042015-03-24 08:41:51 +01005852
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005853 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005854 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5855 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5856
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005857 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005858 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005859 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005860
Eric Laurent3a4311c2014-03-17 12:00:47 -07005861 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005862 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5863 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5864 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005865 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005866 }
jiabin9ff780e2018-03-19 18:19:52 -07005867 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005868 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005869 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005870 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005871 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005872 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005873 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005874 }
5875 }
5876 }
Eric Laurente552edb2014-03-10 17:42:56 -07005877
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005878 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005879
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005880 // Silence ALOGV statements
5881 property_set("log.tag." LOG_TAG, "D");
5882
Eric Laurente552edb2014-03-10 17:42:56 -07005883 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005884 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005885}
5886
Eric Laurente0720872014-03-11 09:30:41 -07005887AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005888{
Eric Laurente552edb2014-03-10 17:42:56 -07005889 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005890 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005891 }
5892 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005893 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005894 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005895 mAvailableOutputDevices.clear();
5896 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005897 mOutputs.clear();
5898 mInputs.clear();
5899 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005900 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005901 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005902}
5903
Eric Laurente0720872014-03-11 09:30:41 -07005904status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005905{
Eric Laurent87ffa392015-05-22 10:32:38 -07005906 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005907}
5908
Eric Laurente552edb2014-03-10 17:42:56 -07005909// ---
5910
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005911void AudioPolicyManager::onNewAudioModulesAvailable()
5912{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005913 DeviceVector newDevices;
5914 onNewAudioModulesAvailableInt(&newDevices);
5915 if (!newDevices.empty()) {
5916 nextAudioPortGeneration();
5917 mpClientInterface->onAudioPortListUpdate();
5918 }
5919}
5920
5921void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5922{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005923 for (const auto& hwModule : mHwModulesAll) {
5924 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5925 continue;
5926 }
5927 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5928 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5929 ALOGW("could not open HW module %s", hwModule->getName());
5930 continue;
5931 }
5932 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005933 // open all output streams needed to access attached devices.
5934 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005935 // This also validates mAvailableOutputDevices list
5936 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5937 if (!outProfile->canOpenNewIo()) {
5938 ALOGE("Invalid Output profile max open count %u for profile %s",
5939 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5940 continue;
5941 }
5942 if (!outProfile->hasSupportedDevices()) {
5943 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5944 continue;
5945 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005946 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5947 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005948 mTtsOutputAvailable = true;
5949 }
5950
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005951 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5952 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5953 sp<DeviceDescriptor> supportedDevice = 0;
5954 if (supportedDevices.contains(mDefaultOutputDevice)) {
5955 supportedDevice = mDefaultOutputDevice;
5956 } else {
5957 // choose first device present in profile's SupportedDevices also part of
5958 // mAvailableOutputDevices.
5959 if (availProfileDevices.isEmpty()) {
5960 continue;
5961 }
5962 supportedDevice = availProfileDevices.itemAt(0);
5963 }
5964 if (!mOutputDevicesAll.contains(supportedDevice)) {
5965 continue;
5966 }
5967 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5968 mpClientInterface);
5969 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005970 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5971 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005972 AUDIO_STREAM_DEFAULT,
5973 AUDIO_OUTPUT_FLAG_NONE, &output);
5974 if (status != NO_ERROR) {
5975 ALOGW("Cannot open output stream for devices %s on hw module %s",
5976 supportedDevice->toString().c_str(), hwModule->getName());
5977 continue;
5978 }
5979 for (const auto &device : availProfileDevices) {
5980 // give a valid ID to an attached device once confirmed it is reachable
5981 if (!device->isAttached()) {
5982 device->attach(hwModule);
5983 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005984 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005985 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005986 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5987 }
5988 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005989 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005990 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5991 mPrimaryOutput = outputDesc;
5992 }
Eric Laurent39095982021-08-24 18:29:27 +02005993 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005994 outputDesc->close();
5995 } else {
5996 addOutput(output, outputDesc);
5997 setOutputDevices(outputDesc,
5998 DeviceVector(supportedDevice),
5999 true,
6000 0,
6001 NULL);
6002 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006003 }
6004 // open input streams needed to access attached devices to validate
6005 // mAvailableInputDevices list
6006 for (const auto& inProfile : hwModule->getInputProfiles()) {
6007 if (!inProfile->canOpenNewIo()) {
6008 ALOGE("Invalid Input profile max open count %u for profile %s",
6009 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6010 continue;
6011 }
6012 if (!inProfile->hasSupportedDevices()) {
6013 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6014 continue;
6015 }
6016 // chose first device present in profile's SupportedDevices also part of
6017 // available input devices
6018 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6019 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6020 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006021 ALOGV("%s: Input device list is empty! for profile %s",
6022 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006023 continue;
6024 }
6025 sp<AudioInputDescriptor> inputDesc =
6026 new AudioInputDescriptor(inProfile, mpClientInterface);
6027
6028 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6029 status_t status = inputDesc->open(nullptr,
6030 availProfileDevices.itemAt(0),
6031 AUDIO_SOURCE_MIC,
6032 AUDIO_INPUT_FLAG_NONE,
6033 &input);
6034 if (status != NO_ERROR) {
6035 ALOGW("Cannot open input stream for device %s on hw module %s",
6036 availProfileDevices.toString().c_str(),
6037 hwModule->getName());
6038 continue;
6039 }
6040 for (const auto &device : availProfileDevices) {
6041 // give a valid ID to an attached device once confirmed it is reachable
6042 if (!device->isAttached()) {
6043 device->attach(hwModule);
6044 device->importAudioPortAndPickAudioProfile(inProfile, true);
6045 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006046 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006047 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6048 }
6049 }
6050 inputDesc->close();
6051 }
6052 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006053
6054 // Check if spatializer outputs can be closed until used.
6055 // mOutputs vector never contains duplicated outputs at this point.
6056 std::vector<audio_io_handle_t> outputsClosed;
6057 for (size_t i = 0; i < mOutputs.size(); i++) {
6058 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6059 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6060 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6061 outputsClosed.push_back(desc->mIoHandle);
6062 desc->close();
6063 }
6064 }
6065 for (auto output : outputsClosed) {
6066 removeOutput(output);
6067 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006068}
6069
Eric Laurent98e38192018-02-15 18:31:53 -08006070void AudioPolicyManager::addOutput(audio_io_handle_t output,
6071 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006072{
Eric Laurent1c333e22014-05-20 10:48:17 -07006073 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006074 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006075 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006076 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006077 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006078}
6079
François Gaffie53615e22015-03-19 09:24:12 +01006080void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6081{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006082 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6083 ALOGV("%s: removing primary output", __func__);
6084 mPrimaryOutput = nullptr;
6085 }
François Gaffie53615e22015-03-19 09:24:12 +01006086 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006087 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006088}
6089
Eric Laurent98e38192018-02-15 18:31:53 -08006090void AudioPolicyManager::addInput(audio_io_handle_t input,
6091 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006092{
Eric Laurent1c333e22014-05-20 10:48:17 -07006093 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006094 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006095}
Eric Laurente552edb2014-03-10 17:42:56 -07006096
François Gaffie11d30102018-11-02 16:09:09 +01006097status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006098 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006099 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006100{
François Gaffie11d30102018-11-02 16:09:09 +01006101 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006102 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006103 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006104
François Gaffie11d30102018-11-02 16:09:09 +01006105 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006106 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006107 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006108 }
Eric Laurente552edb2014-03-10 17:42:56 -07006109
Eric Laurent3b73df72014-03-11 09:06:29 -07006110 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006111 // first call getAudioPort to get the supported attributes from the HAL
6112 struct audio_port_v7 port = {};
6113 device->toAudioPort(&port);
6114 status_t status = mpClientInterface->getAudioPort(&port);
6115 if (status == NO_ERROR) {
6116 device->importAudioPort(port);
6117 }
6118
6119 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006120 for (size_t i = 0; i < mOutputs.size(); i++) {
6121 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006122 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006123 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006124 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6125 mOutputs.keyAt(i), device->toString().c_str());
6126 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006127 }
6128 }
6129 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006130 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006131 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006132 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6133 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006134 if (profile->supportsDevice(device)) {
6135 profiles.add(profile);
6136 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6137 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006138 }
6139 }
6140 }
6141
Eric Laurent7b279bb2015-12-14 10:18:23 -08006142 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006143
Eric Laurente552edb2014-03-10 17:42:56 -07006144 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006145 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006146 return BAD_VALUE;
6147 }
6148
6149 // open outputs for matching profiles if needed. Direct outputs are also opened to
6150 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6151 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006152 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006153
6154 // nothing to do if one output is already opened for this profile
6155 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006156 for (j = 0; j < outputs.size(); j++) {
6157 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006158 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006159 // matching profile: save the sample rates, format and channel masks supported
6160 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006161 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006162 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006163 }
Eric Laurente552edb2014-03-10 17:42:56 -07006164 break;
6165 }
6166 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006167 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006168 continue;
6169 }
6170
Eric Laurent3974e3b2017-12-07 17:58:43 -08006171 if (!profile->canOpenNewIo()) {
6172 ALOGW("Max Output number %u already opened for this profile %s",
6173 profile->maxOpenCount, profile->getTagName().c_str());
6174 continue;
6175 }
6176
Eric Laurent83efe1c2017-07-09 16:51:08 -07006177 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006178 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006179 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6180 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006181 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006182 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006183 profiles.removeAt(profile_index);
6184 profile_index--;
6185 } else {
6186 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006187 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006188 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006189 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6190 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006191 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006192 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006193
François Gaffie11d30102018-11-02 16:09:09 +01006194 if (device_distinguishes_on_address(deviceType)) {
6195 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6196 device->toString().c_str());
6197 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6198 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006199 }
Eric Laurente552edb2014-03-10 17:42:56 -07006200 ALOGV("checkOutputsForDevice(): adding output %d", output);
6201 }
6202 }
6203
6204 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006205 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006206 return BAD_VALUE;
6207 }
Eric Laurentd4692962014-05-05 18:13:44 -07006208 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006209 // check if one opened output is not needed any more after disconnecting one device
6210 for (size_t i = 0; i < mOutputs.size(); i++) {
6211 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006212 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006213 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006214 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006215 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006216 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006217 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006218 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6219 mOutputs.keyAt(i));
6220 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006221 }
Eric Laurente552edb2014-03-10 17:42:56 -07006222 }
6223 }
Eric Laurentd4692962014-05-05 18:13:44 -07006224 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006225 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006226 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6227 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006228 if (!profile->supportsDevice(device)) {
6229 continue;
6230 }
6231 ALOGV("checkOutputsForDevice(): "
6232 "clearing direct output profile %zu on module %s",
6233 j, hwModule->getName());
6234 profile->clearAudioProfiles();
6235 if (!profile->hasDynamicAudioProfile()) {
6236 continue;
6237 }
6238 // When a device is disconnected, if there is an IOProfile that contains dynamic
6239 // profiles and supports the disconnected device, call getAudioPort to repopulate
6240 // the capabilities of the devices that is supported by the IOProfile.
6241 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6242 if (supportedDevice == device ||
6243 !mAvailableOutputDevices.contains(supportedDevice)) {
6244 continue;
6245 }
6246 struct audio_port_v7 port;
6247 supportedDevice->toAudioPort(&port);
6248 status_t status = mpClientInterface->getAudioPort(&port);
6249 if (status == NO_ERROR) {
6250 supportedDevice->importAudioPort(port);
6251 }
Eric Laurente552edb2014-03-10 17:42:56 -07006252 }
6253 }
6254 }
6255 }
6256 return NO_ERROR;
6257}
6258
François Gaffie11d30102018-11-02 16:09:09 +01006259status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006260 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006261{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006262 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006263
François Gaffie11d30102018-11-02 16:09:09 +01006264 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006265 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006266 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006267 }
6268
Eric Laurentd4692962014-05-05 18:13:44 -07006269 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006270 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006271 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006272 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006273 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006274 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006275 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006276 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006277
François Gaffie11d30102018-11-02 16:09:09 +01006278 if (profile->supportsDevice(device)) {
6279 profiles.add(profile);
6280 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6281 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006282 }
6283 }
6284 }
6285
Eric Laurent0dd51852019-04-19 18:18:58 -07006286 if (profiles.isEmpty()) {
6287 ALOGW("%s: No input profile available for device %s",
6288 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006289 return BAD_VALUE;
6290 }
6291
6292 // open inputs for matching profiles if needed. Direct inputs are also opened to
6293 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6294 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6295
Eric Laurent1c333e22014-05-20 10:48:17 -07006296 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006297
Eric Laurentd4692962014-05-05 18:13:44 -07006298 // nothing to do if one input is already opened for this profile
6299 size_t input_index;
6300 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6301 desc = mInputs.valueAt(input_index);
6302 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006303 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006304 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006305 }
Eric Laurentd4692962014-05-05 18:13:44 -07006306 break;
6307 }
6308 }
6309 if (input_index != mInputs.size()) {
6310 continue;
6311 }
6312
Eric Laurent3974e3b2017-12-07 17:58:43 -08006313 if (!profile->canOpenNewIo()) {
6314 ALOGW("Max Input number %u already opened for this profile %s",
6315 profile->maxOpenCount, profile->getTagName().c_str());
6316 continue;
6317 }
6318
Eric Laurentfe231122017-11-17 17:48:06 -08006319 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006320 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006321 status_t status = desc->open(nullptr,
6322 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006323 AUDIO_SOURCE_MIC,
6324 AUDIO_INPUT_FLAG_NONE,
6325 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006326
Eric Laurentcf2c0212014-07-25 16:20:43 -07006327 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006328 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006329 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006330 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006331 mpClientInterface->setParameters(input, String8(param));
6332 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006333 }
François Gaffie11d30102018-11-02 16:09:09 +01006334 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006335 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006336 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006337 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006338 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006339 }
6340
Eric Laurent0dd51852019-04-19 18:18:58 -07006341 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006342 addInput(input, desc);
6343 }
6344 } // endif input != 0
6345
Eric Laurentcf2c0212014-07-25 16:20:43 -07006346 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006347 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006348 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006349 profiles.removeAt(profile_index);
6350 profile_index--;
6351 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006352 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006353 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006354 }
Eric Laurentd4692962014-05-05 18:13:44 -07006355 ALOGV("checkInputsForDevice(): adding input %d", input);
6356 }
6357 } // end scan profiles
6358
6359 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006360 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006361 return BAD_VALUE;
6362 }
6363 } else {
6364 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006365 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006366 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006367 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006368 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006369 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006370 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006371 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006372 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6373 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006374 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006375 }
6376 }
6377 }
6378 } // end disconnect
6379
6380 return NO_ERROR;
6381}
6382
6383
Eric Laurente0720872014-03-11 09:30:41 -07006384void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006385{
6386 ALOGV("closeOutput(%d)", output);
6387
François Gaffie1c878552018-11-22 16:53:21 +01006388 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6389 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006390 ALOGW("closeOutput() unknown output %d", output);
6391 return;
6392 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006393 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006394 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006395
Eric Laurente552edb2014-03-10 17:42:56 -07006396 // look for duplicated outputs connected to the output being removed.
6397 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006398 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6399 if (dupOutput->isDuplicated() &&
6400 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6401 sp<SwAudioOutputDescriptor> remainingOutput =
6402 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006403 // As all active tracks on duplicated output will be deleted,
6404 // and as they were also referenced on the other output, the reference
6405 // count for their stream type must be adjusted accordingly on
6406 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006407 const bool wasActive = remainingOutput->isActive();
6408 // Note: no-op on the closing output where all clients has already been set inactive
6409 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006410 // stop() will be a no op if the output is still active but is needed in case all
6411 // active streams refcounts where cleared above
6412 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006413 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006414 }
Eric Laurente552edb2014-03-10 17:42:56 -07006415 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6416 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6417
6418 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006419 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006420 }
6421 }
6422
Eric Laurent05b90f82014-08-27 15:32:29 -07006423 nextAudioPortGeneration();
6424
François Gaffie1c878552018-11-22 16:53:21 +01006425 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006426 if (index >= 0) {
6427 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006428 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6429 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006430 mAudioPatches.removeItemsAt(index);
6431 mpClientInterface->onAudioPatchListUpdate();
6432 }
6433
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006434 if (closingOutputWasActive) {
6435 closingOutput->stop();
6436 }
François Gaffie1c878552018-11-22 16:53:21 +01006437 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006438
François Gaffie53615e22015-03-19 09:24:12 +01006439 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006440 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006441 if (closingOutput == mSpatializerOutput) {
6442 mSpatializerOutput.clear();
6443 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006444
6445 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6446 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006447 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006448 bool directOutputOpen = false;
6449 for (size_t i = 0; i < mOutputs.size(); i++) {
6450 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6451 directOutputOpen = true;
6452 break;
6453 }
6454 }
6455 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006456 ALOGV("no direct outputs open, reset MSD patches");
6457 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6458 // how output devices for patching are resolved. Avoid by caching and reusing the
6459 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6460 // devices to patch to. This may be complicated by the fact that devices may become
6461 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006462 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006463 }
6464 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006465}
6466
6467void AudioPolicyManager::closeInput(audio_io_handle_t input)
6468{
6469 ALOGV("closeInput(%d)", input);
6470
6471 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6472 if (inputDesc == NULL) {
6473 ALOGW("closeInput() unknown input %d", input);
6474 return;
6475 }
6476
Eric Laurent6a94d692014-05-20 11:18:06 -07006477 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006478
François Gaffie11d30102018-11-02 16:09:09 +01006479 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006480 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006481 if (index >= 0) {
6482 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006483 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6484 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006485 mAudioPatches.removeItemsAt(index);
6486 mpClientInterface->onAudioPatchListUpdate();
6487 }
6488
Eric Laurentfe231122017-11-17 17:48:06 -08006489 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006490 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006491
François Gaffie11d30102018-11-02 16:09:09 +01006492 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6493 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006494 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006495 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006496 }
Eric Laurente552edb2014-03-10 17:42:56 -07006497}
6498
François Gaffie11d30102018-11-02 16:09:09 +01006499SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6500 const DeviceVector &devices,
6501 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006502{
6503 SortedVector<audio_io_handle_t> outputs;
6504
François Gaffie11d30102018-11-02 16:09:09 +01006505 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006506 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006507 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006508 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006509 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006510 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006511 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006512 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006513 outputs.add(openOutputs.keyAt(i));
6514 }
6515 }
6516 return outputs;
6517}
6518
Mikhail Naganov37977152018-07-11 15:54:44 -07006519void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6520{
6521 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6522 // output is suspended before any tracks are moved to it
6523 checkA2dpSuspend();
6524 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006525 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006526 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006527 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006528 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006529 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6530 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6531 // configuration changes will ultimately be rerouted correctly. We can still avoid
6532 // unnecessary rerouting by caching and reusing the arguments to
6533 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6534 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006535 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006536 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006537 // an event that changed routing likely occurred, inform upper layers
6538 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006539}
6540
François Gaffiec005e562018-11-06 15:04:49 +01006541bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6542 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006543{
François Gaffiec005e562018-11-06 15:04:49 +01006544 return mEngine->getProductStrategyForAttributes(lAttr) ==
6545 mEngine->getProductStrategyForAttributes(rAttr);
6546}
6547
Francois Gaffieff1eb522020-05-06 18:37:04 +02006548void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6549{
6550 for (size_t i = 0; i < mAudioSources.size(); i++) {
6551 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6552 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006553 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006554 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006555 connectAudioSource(sourceDesc);
6556 }
6557 }
6558}
6559
6560void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6561{
6562 for (size_t i = 0; i < mAudioSources.size(); i++) {
6563 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6564 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6565 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6566 disconnectAudioSource(sourceDesc);
6567 }
6568 }
6569}
6570
François Gaffiec005e562018-11-06 15:04:49 +01006571void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6572{
6573 auto psId = mEngine->getProductStrategyForAttributes(attr);
6574
6575 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6576 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006577
François Gaffie11d30102018-11-02 16:09:09 +01006578 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6579 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006580
Eric Laurentc209fe42020-06-05 18:11:23 -07006581 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006582 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006583 // take into account dynamic audio policies related changes: if a client is now associated
6584 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006585 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006586 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6587 if (desc->isDuplicated()) {
6588 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006589 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006590 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6591 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6592 continue;
6593 }
6594 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006595 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006596 client->uid(), client->session(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006597 if (status != OK) {
6598 continue;
6599 }
yucliuf4de36d2020-09-14 14:57:56 -07006600 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006601 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006602 maxLatency = desc->latency();
6603 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006604 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006605 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006606 }
6607 }
6608
Eric Laurent56ed8842022-11-15 16:04:41 +01006609 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006610 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6611 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006612 for (audio_io_handle_t srcOut : srcOutputs) {
6613 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006614 if (desc == nullptr) continue;
6615
6616 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006617 maxLatency = desc->latency();
6618 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006619
Eric Laurent56ed8842022-11-15 16:04:41 +01006620 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006621 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006622 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006623 // a client on a non direct outputs has necessarily a linear PCM format
6624 // so we can call selectOutput() safely
6625 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6626 client->flags(),
6627 client->config().format,
6628 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006629 client->config().sample_rate,
6630 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006631 if (newOutput != srcOut) {
6632 invalidate = true;
6633 break;
6634 }
6635 } else {
6636 sp<IOProfile> profile = getProfileForOutput(newDevices,
6637 client->config().sample_rate,
6638 client->config().format,
6639 client->config().channel_mask,
6640 client->flags(),
6641 true /* directOnly */);
6642 if (profile != desc->mProfile) {
6643 invalidate = true;
6644 break;
6645 }
6646 }
6647 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006648 // mute strategy while moving tracks from one output to another
6649 if (invalidate) {
6650 invalidatedOutputs.push_back(desc);
6651 if (desc->isStrategyActive(psId)) {
6652 setStrategyMute(psId, true, desc);
6653 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6654 newDevices.types());
6655 }
Eric Laurente552edb2014-03-10 17:42:56 -07006656 }
François Gaffiec005e562018-11-06 15:04:49 +01006657 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006658 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006659 connectAudioSource(source);
6660 }
Eric Laurente552edb2014-03-10 17:42:56 -07006661 }
6662
Eric Laurent56ed8842022-11-15 16:04:41 +01006663 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6664 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6665 std::to_string(srcOutputs[0]).c_str(),
6666 std::to_string(dstOutputs[0]).c_str());
6667
François Gaffiec005e562018-11-06 15:04:49 +01006668 // Move effects associated to this stream from previous output to new output
6669 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006670 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006671 }
François Gaffiec005e562018-11-06 15:04:49 +01006672 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006673 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006674 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6675 mpClientInterface->invalidateStream(stream);
6676 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006677 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006678 desc->setTracksInvalidatedStatusByStrategy(psId);
6679 }
Eric Laurente552edb2014-03-10 17:42:56 -07006680 }
6681 }
6682}
6683
Eric Laurente0720872014-03-11 09:30:41 -07006684void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006685{
François Gaffiec005e562018-11-06 15:04:49 +01006686 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6687 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6688 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006689 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006690 }
Eric Laurente552edb2014-03-10 17:42:56 -07006691}
6692
Kevin Rocard153f92d2018-12-18 18:33:28 -08006693void AudioPolicyManager::checkSecondaryOutputs() {
6694 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006695 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006696 for (size_t i = 0; i < mOutputs.size(); i++) {
6697 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6698 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006699 sp<AudioPolicyMix> primaryMix;
6700 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006701 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006702 client->uid(), client->session(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006703 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6704 for (auto &secondaryMix : secondaryMixes) {
6705 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6706 if (outputDesc != nullptr &&
6707 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6708 secondaryDescs.push_back(outputDesc);
6709 }
6710 }
6711
jiabin10a03f12021-05-07 23:46:28 +00006712 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006713 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006714 } else if (!std::equal(
6715 client->getSecondaryOutputs().begin(),
6716 client->getSecondaryOutputs().end(),
6717 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006718 if (!audio_is_linear_pcm(client->config().format)) {
6719 // If the format is not PCM, the tracks should be invalidated to get correct
6720 // behavior when the secondary output is changed.
6721 streamsToInvalidate.insert(client->stream());
6722 } else {
6723 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6724 std::vector<audio_io_handle_t> secondaryOutputIds;
6725 for (const auto &secondaryDesc: secondaryDescs) {
6726 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6727 weakSecondaryDescs.push_back(secondaryDesc);
6728 }
6729 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6730 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006731 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006732 }
6733 }
6734 }
jiabin10a03f12021-05-07 23:46:28 +00006735 if (!trackSecondaryOutputs.empty()) {
6736 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6737 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006738 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006739 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006740 mpClientInterface->invalidateStream(stream);
6741 }
6742}
6743
Eric Laurent2517af32020-11-25 15:31:27 +01006744bool AudioPolicyManager::isScoRequestedForComm() const {
6745 AudioDeviceTypeAddrVector devices;
6746 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6747 for (const auto &device : devices) {
6748 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6749 return true;
6750 }
6751 }
6752 return false;
6753}
6754
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006755bool AudioPolicyManager::isHearingAidUsedForComm() const {
6756 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6757 true /*fromCache*/);
6758 for (const auto &device : devices) {
6759 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6760 return true;
6761 }
6762 }
6763 return false;
6764}
6765
6766
Eric Laurente0720872014-03-11 09:30:41 -07006767void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006768{
François Gaffie53615e22015-03-19 09:24:12 +01006769 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006770 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006771 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006772 return;
6773 }
6774
Eric Laurent3a4311c2014-03-17 12:00:47 -07006775 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006776 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6777 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006778 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006779
6780 // if suspended, restore A2DP output if:
6781 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006782 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006783 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006784 //
Eric Laurentf732e072016-08-03 19:30:28 -07006785 // if not suspended, suspend A2DP output if:
6786 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006787 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006788 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006789 //
6790 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006791 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006792 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006793 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006794 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006795
6796 mpClientInterface->restoreOutput(a2dpOutput);
6797 mA2dpSuspended = false;
6798 }
6799 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006800 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006801 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006802 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006803 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006804
6805 mpClientInterface->suspendOutput(a2dpOutput);
6806 mA2dpSuspended = true;
6807 }
6808 }
6809}
6810
François Gaffie11d30102018-11-02 16:09:09 +01006811DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6812 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006813{
François Gaffie11d30102018-11-02 16:09:09 +01006814 DeviceVector devices;
6815
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006816 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006817 if (index >= 0) {
6818 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006819 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006820 ALOGV("%s device %s forced by patch %d", __func__,
6821 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6822 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006823 }
6824 }
6825
Dean Wheatley514b4312020-06-17 21:45:00 +10006826 // Do not retrieve engine device for outputs through MSD
6827 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6828 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6829 return outputDesc->devices();
6830 }
6831
Eric Laurent97ac8712018-07-27 18:59:02 -07006832 // Honor explicit routing requests only if no client using default routing is active on this
6833 // input: a specific app can not force routing for other apps by setting a preferred device.
6834 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006835 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006836 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006837 if (device != nullptr) {
6838 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006839 }
6840
François Gaffiea807ef92018-11-05 10:44:33 +01006841 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6842 // of setForceUse / Default Bus device here
6843 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6844 if (device != nullptr) {
6845 return DeviceVector(device);
6846 }
6847
François Gaffiec005e562018-11-06 15:04:49 +01006848 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6849 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6850 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306851 auto hasStreamActive = [&](auto stream) {
6852 return hasStream(streams, stream) && isStreamActive(stream, 0);
6853 };
Eric Laurent484e9272018-06-07 17:29:23 -07006854
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306855 auto doGetOutputDevicesForVoice = [&]() {
6856 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006857 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306858 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006859 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6860 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306861 };
6862
6863 // With low-latency playing on speaker, music on WFD, when the first low-latency
6864 // output is stopped, getNewOutputDevices checks for a product strategy
6865 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006866 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306867 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6868 // stream is associated to the output descriptor.
6869 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6870 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6871 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6872 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006873 // Retrieval of devices for voice DL is done on primary output profile, cannot
6874 // check the route (would force modifying configuration file for this profile)
6875 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6876 break;
6877 }
Eric Laurente552edb2014-03-10 17:42:56 -07006878 }
François Gaffiec005e562018-11-06 15:04:49 +01006879 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006880 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006881}
6882
François Gaffie11d30102018-11-02 16:09:09 +01006883sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6884 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006885{
François Gaffie11d30102018-11-02 16:09:09 +01006886 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006887
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006888 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006889 if (index >= 0) {
6890 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006891 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006892 ALOGV("getNewInputDevice() device %s forced by patch %d",
6893 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6894 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006895 }
6896 }
6897
Eric Laurent97ac8712018-07-27 18:59:02 -07006898 // Honor explicit routing requests only if no client using default routing is active on this
6899 // input: a specific app can not force routing for other apps by setting a preferred device.
6900 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006901 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6902 if (device != nullptr) {
6903 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006904 }
6905
Eric Laurentdc95a252018-04-12 12:46:56 -07006906 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006907 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006908 audio_attributes_t attributes;
6909 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006910 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006911 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6912 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006913 attributes = topClient->attributes();
6914 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006915 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006916 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006917 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6918 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006919 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006920 }
6921
Francois Gaffie716e1432019-01-14 16:58:59 +01006922 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6923 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006924 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006925 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006926 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006927 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006928
Eric Laurente552edb2014-03-10 17:42:56 -07006929 return device;
6930}
6931
Eric Laurent794fde22016-03-11 09:50:45 -08006932bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6933 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006934 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006935}
6936
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006937status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006938 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006939 if (devices == nullptr) {
6940 return BAD_VALUE;
6941 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006942
Andy Hung6d23c0f2022-02-16 09:37:15 -08006943 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07006944 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
6945 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08006946 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006947 for (const auto& device : curDevices) {
6948 devices->push_back(device->getDeviceTypeAddr());
6949 }
6950 return NO_ERROR;
6951}
6952
Eric Laurente0720872014-03-11 09:30:41 -07006953void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006954 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006955 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006956 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006957 updateDevicesAndOutputs();
6958 break;
6959 default:
6960 break;
6961 }
6962}
6963
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006964uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006965
6966 // skip beacon mute management if a dedicated TTS output is available
6967 if (mTtsOutputAvailable) {
6968 return 0;
6969 }
6970
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006971 switch(event) {
6972 case STARTING_OUTPUT:
6973 mBeaconMuteRefCount++;
6974 break;
6975 case STOPPING_OUTPUT:
6976 if (mBeaconMuteRefCount > 0) {
6977 mBeaconMuteRefCount--;
6978 }
6979 break;
6980 case STARTING_BEACON:
6981 mBeaconPlayingRefCount++;
6982 break;
6983 case STOPPING_BEACON:
6984 if (mBeaconPlayingRefCount > 0) {
6985 mBeaconPlayingRefCount--;
6986 }
6987 break;
6988 }
6989
6990 if (mBeaconMuteRefCount > 0) {
6991 // any playback causes beacon to be muted
6992 return setBeaconMute(true);
6993 } else {
6994 // no other playback: unmute when beacon starts playing, mute when it stops
6995 return setBeaconMute(mBeaconPlayingRefCount == 0);
6996 }
6997}
6998
6999uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7000 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7001 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7002 // keep track of muted state to avoid repeating mute/unmute operations
7003 if (mBeaconMuted != mute) {
7004 // mute/unmute AUDIO_STREAM_TTS on all outputs
7005 ALOGV("\t muting %d", mute);
7006 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007007 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7008 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7009 ALOGV("\t no tts volume source available");
7010 return 0;
7011 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007012 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007013 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007014 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007015 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007016 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007017 maxLatency = latency;
7018 }
7019 }
7020 mBeaconMuted = mute;
7021 return maxLatency;
7022 }
7023 return 0;
7024}
7025
Eric Laurente0720872014-03-11 09:30:41 -07007026void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007027{
François Gaffiec005e562018-11-06 15:04:49 +01007028 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007029 mPreviousOutputs = mOutputs;
7030}
7031
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007032uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007033 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007034 uint32_t delayMs)
7035{
7036 // mute/unmute strategies using an incompatible device combination
7037 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7038 // if unmuting, unmute only after the specified delay
7039 if (outputDesc->isDuplicated()) {
7040 return 0;
7041 }
7042
7043 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007044 DeviceVector devices = outputDesc->devices();
7045 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007046
François Gaffiec005e562018-11-06 15:04:49 +01007047 auto productStrategies = mEngine->getOrderedProductStrategies();
7048 for (const auto &productStrategy : productStrategies) {
7049 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7050 DeviceVector curDevices =
7051 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7052 curDevices = curDevices.filter(outputDesc->supportedDevices());
7053 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007054 bool doMute = false;
7055
François Gaffiec005e562018-11-06 15:04:49 +01007056 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007057 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007058 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7059 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007060 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007061 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007062 }
Eric Laurent99401132014-05-07 19:48:15 -07007063 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007064 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007065 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007066 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007067 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007068 continue;
7069 }
François Gaffiec005e562018-11-06 15:04:49 +01007070 ALOGVV("%s() %s (curDevice %s)", __func__,
7071 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7072 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7073 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007074 if (mute) {
7075 // FIXME: should not need to double latency if volume could be applied
7076 // immediately by the audioflinger mixer. We must account for the delay
7077 // between now and the next time the audioflinger thread for this output
7078 // will process a buffer (which corresponds to one buffer size,
7079 // usually 1/2 or 1/4 of the latency).
7080 if (muteWaitMs < desc->latency() * 2) {
7081 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007082 }
7083 }
7084 }
7085 }
7086 }
7087 }
7088
Eric Laurent99401132014-05-07 19:48:15 -07007089 // temporary mute output if device selection changes to avoid volume bursts due to
7090 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007091 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007092 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007093
Eric Laurentdc462862016-07-19 12:29:53 -07007094 if (muteWaitMs < tempMuteWaitMs) {
7095 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007096 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007097
7098 // If recommended duration is defined, replace temporary mute duration to avoid
7099 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7100 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7101 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7102 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7103 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7104
François Gaffieaaac0fd2018-11-22 17:56:39 +01007105 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7106 // make sure that we do not start the temporary mute period too early in case of
7107 // delayed device change
7108 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7109 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007110 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007111 }
7112 }
7113
Eric Laurente552edb2014-03-10 17:42:56 -07007114 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7115 if (muteWaitMs > delayMs) {
7116 muteWaitMs -= delayMs;
7117 usleep(muteWaitMs * 1000);
7118 return muteWaitMs;
7119 }
7120 return 0;
7121}
7122
François Gaffie11d30102018-11-02 16:09:09 +01007123uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7124 const DeviceVector &devices,
7125 bool force,
7126 int delayMs,
7127 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007128 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007129{
François Gaffie11d30102018-11-02 16:09:09 +01007130 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007131 uint32_t muteWaitMs;
7132
7133 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007134 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7135 nullptr /* patchHandle */, requiresMuteCheck);
7136 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7137 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007138 return muteWaitMs;
7139 }
Eric Laurente552edb2014-03-10 17:42:56 -07007140
7141 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007142 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007143 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007144 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007145
François Gaffie11d30102018-11-02 16:09:09 +01007146 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7147
7148 if (!filteredDevices.isEmpty()) {
7149 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007150 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007151
7152 // if the outputs are not materially active, there is no need to mute.
7153 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007154 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007155 } else {
7156 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7157 muteWaitMs = 0;
7158 }
Eric Laurente552edb2014-03-10 17:42:56 -07007159
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007160 bool outputRouted = outputDesc->isRouted();
7161
Eric Laurent79ea9582020-06-11 18:49:24 -07007162 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7163 // output profile or if new device is not supported AND previous device(s) is(are) still
7164 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007165 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007166 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7167 // restore previous device after evaluating strategy mute state
7168 outputDesc->setDevices(prevDevices);
7169 return muteWaitMs;
7170 }
7171
Eric Laurente552edb2014-03-10 17:42:56 -07007172 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007173 // the requested device is AUDIO_DEVICE_NONE
7174 // OR the requested device is the same as current device
7175 // AND force is not specified
7176 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007177 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007178 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007179 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7180 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007181 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7182 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7183 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7184 }
Eric Laurente552edb2014-03-10 17:42:56 -07007185 return muteWaitMs;
7186 }
7187
François Gaffie11d30102018-11-02 16:09:09 +01007188 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007189
Eric Laurente552edb2014-03-10 17:42:56 -07007190 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007191 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007192 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007193 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007194 PatchBuilder patchBuilder;
7195 patchBuilder.addSource(outputDesc);
7196 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7197 for (const auto &filteredDevice : filteredDevices) {
7198 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007199 }
7200
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007201 // Add half reported latency to delayMs when muteWaitMs is null in order
7202 // to avoid disordered sequence of muting volume and changing devices.
7203 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7204 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007205 }
Eric Laurente552edb2014-03-10 17:42:56 -07007206
7207 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007208 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007209
7210 return muteWaitMs;
7211}
7212
Eric Laurentc75307b2015-03-17 15:29:32 -07007213status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007214 int delayMs,
7215 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007216{
Eric Laurent6a94d692014-05-20 11:18:06 -07007217 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007218 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7219 return INVALID_OPERATION;
7220 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007221 if (patchHandle) {
7222 index = mAudioPatches.indexOfKey(*patchHandle);
7223 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007224 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007225 }
7226 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007227 return INVALID_OPERATION;
7228 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007229 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007230 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007231 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007232 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007233 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007234 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007235 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007236 return status;
7237}
7238
7239status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007240 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007241 bool force,
7242 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007243{
7244 status_t status = NO_ERROR;
7245
Eric Laurent1f2f2232014-06-02 12:01:23 -07007246 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007247 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7248 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007249
François Gaffie11d30102018-11-02 16:09:09 +01007250 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007251 PatchBuilder patchBuilder;
7252 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007253 // AUDIO_SOURCE_HOTWORD is for internal use only:
7254 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007255 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7256 auto result = usecase;
7257 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7258 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7259 }
7260 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007261 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007262 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007263 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007264 }
7265 }
7266 return status;
7267}
7268
Eric Laurent6a94d692014-05-20 11:18:06 -07007269status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7270 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007271{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007272 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007273 ssize_t index;
7274 if (patchHandle) {
7275 index = mAudioPatches.indexOfKey(*patchHandle);
7276 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007277 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007278 }
7279 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007280 return INVALID_OPERATION;
7281 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007282 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007283 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007284 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007285 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007286 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007287 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007288 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007289 return status;
7290}
7291
François Gaffie11d30102018-11-02 16:09:09 +01007292sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007293 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007294 audio_format_t& format,
7295 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007296 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007297{
7298 // Choose an input profile based on the requested capture parameters: select the first available
7299 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007300 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007301 //
7302 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7303 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007304
jiabin2fd710d2022-05-02 23:20:22 +00007305 const audio_input_flags_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ;
7306 const audio_input_flags_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007307
jiabin2fd710d2022-05-02 23:20:22 +00007308 for (;;) {
7309 sp<IOProfile> firstInexact = nullptr;
7310 uint32_t updatedSamplingRate = 0;
7311 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7312 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7313 for (const auto& hwModule : mHwModules) {
7314 for (const auto& profile : hwModule->getInputProfiles()) {
7315 // profile->log();
7316 //updatedFormat = format;
7317 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7318 &samplingRate /*updatedSamplingRate*/,
7319 format,
7320 &format, /*updatedFormat*/
7321 channelMask,
7322 &channelMask /*updatedChannelMask*/,
7323 // FIXME ugly cast
7324 (audio_output_flags_t) flags,
7325 true /*exactMatchRequiredForInputFlags*/)) {
7326 return profile;
7327 }
7328 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7329 samplingRate,
7330 &updatedSamplingRate,
7331 format,
7332 &updatedFormat,
7333 channelMask,
7334 &updatedChannelMask,
7335 // FIXME ugly cast
7336 (audio_output_flags_t) flags,
7337 false /*exactMatchRequiredForInputFlags*/)) {
7338 firstInexact = profile;
7339 }
7340 }
7341 }
7342
7343 if (firstInexact != nullptr) {
7344 samplingRate = updatedSamplingRate;
7345 format = updatedFormat;
7346 channelMask = updatedChannelMask;
7347 return firstInexact;
7348 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7349 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7350 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7351 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7352 flags = AUDIO_INPUT_FLAG_NONE;
7353 } else { // fail
7354 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7355 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7356 samplingRate, format, channelMask, oriFlags);
7357 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007358 }
7359 }
jiabin2fd710d2022-05-02 23:20:22 +00007360
7361 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007362}
7363
François Gaffieaaac0fd2018-11-22 17:56:39 +01007364float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7365 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007366 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007367 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007368{
jiabin9a3361e2019-10-01 09:38:30 -07007369 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007370
7371 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7372 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7373 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7374 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007375 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7376 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7377 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7378 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7379 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007380
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007381 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007382 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7383 mOutputs.isActive(ringVolumeSrc, 0)) {
7384 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007385 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007386 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007387 }
7388
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007389 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007390 if ((volumeSource != callVolumeSrc && (isInCall() ||
7391 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007392 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007393 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7394 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007395 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7396 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7397 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007398 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007399 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007400 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007401 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007402 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007403 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007404 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7405 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7406 // programmatically muted.
7407 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7408 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7409 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007410 bool exemptFromCapping =
7411 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7412 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007413 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7414 volumeSource, volumeDb);
7415 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007416 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7417 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7418 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007419 }
7420 }
Eric Laurente552edb2014-03-10 17:42:56 -07007421 // if a headset is connected, apply the following rules to ring tones and notifications
7422 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007423 // - always attenuate notifications volume by 6dB
7424 // - attenuate ring tones volume by 6dB unless music is not playing and
7425 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007426 // - if music is playing, always limit the volume to current music volume,
7427 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007428 if (!Intersection(deviceTypes,
7429 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7430 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007431 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7432 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007433 ((volumeSource == alarmVolumeSrc ||
7434 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007435 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7436 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7437 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007438 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7439 curves.canBeMuted()) {
7440
Eric Laurente552edb2014-03-10 17:42:56 -07007441 // when the phone is ringing we must consider that music could have been paused just before
7442 // by the music application and behave as if music was active if the last music track was
7443 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007444 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007445 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007446 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007447 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007448 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7449 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007450 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007451 float musicVolDb = computeVolume(musicCurves,
7452 musicVolumeSrc,
7453 musicCurves.getVolumeIndex(musicDevice),
7454 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007455 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7456 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7457 if (volumeDb > minVolDb) {
7458 volumeDb = minVolDb;
7459 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007460 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007461 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7462 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7463 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007464 // on A2DP, also ensure notification volume is not too low compared to media when
7465 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007466 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007467 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007468 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7469 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007470 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7471 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007472 }
7473 }
jiabin9a3361e2019-10-01 09:38:30 -07007474 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007475 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007476 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007477 }
7478 }
7479
François Gaffie43c73442018-11-08 08:21:55 +01007480 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007481}
7482
Eric Laurent3839bc02018-07-10 18:33:34 -07007483int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007484 VolumeSource fromVolumeSource,
7485 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007486{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007487 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007488 return srcIndex;
7489 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007490 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7491 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007492 float minSrc = (float)srcCurves.getVolumeIndexMin();
7493 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7494 float minDst = (float)dstCurves.getVolumeIndexMin();
7495 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007496
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007497 // preserve mute request or correct range
7498 if (srcIndex < minSrc) {
7499 if (srcIndex == 0) {
7500 return 0;
7501 }
7502 srcIndex = minSrc;
7503 } else if (srcIndex > maxSrc) {
7504 srcIndex = maxSrc;
7505 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007506 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7507}
7508
François Gaffieaaac0fd2018-11-22 17:56:39 +01007509status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7510 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007511 int index,
7512 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007513 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007514 int delayMs,
7515 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007516{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007517 // do not change actual attributes volume if the attributes is muted
7518 if (outputDesc->isMuted(volumeSource)) {
7519 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7520 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007521 return NO_ERROR;
7522 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007523 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7524 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7525 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7526 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007527
Eric Laurent2517af32020-11-25 15:31:27 +01007528 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007529 bool isHAUsed = isHearingAidUsedForComm();
7530
Eric Laurente552edb2014-03-10 17:42:56 -07007531 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007532 // if sco and call follow same curves, bypass forceUseForComm
7533 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007534 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007535 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007536 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007537 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007538 // Do not return an error here as AudioService will always set both voice call
7539 // and bluetooth SCO volumes due to stream aliasing.
7540 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007541 }
jiabin9a3361e2019-10-01 09:38:30 -07007542 if (deviceTypes.empty()) {
7543 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007544 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007545
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007546 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7547 ALOGE("invalid volume index range");
7548 return BAD_VALUE;
7549 }
7550
jiabin9a3361e2019-10-01 09:38:30 -07007551 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7552 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007553 // Force VoIP volume to max for bluetooth SCO device except if muted
7554 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007555 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007556 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007557 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007558 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007559 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007560 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007561
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007562 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007563 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007564 // 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 +01007565 if (isVoiceVolSrc) {
7566 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007567 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007568 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007569 }
Eric Laurent18fba842016-03-31 14:41:26 -07007570 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007571 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7572 mLastVoiceVolume = voiceVolume;
7573 }
7574 }
Eric Laurente552edb2014-03-10 17:42:56 -07007575 return NO_ERROR;
7576}
7577
Eric Laurentc75307b2015-03-17 15:29:32 -07007578void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007579 const DeviceTypeSet& deviceTypes,
7580 int delayMs,
7581 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007582{
jiabincd510522020-01-22 09:40:55 -08007583 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007584 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7585 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7586 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007587 curves.getVolumeIndex(deviceTypes),
7588 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007589 }
7590}
7591
François Gaffiec005e562018-11-06 15:04:49 +01007592void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7593 bool on,
7594 const sp<AudioOutputDescriptor>& outputDesc,
7595 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007596 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007597{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007598 std::vector<VolumeSource> sourcesToMute;
7599 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7600 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7601 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007602 VolumeSource source = toVolumeSource(attributes, false);
7603 if ((source != VOLUME_SOURCE_NONE) &&
7604 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7605 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007606 sourcesToMute.push_back(source);
7607 }
Eric Laurente552edb2014-03-10 17:42:56 -07007608 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007609 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007610 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007611 }
7612
Eric Laurente552edb2014-03-10 17:42:56 -07007613}
7614
François Gaffieaaac0fd2018-11-22 17:56:39 +01007615void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7616 bool on,
7617 const sp<AudioOutputDescriptor>& outputDesc,
7618 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007619 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007620{
jiabin9a3361e2019-10-01 09:38:30 -07007621 if (deviceTypes.empty()) {
7622 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007623 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007624 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007625 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007626 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007627 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007628 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007629 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7630 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007631 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007632 }
7633 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007634 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7635 // ignored
7636 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007637 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007638 if (!outputDesc->isMuted(volumeSource)) {
7639 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007640 return;
7641 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007642 if (outputDesc->decMuteCount(volumeSource) == 0) {
7643 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007644 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007645 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007646 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007647 delayMs);
7648 }
7649 }
7650}
7651
François Gaffie53615e22015-03-19 09:24:12 +01007652bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7653{
François Gaffiec005e562018-11-06 15:04:49 +01007654 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007655 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7656 return true;
7657 }
7658
7659 // has known usage?
7660 switch (paa->usage) {
7661 case AUDIO_USAGE_UNKNOWN:
7662 case AUDIO_USAGE_MEDIA:
7663 case AUDIO_USAGE_VOICE_COMMUNICATION:
7664 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7665 case AUDIO_USAGE_ALARM:
7666 case AUDIO_USAGE_NOTIFICATION:
7667 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7668 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7669 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7670 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7671 case AUDIO_USAGE_NOTIFICATION_EVENT:
7672 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7673 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7674 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7675 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007676 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007677 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007678 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007679 case AUDIO_USAGE_EMERGENCY:
7680 case AUDIO_USAGE_SAFETY:
7681 case AUDIO_USAGE_VEHICLE_STATUS:
7682 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007683 break;
7684 default:
7685 return false;
7686 }
7687 return true;
7688}
7689
François Gaffie2110e042015-03-24 08:41:51 +01007690audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7691{
7692 return mEngine->getForceUse(usage);
7693}
7694
Eric Laurent96d1dda2022-03-14 17:14:19 +01007695bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007696 return isStateInCall(mEngine->getPhoneState());
7697}
7698
Eric Laurent96d1dda2022-03-14 17:14:19 +01007699bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007700 return is_state_in_call(state);
7701}
7702
Eric Laurent74b71512019-11-06 17:21:57 -08007703bool AudioPolicyManager::isCallAudioAccessible()
7704{
7705 audio_mode_t mode = mEngine->getPhoneState();
7706 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007707 || (mode == AUDIO_MODE_CALL_SCREEN)
7708 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007709}
7710
Eric Laurentd60560a2015-04-10 11:31:20 -07007711void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7712{
7713 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007714 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007715 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007716 sourceDesc->sinkDevice()->equals(deviceDesc))
7717 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007718 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007719 }
7720 }
7721
7722 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7723 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7724 bool release = false;
7725 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7726 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7727 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7728 source->ext.device.type == deviceDesc->type()) {
7729 release = true;
7730 }
7731 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007732 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007733 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7734 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7735 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007736 sink->ext.device.type == deviceDesc->type() &&
7737 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7738 || strncmp(sink->ext.device.address, address,
7739 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007740 release = true;
7741 }
7742 }
7743 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007744 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7745 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007746 }
7747 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007748
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007749 mInputs.clearSessionRoutesForDevice(deviceDesc);
7750
Francois Gaffie716e1432019-01-14 16:58:59 +01007751 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007752}
7753
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007754void AudioPolicyManager::modifySurroundFormats(
7755 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007756 std::unordered_set<audio_format_t> enforcedSurround(
7757 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007758 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7759 for (const auto& pair : mConfig.getSurroundFormats()) {
7760 allSurround.insert(pair.first);
7761 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7762 }
Phil Burk09bc4612016-02-24 15:58:15 -08007763
7764 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7765 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007766 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007767 // This is the resulting set of formats depending on the surround mode:
7768 // 'all surround' = allSurround
7769 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7770 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7771 // 'manual surround' = mManualSurroundFormats
7772 // AUTO: formats v 'enforced surround'
7773 // ALWAYS: formats v 'all surround' v 'enforced surround'
7774 // NEVER: formats ^ 'non-surround'
7775 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007776
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007777 std::unordered_set<audio_format_t> formatSet;
7778 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7779 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007780 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007781 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007782 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007783 formatSet.insert(*formatIter);
7784 }
7785 }
7786 } else {
7787 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7788 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007789 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007790
jiabin81772902018-04-02 17:52:27 -07007791 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007792 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007793 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7794 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7795 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007796 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007797 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7798 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7799 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007800 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007801 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007802 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007803 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007804 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007805 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007806}
7807
jiabin06e4bab2019-07-29 10:13:34 -07007808void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7809 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007810 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7811 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7812
7813 // If NEVER, then remove support for channelMasks > stereo.
7814 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007815 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7816 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007817 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007818 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007819 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007820 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007821 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007822 }
7823 }
jiabin81772902018-04-02 17:52:27 -07007824 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7825 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7826 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007827 bool supports5dot1 = false;
7828 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007829 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007830 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7831 supports5dot1 = true;
7832 break;
7833 }
7834 }
7835 // If not then add 5.1 support.
7836 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007837 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007838 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007839 }
Phil Burk09bc4612016-02-24 15:58:15 -08007840 }
7841}
7842
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007843void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007844 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007845 AudioProfileVector &profiles)
7846{
7847 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007848 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007849
François Gaffie112b0af2015-11-19 16:13:25 +01007850 // Format MUST be checked first to update the list of AudioProfile
7851 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007852 reply = mpClientInterface->getParameters(
7853 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007854 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007855 AudioParameter repliedParameters(reply);
7856 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007857 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007858 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7859 return;
7860 }
Phil Burk09bc4612016-02-24 15:58:15 -08007861 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007862 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007863 if (device == AUDIO_DEVICE_OUT_HDMI
7864 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007865 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007866 }
jiabin3e277cc2019-09-10 14:27:34 -07007867 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007868 }
François Gaffie112b0af2015-11-19 16:13:25 +01007869
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007870 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007871 ChannelMaskSet channelMasks;
7872 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007873 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007874 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007875
7876 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007877 reply = mpClientInterface->getParameters(
7878 ioHandle,
7879 requestedParameters.toString() + ";" +
7880 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007881 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007882 AudioParameter repliedParameters(reply);
7883 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007884 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007885 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007886 }
7887 }
7888 if (profiles.hasDynamicChannelsFor(format)) {
7889 reply = mpClientInterface->getParameters(ioHandle,
7890 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007891 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007892 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007893 AudioParameter repliedParameters(reply);
7894 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007895 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007896 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007897 if (device == AUDIO_DEVICE_OUT_HDMI
7898 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007899 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007900 }
François Gaffie112b0af2015-11-19 16:13:25 +01007901 }
7902 }
jiabin3e277cc2019-09-10 14:27:34 -07007903 addDynamicAudioProfileAndSort(
7904 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007905 }
7906}
Eric Laurentd60560a2015-04-10 11:31:20 -07007907
Mikhail Naganovdc769682018-05-04 15:34:08 -07007908status_t AudioPolicyManager::installPatch(const char *caller,
7909 audio_patch_handle_t *patchHandle,
7910 AudioIODescriptorInterface *ioDescriptor,
7911 const struct audio_patch *patch,
7912 int delayMs)
7913{
7914 ssize_t index = mAudioPatches.indexOfKey(
7915 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7916 *patchHandle : ioDescriptor->getPatchHandle());
7917 sp<AudioPatch> patchDesc;
7918 status_t status = installPatch(
7919 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7920 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007921 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007922 }
7923 return status;
7924}
7925
7926status_t AudioPolicyManager::installPatch(const char *caller,
7927 ssize_t index,
7928 audio_patch_handle_t *patchHandle,
7929 const struct audio_patch *patch,
7930 int delayMs,
7931 uid_t uid,
7932 sp<AudioPatch> *patchDescPtr)
7933{
7934 sp<AudioPatch> patchDesc;
7935 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7936 if (index >= 0) {
7937 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007938 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007939 }
7940
7941 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7942 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7943 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7944 if (status == NO_ERROR) {
7945 if (index < 0) {
7946 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007947 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007948 } else {
7949 patchDesc->mPatch = *patch;
7950 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007951 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007952 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007953 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007954 }
7955 nextAudioPortGeneration();
7956 mpClientInterface->onAudioPatchListUpdate();
7957 }
7958 if (patchDescPtr) *patchDescPtr = patchDesc;
7959 return status;
7960}
7961
jiabinbce0c1d2020-10-05 11:20:18 -07007962bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7963{
7964 const TrackClientVector activeClients = output->getActiveClients();
7965 if (activeClients.empty()) {
7966 return true;
7967 }
7968 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7969 if (index < 0) {
7970 ALOGE("%s, no audio patch found while there are active clients on output %d",
7971 __func__, output->getId());
7972 return false;
7973 }
7974 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7975 DeviceVector routedDevices;
7976 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7977 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7978 patchDesc->mPatch.sinks[i].id);
7979 if (device == nullptr) {
7980 ALOGE("%s, no audio device found with id(%d)",
7981 __func__, patchDesc->mPatch.sinks[i].id);
7982 return false;
7983 }
7984 routedDevices.add(device);
7985 }
7986 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007987 if (client->isInvalid()) {
7988 // No need to take care about invalidated clients.
7989 continue;
7990 }
jiabinbce0c1d2020-10-05 11:20:18 -07007991 sp<DeviceDescriptor> preferredDevice =
7992 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7993 if (mEngine->getOutputDevicesForAttributes(
7994 client->attributes(), preferredDevice, false) == routedDevices) {
7995 return false;
7996 }
7997 }
7998 return true;
7999}
8000
8001sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008002 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008003 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8004 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008005{
8006 for (const auto& device : devices) {
8007 // TODO: This should be checking if the profile supports the device combo.
8008 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008009 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8010 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008011 return nullptr;
8012 }
8013 }
8014 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8015 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008016 status_t status = desc->open(halConfig, mixerConfig, devices,
8017 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008018 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008019 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008020 return nullptr;
8021 }
8022
8023 // Here is where the out_set_parameters() for card & device gets called
8024 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8025 const audio_devices_t deviceType = device->type();
8026 const String8 &address = String8(device->address().c_str());
8027 if (!address.isEmpty()) {
8028 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8029 mpClientInterface->setParameters(output, String8(param));
8030 free(param);
8031 }
8032 updateAudioProfiles(device, output, profile->getAudioProfiles());
8033 if (!profile->hasValidAudioProfile()) {
8034 ALOGW("%s() missing param", __func__);
8035 desc->close();
8036 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008037 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8038 // Reopen the output with the best audio profile picked by APM when the profile supports
8039 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008040 desc->close();
8041 output = AUDIO_IO_HANDLE_NONE;
8042 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8043 profile->pickAudioProfile(
8044 config.sample_rate, config.channel_mask, config.format);
8045 config.offload_info.sample_rate = config.sample_rate;
8046 config.offload_info.channel_mask = config.channel_mask;
8047 config.offload_info.format = config.format;
8048
jiabina84c3d32022-12-02 18:59:55 +00008049 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008050 if (status != NO_ERROR) {
8051 return nullptr;
8052 }
8053 }
8054
8055 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008056
baek.kim -61c20122022-07-27 10:05:32 +00008057 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8058 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8059
jiabinbce0c1d2020-10-05 11:20:18 -07008060 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8061 sp<AudioPolicyMix> policyMix;
8062 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8063 policyMix->setOutput(desc);
8064 desc->mPolicyMix = policyMix;
8065 } else {
8066 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8067 address.string());
8068 }
8069
baek.kim -61c20122022-07-27 10:05:32 +00008070 } else if (hasPrimaryOutput() && speaker != nullptr
8071 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008072 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8073 // no duplicated output for:
8074 // - direct outputs
8075 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008076 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008077 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8078
8079 //TODO: configure audio effect output stage here
8080
8081 // open a duplicating output thread for the new output and the primary output
8082 sp<SwAudioOutputDescriptor> dupOutputDesc =
8083 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8084 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8085 if (status == NO_ERROR) {
8086 // add duplicated output descriptor
8087 addOutput(duplicatedOutput, dupOutputDesc);
8088 } else {
8089 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8090 mPrimaryOutput->mIoHandle, output);
8091 desc->close();
8092 removeOutput(output);
8093 nextAudioPortGeneration();
8094 return nullptr;
8095 }
8096 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008097 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8098 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8099 mPrimaryOutput = desc;
8100 }
jiabinbce0c1d2020-10-05 11:20:18 -07008101 return desc;
8102}
8103
jiabinf1c73972022-04-14 16:28:52 -07008104status_t AudioPolicyManager::getDevicesForAttributes(
8105 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8106 // Devices are determined in the following precedence:
8107 //
8108 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8109 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8110 //
8111 // If no such dynamic policy then
8112 // 2) Devices containing an active client using setPreferredDevice
8113 // with same strategy as the attributes.
8114 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8115 //
8116 // If no corresponding active client with setPreferredDevice then
8117 // 3) Devices associated with the strategy determined by the attributes
8118 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8119 //
8120 // See related getOutputForAttrInt().
8121
8122 // check dynamic policies but only for primary descriptors (secondary not used for audible
8123 // audio routing, only used for duplication for playback capture)
8124 sp<AudioPolicyMix> policyMix;
8125 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02008126 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE, policyMix,
jiabinf1c73972022-04-14 16:28:52 -07008127 nullptr /* secondaryMixes */);
8128 if (status != OK) {
8129 return status;
8130 }
8131
8132 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8133 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8134 // as they are unaffected by device/stream volume
8135 // (per SwAudioOutputDescriptor::isFixedVolume()).
8136 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8137 ) {
8138 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8139 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8140 devices.add(deviceDesc);
8141 } else {
8142 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8143 // which selects setPreferredDevice if active. This means forVolume call
8144 // will take an active setPreferredDevice, if such exists.
8145
8146 devices = mEngine->getOutputDevicesForAttributes(
8147 attr, nullptr /* preferredDevice */, false /* fromCache */);
8148 }
8149
8150 if (forVolume) {
8151 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8152 // for single volume control in AudioService (such relationship should exist if
8153 // SPEAKER_SAFE is present).
8154 //
8155 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8156 DeviceVector speakerSafeDevices =
8157 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8158 if (!speakerSafeDevices.isEmpty()) {
8159 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8160 devices.remove(speakerSafeDevices);
8161 }
8162 }
8163
8164 return NO_ERROR;
8165}
8166
8167status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8168 AudioProfileVector& audioProfiles,
8169 uint32_t flags,
8170 bool isInput) {
8171 for (const auto& hwModule : mHwModules) {
8172 // the MSD module checks for different conditions
8173 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8174 continue;
8175 }
8176 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8177 : hwModule->getOutputProfiles();
8178 for (const auto& profile : ioProfiles) {
8179 if (!profile->areAllDevicesSupported(devices) ||
8180 !profile->isCompatibleProfileForFlags(
8181 flags, false /*exactMatchRequiredForInputFlags*/)) {
8182 continue;
8183 }
8184 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8185 }
8186 }
8187
8188 if (!isInput) {
8189 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8190 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8191 if (msdModule != nullptr) {
8192 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8193 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8194 for (const auto &profile: msdModule->getOutputProfiles()) {
8195 if (!profile->asAudioPort()->isDirectOutput()) {
8196 continue;
8197 }
8198 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8199 }
8200 } else {
8201 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8202 }
8203 }
8204 }
8205
8206 return NO_ERROR;
8207}
8208
jiabina84c3d32022-12-02 18:59:55 +00008209status_t AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8210 const audio_config_t *config,
8211 audio_output_flags_t flags,
8212 const char* caller) {
8213 closeOutput(outputDesc->mIoHandle);
8214 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8215 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8216 if (preferredOutput == nullptr) {
8217 ALOGE("%s failed to reopen output device=%d, caller=%s",
8218 __func__, outputDesc->devices()[0]->getId(), caller);
8219 return BAD_VALUE;
8220 }
8221 return NO_ERROR;
8222}
8223
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008224} // namespace android