blob: 346191f2fed20bfe689cf86fbadc2c7f8322b20c [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,
jiabinc658e452022-10-21 20:52:21 +00001145 bool *isSpatialized,
1146 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001147{
François Gaffiec005e562018-11-06 15:04:49 +01001148 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001149 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001150 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001151 const sp<DeviceDescriptor> requestedDevice =
1152 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1153
Eric Laurent8a1095a2019-11-08 14:44:16 -08001154 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001155 *isSpatialized = false;
1156
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001157 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1158 if (status != NO_ERROR) {
1159 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001160 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001161 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001162 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001163 }
François Gaffiec005e562018-11-06 15:04:49 +01001164 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001165
François Gaffiec005e562018-11-06 15:04:49 +01001166 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1167 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001168
Kevin Rocard153f92d2018-12-18 18:33:28 -08001169 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1170 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1171 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001172 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001173 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1174 .channel_mask = config->channel_mask,
1175 .format = config->format,
1176 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001177 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
1178 primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001179 if (status != OK) {
1180 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001181 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001182
Kevin Rocard153f92d2018-12-18 18:33:28 -08001183 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001184 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001185
1186 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001187 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1188 && !audio_is_linear_pcm(config->format)) {
1189 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001190 return BAD_VALUE;
1191 }
1192 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001193 sp<DeviceDescriptor> deviceDesc =
1194 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1195 primaryMix->mDeviceAddress,
1196 AUDIO_FORMAT_DEFAULT);
1197 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001198 bool tryDirectForFlags = policyDesc == nullptr ||
1199 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1200 // if a direct output can be opened to deliver the track's multi-channel content to the
1201 // output rather than being downmixed by the primary output, then use this direct
1202 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1203 // mix.
1204 bool tryDirectForChannelMask = policyDesc != nullptr
1205 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1206 audio_channel_count_from_out_mask(config->channel_mask));
1207 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001208 audio_io_handle_t newOutput;
1209 status = openDirectOutput(
1210 *stream, session, config,
1211 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1212 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001213 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001214 policyDesc = mOutputs.valueFor(newOutput);
1215 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001216 } else if (tryDirectForFlags) {
1217 policyDesc = nullptr;
1218 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001219 }
1220 if (policyDesc != nullptr) {
1221 policyDesc->mPolicyMix = primaryMix;
1222 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001223 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001224
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001225 ALOGV("getOutputForAttr() returns output %d", *output);
1226 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1227 *outputType = API_OUT_MIX_PLAYBACK;
1228 } else {
1229 *outputType = API_OUTPUT_LEGACY;
1230 }
1231 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001232 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001233 }
François Gaffiec005e562018-11-06 15:04:49 +01001234 // Virtual sources must always be dynamicaly or explicitly routed
1235 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1236 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1237 return BAD_VALUE;
1238 }
1239 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1240 // in order to let the choice of the order to future vendor engine
1241 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001242
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001243 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001244 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001245 }
1246
Nadav Barb2f18162018-07-18 13:01:53 +03001247 // Set incall music only if device was explicitly set, and fallback to the device which is
1248 // chosen by the engine if not.
1249 // FIXME: provide a more generic approach which is not device specific and move this back
1250 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001251 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001252 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001253 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001254 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001255 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001256 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001257 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001258 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001259 }
1260 }
1261
François Gaffiec005e562018-11-06 15:04:49 +01001262 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1263 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1264 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001265
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001266 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001267 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001268 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001269 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001270 ALOGV("%s() Using MSD devices %s instead of devices %s",
1271 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001272 } else {
1273 *output = AUDIO_IO_HANDLE_NONE;
1274 }
1275 }
1276 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001277 sp<PreferredMixerAttributesInfo> info = nullptr;
1278 if (outputDevices.size() == 1) {
1279 info = getPreferredMixerAttributesInfo(
1280 outputDevices.itemAt(0)->getId(),
1281 mEngine->getProductStrategyForAttributes(*resultAttr));
1282 if (info != nullptr && info->getUid() != uid && info->getActiveClientCount() == 0) {
1283 // Only use preferred mixer when the requested uid matched or
1284 // there is active client on preferred mixer.
1285 info = nullptr;
1286 }
1287 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001288 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001289 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabinc658e452022-10-21 20:52:21 +00001290 *isBitPerfect = (info != nullptr
1291 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
1292 && *output != AUDIO_IO_HANDLE_NONE);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001293 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001294 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001295 AudioProfileVector profiles;
1296 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1297 if (ret == NO_ERROR && !profiles.empty()) {
1298 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1299 : *profiles[0]->getChannels().begin();
1300 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1301 : *profiles[0]->getSampleRates().begin();
1302 config->format = profiles[0]->getFormat();
1303 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001304 return INVALID_OPERATION;
1305 }
Paul McLeanaa981192015-03-21 09:55:15 -07001306
François Gaffiec005e562018-11-06 15:04:49 +01001307 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001308 for (auto &outputDevice : outputDevices) {
1309 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1310 *selectedDeviceId = outputDevice->getId();
1311 break;
1312 }
1313 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001314
Eric Laurent8a1095a2019-11-08 14:44:16 -08001315 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1316 *outputType = API_OUTPUT_TELEPHONY_TX;
1317 } else {
1318 *outputType = API_OUTPUT_LEGACY;
1319 }
1320
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001321 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1322
1323 return NO_ERROR;
1324}
1325
1326status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1327 audio_io_handle_t *output,
1328 audio_session_t session,
1329 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001330 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001331 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001332 audio_output_flags_t *flags,
1333 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001334 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001335 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001336 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001337 bool *isSpatialized,
1338 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001339{
1340 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1341 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1342 return INVALID_OPERATION;
1343 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001344 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001345 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001346 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001347 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001348 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001349 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001350 const sp<DeviceDescriptor> requestedDevice =
1351 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1352
1353 // Prevent from storing invalid requested device id in clients
1354 const audio_port_handle_t sanitizedRequestedPortId =
1355 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1356 *selectedDeviceId = sanitizedRequestedPortId;
1357
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001358 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001359 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001360 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1361 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001362 if (status != NO_ERROR) {
1363 return status;
1364 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001365 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001366 if (secondaryOutputs != nullptr) {
1367 for (auto &secondaryMix : secondaryMixes) {
1368 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1369 if (outputDesc != nullptr &&
1370 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1371 secondaryOutputs->push_back(outputDesc->mIoHandle);
1372 weakSecondaryOutputDescs.push_back(outputDesc);
1373 }
1374 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001375 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001376
Eric Laurent8fc147b2018-07-22 19:13:55 -07001377 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001378 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001379 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001380 };
jiabin4ef93452019-09-10 14:29:54 -07001381 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001382
Eric Laurentc209fe42020-06-05 18:11:23 -07001383 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001384 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001385 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001386 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001387 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001388 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001389 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001390 std::move(weakSecondaryOutputDescs),
1391 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001392 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001393
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001394 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1395 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001396
Eric Laurente83b55d2014-11-14 10:06:21 -08001397 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001398}
1399
Eric Laurentc529cf62020-04-17 18:19:10 -07001400status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1401 audio_session_t session,
1402 const audio_config_t *config,
1403 audio_output_flags_t flags,
1404 const DeviceVector &devices,
1405 audio_io_handle_t *output) {
1406
1407 *output = AUDIO_IO_HANDLE_NONE;
1408
1409 // skip direct output selection if the request can obviously be attached to a mixed output
1410 // and not explicitly requested
1411 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1412 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1413 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1414 return NAME_NOT_FOUND;
1415 }
1416
1417 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1418 // This prevents creating an offloaded track and tearing it down immediately after start
1419 // when audioflinger detects there is an active non offloadable effect.
1420 // FIXME: We should check the audio session here but we do not have it in this context.
1421 // This may prevent offloading in rare situations where effects are left active by apps
1422 // in the background.
1423 sp<IOProfile> profile;
1424 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1425 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1426 profile = getProfileForOutput(
1427 devices, config->sample_rate, config->format, config->channel_mask,
1428 flags, true /* directOnly */);
1429 }
1430
1431 if (profile == nullptr) {
1432 return NAME_NOT_FOUND;
1433 }
1434
1435 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1436 for (size_t i = 0; i < mOutputs.size(); i++) {
1437 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1438 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1439 // reuse direct output if currently open by the same client
1440 // and configured with same parameters
1441 if ((config->sample_rate == desc->getSamplingRate()) &&
1442 (config->format == desc->getFormat()) &&
1443 (config->channel_mask == desc->getChannelMask()) &&
1444 (session == desc->mDirectClientSession)) {
1445 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001446 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001447 mOutputs.keyAt(i), session);
1448 *output = mOutputs.keyAt(i);
1449 return NO_ERROR;
1450 }
1451 }
1452 }
1453
1454 if (!profile->canOpenNewIo()) {
1455 return NAME_NOT_FOUND;
1456 }
1457
1458 sp<SwAudioOutputDescriptor> outputDesc =
1459 new SwAudioOutputDescriptor(profile, mpClientInterface);
1460
Michael Chan6fb34492020-12-08 15:44:49 +11001461 // An MSD patch may be using the only output stream that can service this request. Release
1462 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001463 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001464
Eric Laurentf1f22e72021-07-13 14:04:14 +02001465 status_t status =
1466 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001467
1468 // only accept an output with the requested parameters
1469 if (status != NO_ERROR ||
1470 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1471 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1472 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1473 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1474 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1475 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1476 config->channel_mask, outputDesc->getChannelMask());
1477 if (*output != AUDIO_IO_HANDLE_NONE) {
1478 outputDesc->close();
1479 }
1480 // fall back to mixer output if possible when the direct output could not be open
1481 if (audio_is_linear_pcm(config->format) &&
1482 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1483 return NAME_NOT_FOUND;
1484 }
1485 *output = AUDIO_IO_HANDLE_NONE;
1486 return BAD_VALUE;
1487 }
1488 outputDesc->mDirectOpenCount = 1;
1489 outputDesc->mDirectClientSession = session;
1490
1491 addOutput(*output, outputDesc);
1492 mPreviousOutputs = mOutputs;
1493 ALOGV("%s returns new direct output %d", __func__, *output);
1494 mpClientInterface->onAudioPortListUpdate();
1495 return NO_ERROR;
1496}
1497
François Gaffie11d30102018-11-02 16:09:09 +01001498audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1499 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001500 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001501 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001502 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001503 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001504 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001505 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001506 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001507{
Andy Hungc88b0642018-04-27 15:42:35 -07001508 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001509
jiabine375d412019-02-26 12:54:53 -08001510 // Discard haptic channel mask when forcing muting haptic channels.
1511 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001512 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1513 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001514
Eric Laurente552edb2014-03-10 17:42:56 -07001515 // open a direct output if required by specified parameters
1516 //force direct flag if offload flag is set: offloading implies a direct output stream
1517 // and all common behaviors are driven by checking only the direct flag
1518 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001519 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1520 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001521 }
Nadav Bar766fb022018-01-07 12:18:03 +02001522 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1523 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001524 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001525
1526 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1527
Eric Laurente83b55d2014-11-14 10:06:21 -08001528 // only allow deep buffering for music stream type
1529 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001530 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001531 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001532 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001533 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1534 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001535 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001536 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001537 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001538 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001539 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001540 audio_is_linear_pcm(config->format) &&
1541 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001542 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001543 AUDIO_OUTPUT_FLAG_DIRECT);
1544 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001545 }
Eric Laurente552edb2014-03-10 17:42:56 -07001546
Carter Hsua3abb402021-10-26 11:11:20 +08001547 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1548 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1549 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1550 }
1551
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001552 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001553 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001554 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001555 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001556 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001557 }
1558
Eric Laurentc529cf62020-04-17 18:19:10 -07001559 audio_config_t directConfig = *config;
1560 directConfig.channel_mask = channelMask;
1561 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1562 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001563 return output;
1564 }
1565
Eric Laurent14cbfca2016-03-17 09:42:16 -07001566 // A request for HW A/V sync cannot fallback to a mixed output because time
1567 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001568 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001569 return AUDIO_IO_HANDLE_NONE;
1570 }
1571
Eric Laurente552edb2014-03-10 17:42:56 -07001572 // ignoring channel mask due to downmix capability in mixer
1573
1574 // open a non direct output
1575
1576 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001577 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001578 // get which output is suitable for the specified stream. The actual
1579 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001580 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001581 if (prefMixerConfigInfo != nullptr) {
1582 for (audio_io_handle_t outputHandle : outputs) {
1583 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1584 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1585 output = outputHandle;
1586 break;
1587 }
1588 }
1589 if (output == AUDIO_IO_HANDLE_NONE) {
1590 // No output open with the preferred profile. Open a new one.
1591 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1592 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1593 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1594 config.format = prefMixerConfigInfo->getConfigBase().format;
1595 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1596 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1597 &config, prefMixerConfigInfo->getFlags());
1598 if (preferredOutput == nullptr) {
1599 ALOGE("%s failed to open output with preferred mixer config", __func__);
1600 } else {
1601 output = preferredOutput->mIoHandle;
1602 }
1603 }
1604 } else {
1605 // at this stage we should ignore the DIRECT flag as no direct output could be
1606 // found earlier
1607 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1608 output = selectOutput(
1609 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1610 }
Eric Laurente552edb2014-03-10 17:42:56 -07001611 }
François Gaffie11d30102018-11-02 16:09:09 +01001612 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001613 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001614 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001615
Eric Laurente552edb2014-03-10 17:42:56 -07001616 return output;
1617}
1618
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001619sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001620 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1621 mAvailableInputDevices);
1622 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1623}
1624
1625DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1626 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1627 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001628}
1629
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001630const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001631 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001632 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1633 if (msdModule != 0) {
1634 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1635 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1636 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1637 const struct audio_port_config *source = &patch->mPatch.sources[j];
1638 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1639 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001640 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001641 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001642 }
1643 }
1644 }
1645 return msdPatches;
1646}
1647
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001648bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1649 ssize_t index = mAudioPatches.indexOfKey(handle);
1650 if (index < 0) {
1651 return false;
1652 }
1653 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1654 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1655 if (msdModule == nullptr) {
1656 return false;
1657 }
1658 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1659 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1660 return true;
1661 }
1662 index = getMsdOutputPatches().indexOfKey(handle);
1663 if (index < 0) {
1664 return false;
1665 }
1666 return true;
1667}
1668
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001669status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1670 const InputProfileCollection &inputProfiles,
1671 const OutputProfileCollection &outputProfiles,
1672 const sp<DeviceDescriptor> &sourceDevice,
1673 const sp<DeviceDescriptor> &sinkDevice,
1674 AudioProfileVector& sourceProfiles,
1675 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001676 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001677 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001678 return NO_INIT;
1679 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001680 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001681 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001682 return NO_INIT;
1683 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001684 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001685 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1686 inProfile->supportsDevice(sourceDevice)) {
1687 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001688 }
1689 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001690 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001691 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001692 outProfile->supportsDevice(sinkDevice)) {
1693 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001694 }
1695 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001696 return NO_ERROR;
1697}
1698
1699status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1700 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1701 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1702{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001703 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001704 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1705 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1706 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001707 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001708 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1709 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001710 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001711 }
1712 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1713 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1714 sinkConfig->format = bestSinkConfig.format;
1715 // For encoded streams force direct flag to prevent downstream mixing.
1716 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1717 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001718 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1719 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001720 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001721 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1722 // raw and IEC61937 framed streams.
1723 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1724 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1725 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001726 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1727 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1728 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1729 sourceConfig->format = bestSinkConfig.format;
1730 // Copy input stream directly without any processing (e.g. resampling).
1731 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1732 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1733 if (hwAvSync) {
1734 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1735 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1736 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1737 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1738 }
1739 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1740 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1741 sinkConfig->config_mask |= config_mask;
1742 sourceConfig->config_mask |= config_mask;
1743 return NO_ERROR;
1744}
1745
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001746PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1747 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001748{
1749 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001750 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1751 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1752 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1753 if (deviceModule == nullptr) {
1754 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1755 return patchBuilder;
1756 }
1757 const InputProfileCollection inputProfiles = msdIsSource ?
1758 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1759 const OutputProfileCollection outputProfiles = msdIsSource ?
1760 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1761
1762 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1763 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1764 device : getMsdAudioOutDevices().itemAt(0);
1765 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1766
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001767 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1768 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001769 AudioProfileVector sourceProfiles;
1770 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1772 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001773 for (auto hwAvSync : { true, false }) {
1774 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1775 sourceProfiles, sinkProfiles) != NO_ERROR) {
1776 continue;
1777 }
1778 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1779 &sinkConfig) == NO_ERROR) {
1780 // Found a matching config. Re-create PatchBuilder with this config.
1781 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1782 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001783 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001784 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001785 " supporting PCM format conversion.", __func__);
1786 return patchBuilder;
1787}
1788
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001789status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001790 DeviceVector devices;
1791 if (outputDevices != nullptr && outputDevices->size() > 0) {
1792 devices.add(*outputDevices);
1793 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001794 // Use media strategy for unspecified output device. This should only
1795 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1796 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001797 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001798 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001799 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001800 }
Michael Chan6fb34492020-12-08 15:44:49 +11001801 std::vector<PatchBuilder> patchesToCreate;
1802 for (auto i = 0u; i < devices.size(); ++i) {
1803 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001804 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001805 }
1806 // Retain only the MSD patches associated with outputDevices request.
1807 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001808 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001809 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1810 auto retainedPatch = false;
1811 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1812 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1813 patchesToRemove.removeItemsAt(i);
1814 retainedPatch = true;
1815 break;
1816 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001817 }
Michael Chan6fb34492020-12-08 15:44:49 +11001818 if (retainedPatch) {
1819 it = patchesToCreate.erase(it);
1820 continue;
1821 }
1822 ++it;
1823 }
1824 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1825 return NO_ERROR;
1826 }
1827 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1828 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001829 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001830 }
Michael Chan6fb34492020-12-08 15:44:49 +11001831 status_t status = NO_ERROR;
1832 for (const auto &p : patchesToCreate) {
1833 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1834 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1835 char message[256];
1836 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1837 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1838 currStatus == NO_ERROR ? "Success" : "Error",
1839 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1840 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1841 if (currStatus == NO_ERROR) {
1842 ALOGD("%s", message);
1843 } else {
1844 ALOGE("%s", message);
1845 if (status == NO_ERROR) {
1846 status = currStatus;
1847 }
1848 }
1849 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001850 return status;
1851}
1852
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001853void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1854 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001855 for (size_t i = 0; i < msdPatches.size(); i++) {
1856 const auto& patch = msdPatches[i];
1857 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1858 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1859 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1860 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1861 releaseAudioPatch(patch->getHandle(), mUidCached);
1862 break;
1863 }
1864 }
1865 }
1866}
1867
Dorin Drimus94d94412022-02-02 09:05:02 +01001868bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1869 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1870 AudioPatchCollection msdPatches = getMsdOutputPatches();
1871 for (size_t i = 0; i < msdPatches.size(); i++) {
1872 const auto& patch = msdPatches[i];
1873 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1874 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1875 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1876 const auto& foundDevice = devicesToCheck.getDevice(
1877 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1878 if (foundDevice != nullptr) {
1879 devicesToCheck.remove(foundDevice);
1880 if (devicesToCheck.isEmpty()) {
1881 return true;
1882 }
1883 }
1884 }
1885 }
1886 }
1887 return false;
1888}
1889
Eric Laurente0720872014-03-11 09:30:41 -07001890audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001891 audio_output_flags_t flags,
1892 audio_format_t format,
1893 audio_channel_mask_t channelMask,
1894 uint32_t samplingRate,
1895 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001896{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001897 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1898 "%s called with format %#x", __func__, format);
1899
jiabinebb6af42020-06-09 17:31:17 -07001900 // Return the output that haptic-generating attached to when 1) session id is specified,
1901 // 2) haptic-generating effect exists for given session id and 3) the output that
1902 // haptic-generating effect attached to is in given outputs.
1903 if (sessionId != AUDIO_SESSION_NONE) {
1904 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1905 sessionId, FX_IID_HAPTICGENERATOR);
1906 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1907 return hapticGeneratingOutput;
1908 }
1909 }
1910
Eric Laurent16c66dd2019-05-01 17:54:10 -07001911 // Flags disqualifying an output: the match must happen before calling selectOutput()
1912 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1913 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1914
1915 // Flags expressing a functional request: must be honored in priority over
1916 // other criteria
1917 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1918 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001919 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1920 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001921 // Flags expressing a performance request: have lower priority than serving
1922 // requested sampling rate or channel mask
1923 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1924 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1925 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1926
1927 const audio_output_flags_t functionalFlags =
1928 (audio_output_flags_t)(flags & kFunctionalFlags);
1929 const audio_output_flags_t performanceFlags =
1930 (audio_output_flags_t)(flags & kPerformanceFlags);
1931
1932 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1933
Eric Laurente552edb2014-03-10 17:42:56 -07001934 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001935 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001936 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001937 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001938 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001939 // with tiebreak preferring the minimum number of extra functional flags
1940 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001941 // 3: the output supporting the exact channel mask
1942 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001943 // 5: the output with the highest sampling rate if the requested sample rate is
1944 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001945 // 6: the output with the highest number of requested performance flags
1946 // 7: the output with the bit depth the closest to the requested one
1947 // 8: the primary output
1948 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001949
Eric Laurent16c66dd2019-05-01 17:54:10 -07001950 // matching criteria values in priority order for best matching output so far
1951 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001952
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1954 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1955 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001956
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001957 for (audio_io_handle_t output : outputs) {
1958 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001959 // matching criteria values in priority order for current output
1960 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001961
Eric Laurent16c66dd2019-05-01 17:54:10 -07001962 if (outputDesc->isDuplicated()) {
1963 continue;
1964 }
1965 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1966 continue;
1967 }
Eric Laurent8838a382014-09-08 16:44:28 -07001968
Eric Laurent16c66dd2019-05-01 17:54:10 -07001969 // If haptic channel is specified, use the haptic output if present.
1970 // When using haptic output, same audio format and sample rate are required.
1971 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001972 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001973 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1974 continue;
1975 }
1976 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001977 && format == outputDesc->getFormat()
1978 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001979 currentMatchCriteria[0] = outputHapticChannelCount;
1980 }
1981
1982 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001983 const int matchingFunctionalFlags =
1984 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1985 const int totalFunctionalFlags =
1986 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1987 // Prefer matching functional flags, but subtract unnecessary functional flags.
1988 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001989
1990 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001991 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1992 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001993 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1994 channelCount <= outputChannelCount) {
1995 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001996 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1997 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001998 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001999 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002000 currentMatchCriteria[3] = outputChannelCount;
2001 }
2002
2003 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002004 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002005 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002006 }
2007
2008 // performance flags match
2009 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2010
2011 // format match
2012 if (format != AUDIO_FORMAT_INVALID) {
2013 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002014 PolicyAudioPort::kFormatDistanceMax -
2015 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002016 }
2017
2018 // primary output match
2019 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2020
2021 // compare match criteria by priority then value
2022 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2023 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2024 bestMatchCriteria = currentMatchCriteria;
2025 bestOutput = output;
2026
2027 std::stringstream result;
2028 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2029 std::ostream_iterator<int>(result, " "));
2030 ALOGV("%s new bestOutput %d criteria %s",
2031 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002032 }
2033 }
2034
Eric Laurent16c66dd2019-05-01 17:54:10 -07002035 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002036}
2037
Eric Laurent8fc147b2018-07-22 19:13:55 -07002038status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002039{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002040 ALOGV("%s portId %d", __FUNCTION__, portId);
2041
2042 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2043 if (outputDesc == 0) {
2044 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002045 return BAD_VALUE;
2046 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002047 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002048
Eric Laurent8fc147b2018-07-22 19:13:55 -07002049 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002050 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002051
Eric Laurent733ce942017-12-07 12:18:25 -08002052 status_t status = outputDesc->start();
2053 if (status != NO_ERROR) {
2054 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002055 }
2056
Eric Laurent97ac8712018-07-27 18:59:02 -07002057 uint32_t delayMs;
2058 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002059
2060 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002061 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002062 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002063 }
jiabina84c3d32022-12-02 18:59:55 +00002064
2065 // If the client is the first one active on preferred mixer parameters, reopen the output
2066 // if the current mixer parameters doesn't match the preferred one.
2067 if (outputDesc->devices().size() == 1) {
2068 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2069 outputDesc->devices()[0]->getId(), client->strategy());
2070 if (info != nullptr && info->getUid() == client->uid()) {
2071 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2072 info->getConfigBase(), info->getFlags())) {
2073 stopSource(outputDesc, client);
2074 outputDesc->stop();
2075 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2076 config.channel_mask = info->getConfigBase().channel_mask;
2077 config.sample_rate = info->getConfigBase().sample_rate;
2078 config.format = info->getConfigBase().format;
2079 status_t status = reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2080 if (status != NO_ERROR) {
2081 return status;
2082 }
2083 // Intentionally return error to let the client side resending request for
2084 // creating and starting.
2085 return DEAD_OBJECT;
2086 }
2087 info->increaseActiveClient();
2088 }
2089 }
2090
Eric Laurentc75307b2015-03-17 15:29:32 -07002091 if (delayMs != 0) {
2092 usleep(delayMs * 1000);
2093 }
2094
2095 return status;
2096}
2097
Eric Laurent96d1dda2022-03-14 17:14:19 +01002098bool AudioPolicyManager::isLeUnicastActive() const {
2099 if (isInCall()) {
2100 return true;
2101 }
2102 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2103}
2104
2105bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2106 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2107 return false;
2108 }
2109 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2110 ALOGV("%s active %d", __func__, active);
2111 return active;
2112}
2113
Eric Laurent97ac8712018-07-27 18:59:02 -07002114status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2115 const sp<TrackClientDescriptor>& client,
2116 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002117{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002118 // cannot start playback of STREAM_TTS if any other output is being used
2119 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002120
2121 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002122 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002123 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002124 auto clientStrategy = client->strategy();
2125 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002126 if (stream == AUDIO_STREAM_TTS) {
2127 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002128 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002129 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002130 return INVALID_OPERATION;
2131 } else {
2132 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2133 }
2134 } else {
2135 // some playback other than beacon starts
2136 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2137 }
2138
Eric Laurent77305a62016-07-25 16:39:22 -07002139 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002140 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002141 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002142
François Gaffie11d30102018-11-02 16:09:09 +01002143 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002144 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002145 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002146 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002147 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002148 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002149 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002150 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002151 } else {
2152 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002153 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002154 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2155 AUDIO_FORMAT_DEFAULT);
2156 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2157 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002158 }
2159
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002160 // requiresMuteCheck is false when we can bypass mute strategy.
2161 // It covers a common case when there is no materially active audio
2162 // and muting would result in unnecessary delay and dropped audio.
2163 const uint32_t outputLatencyMs = outputDesc->latency();
2164 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002165 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002166
Eric Laurente552edb2014-03-10 17:42:56 -07002167 // increment usage count for this stream on the requested output:
2168 // NOTE that the usage count is the same for duplicated output and hardware output which is
2169 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002170 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002171
2172 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002173 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2174 client->isPreferredDeviceForExclusiveUse()) {
2175 // Preferred device may be exclusive, use only if no other active clients on this output
2176 devices = DeviceVector(
2177 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2178 } else {
2179 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2180 }
François Gaffie11d30102018-11-02 16:09:09 +01002181 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002182 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002183 }
2184 }
Eric Laurente552edb2014-03-10 17:42:56 -07002185
François Gaffiec005e562018-11-06 15:04:49 +01002186 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002187 selectOutputForMusicEffects();
2188 }
2189
François Gaffie1c878552018-11-22 16:53:21 +01002190 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002191 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002192 if (devices.isEmpty()) {
2193 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002194 }
François Gaffiec005e562018-11-06 15:04:49 +01002195 bool shouldWait =
2196 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2197 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2198 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002199 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002200 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002201 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002202 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002203 // An output has a shared device if
2204 // - managed by the same hw module
2205 // - supports the currently selected device
2206 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002207 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002208
Eric Laurent77305a62016-07-25 16:39:22 -07002209 // force a device change if any other output is:
2210 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002211 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002212 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002213 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002214 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002215 // change the device currently selected by the other output.
2216 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002217 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002218 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002219 force = true;
2220 }
2221 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002222 // a notification so that audio focus effect can propagate, or that a mute/unmute
2223 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002224 const uint32_t latencyMs = desc->latency();
2225 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2226
2227 if (shouldWait && isActive && (waitMs < latencyMs)) {
2228 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002229 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002230
2231 // Require mute check if another output is on a shared device
2232 // and currently active to have proper drain and avoid pops.
2233 // Note restoring AudioTracks onto this output needs to invoke
2234 // a volume ramp if there is no mute.
2235 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002236 }
2237 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002238
2239 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002240 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002241
Eric Laurente552edb2014-03-10 17:42:56 -07002242 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002243 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002244 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002245 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002246 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002247 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002248 outputDesc->useHwGain() /*force*/)) {
2249 // request AudioService to reinitialize the volume curves asynchronously
2250 ALOGE("checkAndSetVolume failed, requesting volume range init");
2251 mpClientInterface->onVolumeRangeInitRequest();
2252 };
Eric Laurente552edb2014-03-10 17:42:56 -07002253
2254 // update the outputs if starting an output with a stream that can affect notification
2255 // routing
2256 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002257
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002258 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002259 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002260 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2261 }
Eric Laurentdc462862016-07-19 12:29:53 -07002262
2263 if (waitMs > muteWaitMs) {
2264 *delayMs = waitMs - muteWaitMs;
2265 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002266
2267 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2268 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2269 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2270 // change occurs after the MixerThread starts and causes a stream volume
2271 // glitch.
2272 //
2273 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002274 }
Eric Laurentdc462862016-07-19 12:29:53 -07002275
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002276 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002277 mEngine->getForceUse(
2278 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002279 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002280 }
2281
Eric Laurent97ac8712018-07-27 18:59:02 -07002282 // Automatically enable the remote submix input when output is started on a re routing mix
2283 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002284 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2285 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002286 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2287 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2288 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002289 "remote-submix",
2290 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002291 }
2292
Eric Laurent96d1dda2022-03-14 17:14:19 +01002293 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2294
Eric Laurente552edb2014-03-10 17:42:56 -07002295 return NO_ERROR;
2296}
2297
Eric Laurent96d1dda2022-03-14 17:14:19 +01002298void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2299 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2300 bool isUnicastActive = isLeUnicastActive();
2301
2302 if (wasUnicastActive != isUnicastActive) {
2303 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2304 for (size_t i = 0; i < mOutputs.size(); i++) {
2305 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2306 if (desc != ignoredOutput && desc->isActive()
2307 && ((isUnicastActive &&
2308 !desc->devices().
2309 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2310 || (wasUnicastActive &&
2311 !desc->devices().getDevicesFromTypes(
2312 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2313 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2314 bool force = desc->devices() != newDevices;
2315 setOutputDevices(desc, newDevices, force, delayMs);
2316 // re-apply device specific volume if not done by setOutputDevice()
2317 if (!force) {
2318 applyStreamVolumes(desc, newDevices.types(), delayMs);
2319 }
2320 }
2321 }
2322 }
2323}
2324
Eric Laurent8fc147b2018-07-22 19:13:55 -07002325status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002326{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002327 ALOGV("%s portId %d", __FUNCTION__, portId);
2328
2329 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2330 if (outputDesc == 0) {
2331 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002332 return BAD_VALUE;
2333 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002334 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002335
Eric Laurent97ac8712018-07-27 18:59:02 -07002336 ALOGV("stopOutput() output %d, stream %d, session %d",
2337 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002338
Eric Laurent97ac8712018-07-27 18:59:02 -07002339 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002340
Eric Laurent733ce942017-12-07 12:18:25 -08002341 if (status == NO_ERROR ) {
2342 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002343 } else {
2344 return status;
2345 }
2346
2347 if (outputDesc->devices().size() == 1) {
2348 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2349 outputDesc->devices()[0]->getId(), client->strategy());
2350 if (info != nullptr && info->getUid() == client->uid()) {
2351 info->decreaseActiveClient();
2352 if (info->getActiveClientCount() == 0) {
2353 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2354 }
2355 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002356 }
2357 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002358}
2359
Eric Laurent97ac8712018-07-27 18:59:02 -07002360status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2361 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002362{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002363 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002364 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002365 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002366 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002367
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002368 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2369
François Gaffie1c878552018-11-22 16:53:21 +01002370 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2371 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002372 // Automatically disable the remote submix input when output is stopped on a
2373 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002374 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002375 if (isSingleDeviceType(
2376 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002377 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002378 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002379 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2380 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002381 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002382 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002383 }
2384 }
2385 bool forceDeviceUpdate = false;
2386 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002387 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002388 forceDeviceUpdate = true;
2389 }
2390
Eric Laurente552edb2014-03-10 17:42:56 -07002391 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002392 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002393
Eric Laurente552edb2014-03-10 17:42:56 -07002394 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002395 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002396 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002397 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002398
2399 // If the routing does not change, if an output is routed on a device using HwGain
2400 // (aka setAudioPortConfig) and there are still active clients following different
2401 // volume group(s), force reapply volume
2402 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2403 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2404
Eric Laurente552edb2014-03-10 17:42:56 -07002405 // delay the device switch by twice the latency because stopOutput() is executed when
2406 // the track stop() command is received and at that time the audio track buffer can
2407 // still contain data that needs to be drained. The latency only covers the audio HAL
2408 // and kernel buffers. Also the latency does not always include additional delay in the
2409 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002410 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2411 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002412
2413 // force restoring the device selection on other active outputs if it differs from the
2414 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002415 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002416 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002417 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002418 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002419 desc->isActive() &&
2420 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002421 (newDevices != desc->devices())) {
2422 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2423 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002424
François Gaffie11d30102018-11-02 16:09:09 +01002425 setOutputDevices(desc, newDevices2, force, delayMs);
2426
Eric Laurent57de36c2016-09-28 16:59:11 -07002427 // re-apply device specific volume if not done by setOutputDevice()
2428 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002429 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002430 }
Eric Laurente552edb2014-03-10 17:42:56 -07002431 }
2432 }
2433 // update the outputs if stopping one with a stream that can affect notification routing
2434 handleNotificationRoutingForStream(stream);
2435 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002436
2437 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2438 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002439 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002440 }
2441
François Gaffiec005e562018-11-06 15:04:49 +01002442 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002443 selectOutputForMusicEffects();
2444 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002445
2446 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2447
Eric Laurente552edb2014-03-10 17:42:56 -07002448 return NO_ERROR;
2449 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002450 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002451 return INVALID_OPERATION;
2452 }
2453}
2454
jiabinbce0c1d2020-10-05 11:20:18 -07002455bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002456{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002457 ALOGV("%s portId %d", __FUNCTION__, portId);
2458
2459 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2460 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002461 // If an output descriptor is closed due to a device routing change,
2462 // then there are race conditions with releaseOutput from tracks
2463 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2464 // destroyed shortly thereafter.
2465 //
2466 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002467 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002468 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002469 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002470
2471 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002472
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302473 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2474 if (outputDesc->isClientActive(client)) {
2475 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2476 stopOutput(portId);
2477 }
2478
Eric Laurent8fc147b2018-07-22 19:13:55 -07002479 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2480 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002481 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002482 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002483 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002484 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002485 if (--outputDesc->mDirectOpenCount == 0) {
2486 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002487 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002488 }
2489 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302490
Andy Hung39efb7a2018-09-26 15:39:28 -07002491 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002492 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2493 // The output is pending reopened to query dynamic profiles and
2494 // there is no active clients
2495 closeOutput(outputDesc->mIoHandle);
2496 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2497 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2498 if (newOutputDesc == nullptr) {
2499 ALOGE("%s failed to open output", __func__);
2500 }
2501 return true;
2502 }
2503 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002504}
2505
Eric Laurentcaf7f482014-11-25 17:50:47 -08002506status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2507 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002508 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002509 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002510 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002511 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002512 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002513 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002514 input_type_t *inputType,
2515 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002516{
François Gaffiec005e562018-11-06 15:04:49 +01002517 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002518 "flags %#x attributes=%s requested device ID %d",
2519 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2520 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002521
Eric Laurentad2e7b92017-09-14 20:06:42 -07002522 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002523 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002524 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002525 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002526 sp<AudioInputDescriptor> inputDesc;
2527 sp<RecordClientDescriptor> clientDesc;
2528 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002529 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002530 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002531
2532 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2533 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2534 return INVALID_OPERATION;
2535 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002536
Francois Gaffie716e1432019-01-14 16:58:59 +01002537 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2538 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002539 }
2540
Paul McLean466dc8e2015-04-17 13:15:36 -06002541 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002542 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002543 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002544
Eric Laurentad2e7b92017-09-14 20:06:42 -07002545 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2546 // possible
2547 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2548 *input != AUDIO_IO_HANDLE_NONE) {
2549 ssize_t index = mInputs.indexOfKey(*input);
2550 if (index < 0) {
2551 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2552 status = BAD_VALUE;
2553 goto error;
2554 }
2555 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002556 RecordClientVector clients = inputDesc->getClientsForSession(session);
2557 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002558 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2559 status = BAD_VALUE;
2560 goto error;
2561 }
2562 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2563 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002564 // corresponds to a new client and is only permitted from the same UID.
2565 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002566 if (clients.size() > 1) {
2567 for (const auto& client : clients) {
2568 // The client map is ordered by key values (portId) and portIds are allocated
2569 // incrementaly. So the first client in this list is the one opened by audio flinger
2570 // when the mmap stream is created and should be ignored as it does not correspond
2571 // to an actual client
2572 if (client == *clients.cbegin()) {
2573 continue;
2574 }
2575 if (uid != client->uid() && !client->isSilenced()) {
2576 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2577 uid, client->portId(), client->uid());
2578 status = INVALID_OPERATION;
2579 goto error;
2580 }
Eric Laurent331679c2018-04-16 17:03:16 -07002581 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002582 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002583 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002584 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002585
Eric Laurentfecbceb2021-02-09 14:46:43 +01002586 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002587 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002588 }
2589
2590 *input = AUDIO_IO_HANDLE_NONE;
2591 *inputType = API_INPUT_INVALID;
2592
Francois Gaffie716e1432019-01-14 16:58:59 +01002593 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002594 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002595 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002596 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002597 ALOGW("%s could not find input mix for attr %s",
2598 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002599 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002600 }
jiabinc1de2df2019-05-07 14:26:40 -07002601 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2602 String8(attr->tags + strlen("addr=")),
2603 AUDIO_FORMAT_DEFAULT);
2604 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002605 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002606 __func__, attributes.source, attributes.tags);
2607 status = BAD_VALUE;
2608 goto error;
2609 }
2610
Kevin Rocard25f9b052019-02-27 15:08:54 -08002611 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2612 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2613 } else {
2614 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2615 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002616 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002617 if (explicitRoutingDevice != nullptr) {
2618 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002619 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002620 // Prevent from storing invalid requested device id in clients
2621 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002622 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002623 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2624 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002625 }
François Gaffie11d30102018-11-02 16:09:09 +01002626 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002627 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002628 status = BAD_VALUE;
2629 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002630 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002631 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2632 *inputType = API_INPUT_MIX_CAPTURE;
2633 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002634 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2635 // there is an external policy, but this input is attached to a mix of recorders,
2636 // meaning it receives audio injected into the framework, so the recorder doesn't
2637 // know about it and is therefore considered "legacy"
2638 *inputType = API_INPUT_LEGACY;
2639 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002640 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002641 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002642 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002643 } else {
2644 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002645 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002646
Eric Laurent599c7582015-12-07 18:05:55 -08002647 }
2648
François Gaffiec005e562018-11-06 15:04:49 +01002649 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002650 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002651 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002652 AudioProfileVector profiles;
2653 status_t ret = getProfilesForDevices(
2654 DeviceVector(device), profiles, flags, true /*isInput*/);
2655 if (ret == NO_ERROR && !profiles.empty()) {
2656 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2657 : *profiles[0]->getChannels().begin();
2658 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2659 : *profiles[0]->getSampleRates().begin();
2660 config->format = profiles[0]->getFormat();
2661 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002662 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002663 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002664
Eric Laurent8f42ea12018-08-08 09:08:25 -07002665exit:
2666
François Gaffiec005e562018-11-06 15:04:49 +01002667 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2668 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002669
Francois Gaffie716e1432019-01-14 16:58:59 +01002670 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002671 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002672 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002673
Mikhail Naganov2996f672019-04-18 12:29:59 -07002674 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002675 requestedDeviceId, attributes.source, flags,
2676 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002677 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002678 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002679
2680 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2681 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002682
Eric Laurent599c7582015-12-07 18:05:55 -08002683 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002684
2685error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002686 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002687}
2688
2689
François Gaffie11d30102018-11-02 16:09:09 +01002690audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002691 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002692 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002693 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002694 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002695 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002696{
2697 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002698 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002699 bool isSoundTrigger = false;
2700
François Gaffiec005e562018-11-06 15:04:49 +01002701 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002702 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2703 if (index >= 0) {
2704 input = mSoundTriggerSessions.valueFor(session);
2705 isSoundTrigger = true;
2706 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2707 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2708 } else {
2709 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002710 }
François Gaffiec005e562018-11-06 15:04:49 +01002711 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002712 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002713 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002714 }
2715
Carter Hsua3abb402021-10-26 11:11:20 +08002716 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2717 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2718 }
2719
Eric Laurentfe231122017-11-17 17:48:06 -08002720 // sampling rate and flags may be updated by getInputProfile
2721 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2722 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002723 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002724 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002725 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002726 // find a compatible input profile (not necessarily identical in parameters)
2727 sp<IOProfile> profile = getInputProfile(
2728 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2729 if (profile == nullptr) {
2730 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002731 }
jiabin2fd710d2022-05-02 23:20:22 +00002732
Glenn Kasten05ddca52016-02-11 08:17:12 -08002733 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002734 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002735 if (samplingRate == 0) {
2736 samplingRate = profileSamplingRate;
2737 }
Eric Laurente552edb2014-03-10 17:42:56 -07002738
Eric Laurent322b4d22015-04-03 15:57:54 -07002739 if (profile->getModuleHandle() == 0) {
2740 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002741 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002742 }
2743
Eric Laurentec376dc2021-04-08 20:41:22 +02002744 // Reuse an already opened input if a client with the same session ID already exists
2745 // on that input
2746 for (size_t i = 0; i < mInputs.size(); i++) {
2747 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2748 if (desc->mProfile != profile) {
2749 continue;
2750 }
2751 RecordClientVector clients = desc->clientsList();
2752 for (const auto &client : clients) {
2753 if (session == client->session()) {
2754 return desc->mIoHandle;
2755 }
2756 }
2757 }
2758
Eric Laurent3974e3b2017-12-07 17:58:43 -08002759 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002760 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002761 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002762 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002763 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002764 continue;
2765 }
2766 // if sound trigger, reuse input if used by other sound trigger on same session
2767 // else
2768 // reuse input if active client app is not in IDLE state
2769 //
2770 RecordClientVector clients = desc->clientsList();
2771 bool doClose = false;
2772 for (const auto& client : clients) {
2773 if (isSoundTrigger != client->isSoundTrigger()) {
2774 continue;
2775 }
2776 if (client->isSoundTrigger()) {
2777 if (session == client->session()) {
2778 return desc->mIoHandle;
2779 }
2780 continue;
2781 }
2782 if (client->active() && client->appState() != APP_STATE_IDLE) {
2783 return desc->mIoHandle;
2784 }
2785 doClose = true;
2786 }
2787 if (doClose) {
2788 closeInput(desc->mIoHandle);
2789 } else {
2790 i++;
2791 }
2792 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002793 }
2794
Eric Laurentfe231122017-11-17 17:48:06 -08002795 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002796
Eric Laurentfe231122017-11-17 17:48:06 -08002797 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2798 lConfig.sample_rate = profileSamplingRate;
2799 lConfig.channel_mask = profileChannelMask;
2800 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002801
François Gaffie11d30102018-11-02 16:09:09 +01002802 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002803
2804 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002805 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002806 (profileSamplingRate != lConfig.sample_rate) ||
2807 !audio_formats_match(profileFormat, lConfig.format) ||
2808 (profileChannelMask != lConfig.channel_mask)) {
2809 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002810 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002811 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002812 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002813 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002814 }
Eric Laurent599c7582015-12-07 18:05:55 -08002815 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002816 }
2817
Eric Laurentc722f302014-12-10 11:21:49 -08002818 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002819
Eric Laurent599c7582015-12-07 18:05:55 -08002820 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002821 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002822
Eric Laurent599c7582015-12-07 18:05:55 -08002823 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002824}
2825
Eric Laurent4eb58f12018-12-07 16:41:02 -08002826status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002827{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002828 ALOGV("%s portId %d", __FUNCTION__, portId);
2829
2830 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2831 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002832 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002833 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002835 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002836 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002837 if (client->active()) {
2838 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2839 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002840 }
2841
Eric Laurent8f42ea12018-08-08 09:08:25 -07002842 audio_session_t session = client->session();
2843
Eric Laurent4eb58f12018-12-07 16:41:02 -08002844 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002845
Eric Laurent4eb58f12018-12-07 16:41:02 -08002846 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002847
Eric Laurent4eb58f12018-12-07 16:41:02 -08002848 status_t status = inputDesc->start();
2849 if (status != NO_ERROR) {
2850 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002851 }
Eric Laurente552edb2014-03-10 17:42:56 -07002852
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002853 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002854 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002856
Eric Laurent8f42ea12018-08-08 09:08:25 -07002857 // indicate active capture to sound trigger service if starting capture from a mic on
2858 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002859 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002860 if (device != nullptr) {
2861 status = setInputDevice(input, device, true /* force */);
2862 } else {
2863 ALOGW("%s no new input device can be found for descriptor %d",
2864 __FUNCTION__, inputDesc->getId());
2865 status = BAD_VALUE;
2866 }
Eric Laurente552edb2014-03-10 17:42:56 -07002867
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002868 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002869 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002870 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002871 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002872 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2873 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002874 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002875 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002876
François Gaffie11d30102018-11-02 16:09:09 +01002877 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2878 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002879 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002880 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002881 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002882
Eric Laurent8f42ea12018-08-08 09:08:25 -07002883 // automatically enable the remote submix output when input is started if not
2884 // used by a policy mix of type MIX_TYPE_RECORDERS
2885 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002886 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002887 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002888 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002889 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002890 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2891 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002892 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002893 if (address != "") {
2894 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2895 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002896 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002897 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002898 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002899 } else if (status != NO_ERROR) {
2900 // Restore client activity state.
2901 inputDesc->setClientActive(client, false);
2902 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002903 }
2904
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002905 ALOGV("%s input %d source = %d status = %d exit",
2906 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002907
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002908 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002909}
2910
Eric Laurent8fc147b2018-07-22 19:13:55 -07002911status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002912{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002913 ALOGV("%s portId %d", __FUNCTION__, portId);
2914
2915 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2916 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002917 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002918 return BAD_VALUE;
2919 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002920 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002921 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002922 if (!client->active()) {
2923 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002924 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002925 }
Carter Hsue6139d52021-07-08 10:30:20 +08002926 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002927 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002928
Eric Laurent8f42ea12018-08-08 09:08:25 -07002929 inputDesc->stop();
2930 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002931 auto current_source = inputDesc->source();
2932 setInputDevice(input, getNewInputDevice(inputDesc),
2933 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002934 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002935 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002936 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002937 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002938 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2939 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002940 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002941 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002942
2943 // automatically disable the remote submix output when input is stopped if not
2944 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002945 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002946 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002947 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002948 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002949 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2950 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002951 }
2952 if (address != "") {
2953 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2954 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002955 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002956 }
2957 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002958 resetInputDevice(input);
2959
2960 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2961 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002962 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2963 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002964 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002965 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002966 }
2967 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002968 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002969 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002970}
2971
Eric Laurent8fc147b2018-07-22 19:13:55 -07002972void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002973{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002974 ALOGV("%s portId %d", __FUNCTION__, portId);
2975
2976 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2977 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002978 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002979 return;
2980 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002981 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002982 audio_io_handle_t input = inputDesc->mIoHandle;
2983
Eric Laurent8f42ea12018-08-08 09:08:25 -07002984 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002985
Andy Hung39efb7a2018-09-26 15:39:28 -07002986 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002987
Andy Hung39efb7a2018-09-26 15:39:28 -07002988 if (inputDesc->getClientCount() > 0) {
2989 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002990 return;
2991 }
2992
Eric Laurent05b90f82014-08-27 15:32:29 -07002993 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002994 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002995 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002996}
2997
Eric Laurent8f42ea12018-08-08 09:08:25 -07002998void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002999{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003000 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003001
3002 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003003 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003004 }
3005}
3006
Eric Laurent8f42ea12018-08-08 09:08:25 -07003007void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3008{
3009 stopInput(portId);
3010 releaseInput(portId);
3011}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003012
Eric Laurent0dd51852019-04-19 18:18:58 -07003013void AudioPolicyManager::checkCloseInputs() {
3014 // After connecting or disconnecting an input device, close input if:
3015 // - it has no client (was just opened to check profile) OR
3016 // - none of its supported devices are connected anymore OR
3017 // - one of its clients cannot be routed to one of its supported
3018 // devices anymore. Otherwise update device selection
3019 std::vector<audio_io_handle_t> inputsToClose;
3020 for (size_t i = 0; i < mInputs.size(); i++) {
3021 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3022 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003023 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003024 inputsToClose.push_back(mInputs.keyAt(i));
3025 } else {
3026 bool close = false;
3027 for (const auto& client : input->clientsList()) {
3028 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003029 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3030 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003031 if (!input->supportedDevices().contains(device)) {
3032 close = true;
3033 break;
3034 }
3035 }
3036 if (close) {
3037 inputsToClose.push_back(mInputs.keyAt(i));
3038 } else {
3039 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3040 }
3041 }
3042 }
3043
3044 for (const audio_io_handle_t handle : inputsToClose) {
3045 ALOGV("%s closing input %d", __func__, handle);
3046 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003047 }
Eric Laurentd4692962014-05-05 18:13:44 -07003048}
3049
François Gaffie251c7f02018-11-07 10:41:08 +01003050void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003051{
3052 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003053 if (indexMin < 0 || indexMax < 0) {
3054 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3055 return;
3056 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003057 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003058
3059 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003060 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3061 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003062 continue;
3063 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003064 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003065 }
Eric Laurente552edb2014-03-10 17:42:56 -07003066}
3067
Eric Laurente0720872014-03-11 09:30:41 -07003068status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003069 int index,
3070 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003071{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003072 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003073 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3074 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3075 return NO_ERROR;
3076 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003077 ALOGV("%s: stream %s attributes=%s", __func__,
3078 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003079 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003080}
3081
Eric Laurente0720872014-03-11 09:30:41 -07003082status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003083 int *index,
3084 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003085{
François Gaffiec005e562018-11-06 15:04:49 +01003086 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3087 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003088 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003089 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003090 deviceTypes = mEngine->getOutputDevicesForStream(
3091 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003092 }
jiabin9a3361e2019-10-01 09:38:30 -07003093 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003094}
3095
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003096status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003097 int index,
3098 audio_devices_t device)
3099{
3100 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003101 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3102 if (group == VOLUME_GROUP_NONE) {
3103 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003104 return BAD_VALUE;
3105 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003106 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003107 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003108 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003109 VolumeSource vs = toVolumeSource(group);
3110 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3111
3112 status = setVolumeCurveIndex(index, device, curves);
3113 if (status != NO_ERROR) {
3114 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3115 return status;
3116 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003117
jiabin9a3361e2019-10-01 09:38:30 -07003118 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003119 auto curCurvAttrs = curves.getAttributes();
3120 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3121 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003122 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003123 } else if (!curves.getStreamTypes().empty()) {
3124 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003125 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003126 } else {
3127 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3128 return BAD_VALUE;
3129 }
jiabin9a3361e2019-10-01 09:38:30 -07003130 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3131 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003132
François Gaffiecfe17322018-11-07 13:41:29 +01003133 // update volume on all outputs and streams matching the following:
3134 // - The requested stream (or a stream matching for volume control) is active on the output
3135 // - The device (or devices) selected by the engine for this stream includes
3136 // the requested device
3137 // - For non default requested device, currently selected device on the output is either the
3138 // requested device or one of the devices selected by the engine for this stream
3139 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3140 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003141 for (size_t i = 0; i < mOutputs.size(); i++) {
3142 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003143 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003144
jiabin9a3361e2019-10-01 09:38:30 -07003145 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3146 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003147 }
François Gaffieed91f582020-01-31 10:35:37 +01003148 if (!(desc->isActive(vs) || isInCall())) {
3149 continue;
3150 }
3151 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3152 curDevices.find(device) == curDevices.end()) {
3153 continue;
3154 }
3155 bool applyVolume = false;
3156 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3157 curSrcDevices.insert(device);
3158 applyVolume = (curSrcDevices.find(
3159 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3160 } else {
3161 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3162 }
3163 if (!applyVolume) {
3164 continue; // next output
3165 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003166 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3167 // If a higher priority strategy is active, and the output is routed to a device with a
3168 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003169 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003170 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003171 // If the volume source is active with higher priority source, ensure at least Sw Muted
3172 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003173 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3174 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3175 false /*preferredDevice*/);
3176 if (activeClients.empty()) {
3177 continue;
3178 }
3179 bool isPreempted = false;
3180 bool isHigherPriority = productStrategy < strategy;
3181 for (const auto &client : activeClients) {
3182 if (isHigherPriority && (client->volumeSource() != vs)) {
3183 ALOGV("%s: Strategy=%d (\nrequester:\n"
3184 " group %d, volumeGroup=%d attributes=%s)\n"
3185 " higher priority source active:\n"
3186 " volumeGroup=%d attributes=%s) \n"
3187 " on output %zu, bailing out", __func__, productStrategy,
3188 group, group, toString(attributes).c_str(),
3189 client->volumeSource(), toString(client->attributes()).c_str(), i);
3190 applyVolume = false;
3191 isPreempted = true;
3192 break;
3193 }
3194 // However, continue for loop to ensure no higher prio clients running on output
3195 if (client->volumeSource() == vs) {
3196 applyVolume = true;
3197 }
3198 }
3199 if (isPreempted || applyVolume) {
3200 break;
3201 }
3202 }
3203 if (!applyVolume) {
3204 continue; // next output
3205 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003206 }
François Gaffieed91f582020-01-31 10:35:37 +01003207 //FIXME: workaround for truncated touch sounds
3208 // delayed volume change for system stream to be removed when the problem is
3209 // handled by system UI
3210 status_t volStatus = checkAndSetVolume(
3211 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003212 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003213 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3214 if (volStatus != NO_ERROR) {
3215 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003216 }
3217 }
François Gaffiecfe17322018-11-07 13:41:29 +01003218 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3219 return status;
3220}
3221
François Gaffieaaac0fd2018-11-22 17:56:39 +01003222status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003223 audio_devices_t device,
3224 IVolumeCurves &volumeCurves)
3225{
3226 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3227 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003228 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3229 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003230 (index > volumeCurves.getVolumeIndexMax())) {
3231 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3232 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3233 return BAD_VALUE;
3234 }
3235 if (!audio_is_output_device(device)) {
3236 return BAD_VALUE;
3237 }
3238
3239 // Force max volume if stream cannot be muted
3240 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3241
François Gaffieaaac0fd2018-11-22 17:56:39 +01003242 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003243 volumeCurves.addCurrentVolumeIndex(device, index);
3244 return NO_ERROR;
3245}
3246
3247status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3248 int &index,
3249 audio_devices_t device)
3250{
3251 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3252 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003253 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003254 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003255 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003256 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003257 }
jiabin9a3361e2019-10-01 09:38:30 -07003258 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003259}
3260
3261status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3262 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003263 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003264{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003265 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003266 return BAD_VALUE;
3267 }
jiabin9a3361e2019-10-01 09:38:30 -07003268 index = curves.getVolumeIndex(deviceTypes);
3269 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003270 return NO_ERROR;
3271}
3272
3273status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3274 int &index)
3275{
3276 index = getVolumeCurves(attr).getVolumeIndexMin();
3277 return NO_ERROR;
3278}
3279
3280status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3281 int &index)
3282{
3283 index = getVolumeCurves(attr).getVolumeIndexMax();
3284 return NO_ERROR;
3285}
3286
Eric Laurent36829f92017-04-07 19:04:42 -07003287audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003288{
3289 // select one output among several suitable for global effects.
3290 // The priority is as follows:
3291 // 1: An offloaded output. If the effect ends up not being offloadable,
3292 // AudioFlinger will invalidate the track and the offloaded output
3293 // will be closed causing the effect to be moved to a PCM output.
3294 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003295 // 3: The primary output
3296 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003297
François Gaffiec005e562018-11-06 15:04:49 +01003298 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3299 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003300 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003301
Eric Laurent36829f92017-04-07 19:04:42 -07003302 if (outputs.size() == 0) {
3303 return AUDIO_IO_HANDLE_NONE;
3304 }
Eric Laurente552edb2014-03-10 17:42:56 -07003305
Eric Laurent36829f92017-04-07 19:04:42 -07003306 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3307 bool activeOnly = true;
3308
3309 while (output == AUDIO_IO_HANDLE_NONE) {
3310 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3311 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3312 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3313
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003314 for (audio_io_handle_t output : outputs) {
3315 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003316 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003317 continue;
3318 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003319 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3320 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003321 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003322 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003323 }
3324 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003325 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003326 }
3327 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003328 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003329 }
3330 }
3331 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3332 output = outputOffloaded;
3333 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3334 output = outputDeepBuffer;
3335 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3336 output = outputPrimary;
3337 } else {
3338 output = outputs[0];
3339 }
3340 activeOnly = false;
3341 }
3342
3343 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003344 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003345 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3346 mMusicEffectOutput = output;
3347 }
3348
3349 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003350 return output;
3351}
3352
Eric Laurent36829f92017-04-07 19:04:42 -07003353audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3354{
3355 return selectOutputForMusicEffects();
3356}
3357
Eric Laurente0720872014-03-11 09:30:41 -07003358status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003359 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003360 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003361 int session,
3362 int id)
3363{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003364 if (session != AUDIO_SESSION_DEVICE) {
3365 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003366 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003367 index = mInputs.indexOfKey(io);
3368 if (index < 0) {
3369 ALOGW("registerEffect() unknown io %d", io);
3370 return INVALID_OPERATION;
3371 }
Eric Laurente552edb2014-03-10 17:42:56 -07003372 }
3373 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003374 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3375 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3376 || strategy == PRODUCT_STRATEGY_NONE));
3377 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003378}
3379
Eric Laurentc241b0d2018-11-28 09:08:49 -08003380status_t AudioPolicyManager::unregisterEffect(int id)
3381{
3382 if (mEffects.getEffect(id) == nullptr) {
3383 return INVALID_OPERATION;
3384 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003385 if (mEffects.isEffectEnabled(id)) {
3386 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3387 setEffectEnabled(id, false);
3388 }
3389 return mEffects.unregisterEffect(id);
3390}
3391
3392status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3393{
3394 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3395 if (effect == nullptr) {
3396 return INVALID_OPERATION;
3397 }
3398
3399 status_t status = mEffects.setEffectEnabled(id, enabled);
3400 if (status == NO_ERROR) {
3401 mInputs.trackEffectEnabled(effect, enabled);
3402 }
3403 return status;
3404}
3405
Eric Laurent6c796322019-04-09 14:13:17 -07003406
3407status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3408{
3409 mEffects.moveEffects(ids, io);
3410 return NO_ERROR;
3411}
3412
Eric Laurentc75307b2015-03-17 15:29:32 -07003413bool AudioPolicyManager::isStreamActive(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.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003417}
3418
3419bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3420{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003421 auto vs = toVolumeSource(stream, false);
3422 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003423}
3424
Eric Laurente0720872014-03-11 09:30:41 -07003425bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003426{
3427 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003428 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003429 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003430 return true;
3431 }
3432 }
3433 return false;
3434}
3435
Eric Laurent275e8e92014-11-30 15:14:47 -08003436// Register a list of custom mixes with their attributes and format.
3437// When a mix is registered, corresponding input and output profiles are
3438// added to the remote submix hw module. The profile contains only the
3439// parameters (sampling rate, format...) specified by the mix.
3440// The corresponding input remote submix device is also connected.
3441//
3442// When a remote submix device is connected, the address is checked to select the
3443// appropriate profile and the corresponding input or output stream is opened.
3444//
3445// When capture starts, getInputForAttr() will:
3446// - 1 look for a mix matching the address passed in attribtutes tags if any
3447// - 2 if none found, getDeviceForInputSource() will:
3448// - 2.1 look for a mix matching the attributes source
3449// - 2.2 if none found, default to device selection by policy rules
3450// At this time, the corresponding output remote submix device is also connected
3451// and active playback use cases can be transferred to this mix if needed when reconnecting
3452// after AudioTracks are invalidated
3453//
3454// When playback starts, getOutputForAttr() will:
3455// - 1 look for a mix matching the address passed in attribtutes tags if any
3456// - 2 if none found, look for a mix matching the attributes usage
3457// - 3 if none found, default to device and output selection by policy rules.
3458
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003459status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003460{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003461 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3462 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003463 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003464 sp<HwModule> rSubmixModule;
3465 // examine each mix's route type
3466 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003467 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003468 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3469 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3470 ALOGE("Unsupported Policy Mix %zu of %zu: "
3471 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3472 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003473 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003474 break;
3475 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003476 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3477 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003478 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003479 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3480 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003481 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003482 rSubmixModule = mHwModules.getModuleFromName(
3483 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3484 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003485 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003486 i);
3487 res = INVALID_OPERATION;
3488 break;
3489 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003490 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003491
Eric Laurent97ac8712018-07-27 18:59:02 -07003492 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003493 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003494 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003495 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003496 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3497 } else {
3498 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3499 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003500 }
François Gaffie036e1e92015-03-19 10:16:24 +01003501
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003502 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003503 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003504 res = INVALID_OPERATION;
3505 break;
3506 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003507 audio_config_t outputConfig = mix.mFormat;
3508 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003509 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3510 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003511 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3512 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003513 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003514 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003515 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003516 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003517
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003518 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003519 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3520 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3521 ALOGE("Failed to set remote submix device available, type %u, address %s",
3522 mix.mDeviceType, address.string());
3523 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003524 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003525 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3526 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003527 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003528 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003529 i, mixes.size(), type, address.string());
3530
3531 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3532 mix.mDeviceType, mix.mDeviceAddress,
3533 String8(), AUDIO_FORMAT_DEFAULT);
3534 if (device == nullptr) {
3535 res = INVALID_OPERATION;
3536 break;
3537 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003538
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003539 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003540 // First try to find an already opened output supporting the device
3541 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003542 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003543
Eric Laurentc529cf62020-04-17 18:19:10 -07003544 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003545 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003546 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3547 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003548 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003549 } else {
3550 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003551 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003552 }
3553 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003554 // If no output found, try to find a direct output profile supporting the device
3555 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3556 sp<HwModule> module = mHwModules[i];
3557 for (size_t j = 0;
3558 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3559 j++) {
3560 sp<IOProfile> profile = module->getOutputProfiles()[j];
3561 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3562 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3563 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3564 address.string());
3565 res = INVALID_OPERATION;
3566 } else {
3567 foundOutput = true;
3568 }
3569 }
3570 }
3571 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003572 if (res != NO_ERROR) {
3573 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003574 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003575 res = INVALID_OPERATION;
3576 break;
3577 } else if (!foundOutput) {
3578 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003579 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003580 res = INVALID_OPERATION;
3581 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003582 } else {
3583 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003584 }
Eric Laurentc722f302014-12-10 11:21:49 -08003585 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003586 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003587 if (res != NO_ERROR) {
3588 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003589 } else if (checkOutputs) {
3590 checkForDeviceAndOutputChanges();
3591 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003592 }
3593 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003594}
3595
3596status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3597{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003598 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003599 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003600 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003601 sp<HwModule> rSubmixModule;
3602 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003603 for (const auto& mix : mixes) {
3604 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003605
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003606 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003607 rSubmixModule = mHwModules.getModuleFromName(
3608 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3609 if (rSubmixModule == 0) {
3610 res = INVALID_OPERATION;
3611 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003612 }
3613 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003614
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003615 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003616
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003617 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003618 res = INVALID_OPERATION;
3619 continue;
3620 }
3621
Kevin Rocard04ed0462019-05-02 17:53:24 -07003622 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3623 if (getDeviceConnectionState(device, address.string()) ==
3624 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3625 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3626 address.string(), "remote-submix",
3627 AUDIO_FORMAT_DEFAULT);
3628 if (res != OK) {
3629 ALOGE("Error making RemoteSubmix device unavailable for mix "
3630 "with type %d, address %s", device, address.string());
3631 }
3632 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003633 }
jiabin5740f082019-08-19 15:08:30 -07003634 rSubmixModule->removeOutputProfile(address.c_str());
3635 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003636
Kevin Rocard153f92d2018-12-18 18:33:28 -08003637 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003638 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003639 res = INVALID_OPERATION;
3640 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003641 } else {
3642 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003643 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003644 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003645 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003646 if (res == NO_ERROR && checkOutputs) {
3647 checkForDeviceAndOutputChanges();
3648 updateCallAndOutputRouting();
3649 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003650 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003651}
3652
Mikhail Naganov100f0122018-11-29 11:22:16 -08003653void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3654{
3655 size_t i = 0;
3656 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3657 for (const auto& fmt : mManualSurroundFormats) {
3658 if (i++ != 0) dst->append(", ");
3659 std::string sfmt;
3660 FormatConverter::toString(fmt, sfmt);
3661 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3662 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3663 }
3664}
3665
Eric Laurentc529cf62020-04-17 18:19:10 -07003666// Returns true if all devices types match the predicate and are supported by one HW module
3667bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003668 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003669 std::function<bool(audio_devices_t)> predicate,
3670 const char *context) {
3671 for (size_t i = 0; i < devices.size(); i++) {
3672 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003673 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003674 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003675 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003676 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003677 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003678 return false;
3679 }
3680 }
3681 return true;
3682}
3683
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003684status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003685 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003686 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003687 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3688 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003689 }
3690 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003691 if (res != NO_ERROR) {
3692 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3693 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003694 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003695
3696 checkForDeviceAndOutputChanges();
3697 updateCallAndOutputRouting();
3698
3699 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003700}
3701
3702status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3703 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003704 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3705 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003706 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003707 __FUNCTION__, uid);
3708 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003709 }
3710
Eric Laurentc529cf62020-04-17 18:19:10 -07003711 checkForDeviceAndOutputChanges();
3712 updateCallAndOutputRouting();
3713
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003714 return res;
3715}
3716
Eric Laurent2517af32020-11-25 15:31:27 +01003717
jiabin0a488932020-08-07 17:32:40 -07003718status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3719 device_role_t role,
3720 const AudioDeviceTypeAddrVector &devices) {
3721 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3722 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003723
Eric Laurentc529cf62020-04-17 18:19:10 -07003724 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003725 return BAD_VALUE;
3726 }
jiabin0a488932020-08-07 17:32:40 -07003727 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003728 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003729 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3730 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003731 return status;
3732 }
3733
3734 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003735
3736 bool forceVolumeReeval = false;
3737 // FIXME: workaround for truncated touch sounds
3738 // to be removed when the problem is handled by system UI
3739 uint32_t delayMs = 0;
3740 if (strategy == mCommunnicationStrategy) {
3741 forceVolumeReeval = true;
3742 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3743 updateInputRouting();
3744 }
3745 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003746
3747 return NO_ERROR;
3748}
3749
3750void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3751{
3752 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003753 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003754 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003755 // Only apply special touch sound delay once
3756 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003757 }
3758 for (size_t i = 0; i < mOutputs.size(); i++) {
3759 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3760 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003761 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3762 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003763 // As done in setDeviceConnectionState, we could also fix default device issue by
3764 // preventing the force re-routing in case of default dev that distinguishes on address.
3765 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003766 bool forceRouting = !newDevices.isEmpty();
3767 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3768 true /*requiresMuteCheck*/,
3769 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003770 // Only apply special touch sound delay once
3771 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003772 }
3773 if (forceVolumeReeval && !newDevices.isEmpty()) {
3774 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3775 }
3776 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003777 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003778}
3779
Eric Laurent2517af32020-11-25 15:31:27 +01003780void AudioPolicyManager::updateInputRouting() {
3781 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303782 // Skip for hotword recording as the input device switch
3783 // is handled within sound trigger HAL
3784 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3785 continue;
3786 }
Eric Laurent2517af32020-11-25 15:31:27 +01003787 auto newDevice = getNewInputDevice(activeDesc);
3788 // Force new input selection if the new device can not be reached via current input
3789 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3790 setInputDevice(activeDesc->mIoHandle, newDevice);
3791 } else {
3792 closeInput(activeDesc->mIoHandle);
3793 }
3794 }
3795}
3796
jiabin0a488932020-08-07 17:32:40 -07003797status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3798 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003799{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003800 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003801
jiabin0a488932020-08-07 17:32:40 -07003802 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003803 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003804 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3805 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003806 return status;
3807 }
3808
3809 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003810
3811 bool forceVolumeReeval = false;
3812 // FIXME: workaround for truncated touch sounds
3813 // to be removed when the problem is handled by system UI
3814 uint32_t delayMs = 0;
3815 if (strategy == mCommunnicationStrategy) {
3816 forceVolumeReeval = true;
3817 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3818 updateInputRouting();
3819 }
3820 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003821
3822 return NO_ERROR;
3823}
3824
jiabin0a488932020-08-07 17:32:40 -07003825status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3826 device_role_t role,
3827 AudioDeviceTypeAddrVector &devices) {
3828 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003829}
3830
Jiabin Huang3b98d322020-09-03 17:54:16 +00003831status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3832 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3833 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3834 dumpAudioDeviceTypeAddrVector(devices).c_str());
3835
Mikhail Naganov55773032020-10-01 15:08:13 -07003836 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003837 return BAD_VALUE;
3838 }
3839 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3840 ALOGW_IF(status != NO_ERROR,
3841 "Engine could not set preferred devices %s for audio source %d role %d",
3842 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3843
3844 return status;
3845}
3846
3847status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3848 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3849 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3850 dumpAudioDeviceTypeAddrVector(devices).c_str());
3851
Mikhail Naganov55773032020-10-01 15:08:13 -07003852 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003853 return BAD_VALUE;
3854 }
3855 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3856 ALOGW_IF(status != NO_ERROR,
3857 "Engine could not add preferred devices %s for audio source %d role %d",
3858 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3859
Eric Laurent2517af32020-11-25 15:31:27 +01003860 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003861 return status;
3862}
3863
3864status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3865 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3866{
3867 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3868 dumpAudioDeviceTypeAddrVector(devices).c_str());
3869
Mikhail Naganov55773032020-10-01 15:08:13 -07003870 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003871 return BAD_VALUE;
3872 }
3873
3874 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3875 audioSource, role, devices);
3876 ALOGW_IF(status != NO_ERROR,
3877 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3878
Eric Laurent2517af32020-11-25 15:31:27 +01003879 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003880 return status;
3881}
3882
3883status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3884 device_role_t role) {
3885 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3886
3887 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3888 ALOGW_IF(status != NO_ERROR,
3889 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3890
Eric Laurent2517af32020-11-25 15:31:27 +01003891 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003892 return status;
3893}
3894
3895status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3896 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3897 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3898}
3899
Oscar Azucena90e77632019-11-27 17:12:28 -08003900status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003901 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003902 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003903 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3904 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003905 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003906 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3907 if (status != NO_ERROR) {
3908 ALOGE("%s() could not set device affinity for userId %d",
3909 __FUNCTION__, userId);
3910 return status;
3911 }
3912
3913 // reevaluate outputs for all devices
3914 checkForDeviceAndOutputChanges();
3915 updateCallAndOutputRouting();
3916
3917 return NO_ERROR;
3918}
3919
3920status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003921 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003922 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3923 if (status != NO_ERROR) {
3924 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3925 __FUNCTION__, userId);
3926 return status;
3927 }
3928
3929 // reevaluate outputs for all devices
3930 checkForDeviceAndOutputChanges();
3931 updateCallAndOutputRouting();
3932
3933 return NO_ERROR;
3934}
3935
Andy Hungc29d82b2018-10-05 12:23:17 -07003936void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003937{
Andy Hungc29d82b2018-10-05 12:23:17 -07003938 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003939 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003940 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003941 std::string stateLiteral;
3942 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003943 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003944 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3945 "communications", "media", "record", "dock", "system",
3946 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3947 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3948 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003949 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3950 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3951 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3952 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3953 dst->append(" (MANUAL: ");
3954 dumpManualSurroundFormats(dst);
3955 dst->append(")");
3956 }
3957 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003958 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003959 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3960 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003961 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003962 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003963
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003964 dst->append("\n");
3965 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3966 dst->append("\n");
3967 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003968 mHwModulesAll.dump(dst);
3969 mOutputs.dump(dst);
3970 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003971 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003972 mAudioPatches.dump(dst);
3973 mPolicyMixes.dump(dst);
3974 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003975
Kevin Rocardb99cc752019-03-21 20:52:24 -07003976 dst->appendFormat(" AllowedCapturePolicies:\n");
3977 for (auto& policy : mAllowedCapturePolicies) {
3978 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3979 }
3980
jiabina84c3d32022-12-02 18:59:55 +00003981 dst->appendFormat(" Preferred mixer audio configuration:\n");
3982 for (const auto it : mPreferredMixerAttrInfos) {
3983 dst->appendFormat(" - device port id: %d\n", it.first);
3984 for (const auto preferredMixerInfoIt : it.second) {
3985 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
3986 preferredMixerInfoIt.second->dump(dst);
3987 }
3988 }
3989
François Gaffiec005e562018-11-06 15:04:49 +01003990 dst->appendFormat("\nPolicy Engine dump:\n");
3991 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003992}
3993
3994status_t AudioPolicyManager::dump(int fd)
3995{
3996 String8 result;
3997 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003998 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003999 return NO_ERROR;
4000}
4001
Kevin Rocardb99cc752019-03-21 20:52:24 -07004002status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4003{
4004 mAllowedCapturePolicies[uid] = capturePolicy;
4005 return NO_ERROR;
4006}
4007
Eric Laurente552edb2014-03-10 17:42:56 -07004008// This function checks for the parameters which can be offloaded.
4009// This can be enhanced depending on the capability of the DSP and policy
4010// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004011audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004012{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004013 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004014 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004015 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004016 offloadInfo.format,
4017 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4018 offloadInfo.has_video);
4019
jiabin2b9d5a12021-12-10 01:06:29 +00004020 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004021 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004022 }
4023
4024 // See if there is a profile to support this.
4025 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004026 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004027 offloadInfo.sample_rate,
4028 offloadInfo.format,
4029 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004030 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4031 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004032 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4033 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4034 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004035 if (profile == nullptr) {
4036 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4037 }
4038 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4039 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4040 }
4041 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004042}
4043
Michael Chana94fbb22018-04-24 14:31:19 +10004044bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4045 const audio_attributes_t& attributes) {
4046 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004047 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004048 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4049 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004050 config.sample_rate,
4051 config.format,
4052 config.channel_mask,
4053 output_flags,
4054 true /* directOnly */);
4055 ALOGV("%s() profile %sfound with name: %s, "
4056 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4057 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004058 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004059 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004060
4061 // also try the MSD module if compatible profile not found
4062 if (profile == nullptr) {
4063 profile = getMsdProfileForOutput(outputDevices,
4064 config.sample_rate,
4065 config.format,
4066 config.channel_mask,
4067 output_flags,
4068 true /* directOnly */);
4069 ALOGV("%s() MSD profile %sfound with name: %s, "
4070 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4071 __FUNCTION__, profile != 0 ? "" : "NOT ",
4072 (profile != 0 ? profile->getTagName().c_str() : "null"),
4073 config.sample_rate, config.format, config.channel_mask, output_flags);
4074 }
4075 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004076}
4077
jiabin2b9d5a12021-12-10 01:06:29 +00004078bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4079 bool durationIgnored) {
4080 if (mMasterMono) {
4081 return false; // no offloading if mono is set.
4082 }
4083
4084 // Check if offload has been disabled
4085 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4086 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4087 return false;
4088 }
4089
4090 // Check if stream type is music, then only allow offload as of now.
4091 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4092 {
4093 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4094 return false;
4095 }
4096
4097 //TODO: enable audio offloading with video when ready
4098 const bool allowOffloadWithVideo =
4099 property_get_bool("audio.offload.video", false /* default_value */);
4100 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4101 ALOGV("%s: has_video == true, returning false", __func__);
4102 return false;
4103 }
4104
4105 //If duration is less than minimum value defined in property, return false
4106 const int min_duration_secs = property_get_int32(
4107 "audio.offload.min.duration.secs", -1 /* default_value */);
4108 if (!durationIgnored) {
4109 if (min_duration_secs >= 0) {
4110 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4111 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4112 __func__, min_duration_secs);
4113 return false;
4114 }
4115 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4116 ALOGV("%s: Offload denied by duration < default min(=%u)",
4117 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4118 return false;
4119 }
4120 }
4121
4122 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4123 // creating an offloaded track and tearing it down immediately after start when audioflinger
4124 // detects there is an active non offloadable effect.
4125 // FIXME: We should check the audio session here but we do not have it in this context.
4126 // This may prevent offloading in rare situations where effects are left active by apps
4127 // in the background.
4128 if (mEffects.isNonOffloadableEffectEnabled()) {
4129 return false;
4130 }
4131
4132 return true;
4133}
4134
4135audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4136 const audio_config_t *config) {
4137 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4138 offloadInfo.format = config->format;
4139 offloadInfo.sample_rate = config->sample_rate;
4140 offloadInfo.channel_mask = config->channel_mask;
4141 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4142 offloadInfo.has_video = false;
4143 offloadInfo.is_streaming = false;
4144 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4145
4146 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4147 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4148 audio_flags_to_audio_output_flags(attr->flags, &flags);
4149 // only retain flags that will drive compressed offload or passthrough
4150 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4151 if (offloadPossible) {
4152 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4153 }
4154 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4155
Dorin Drimusfae3c642022-03-17 18:36:30 +01004156 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004157 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004158 DeviceVector outputDevices = engineOutputDevices;
4159 // the MSD module checks for different conditions and output devices
4160 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4161 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4162 continue;
4163 }
4164 outputDevices = getMsdAudioOutDevices();
4165 }
jiabin2b9d5a12021-12-10 01:06:29 +00004166 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004167 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004168 config->sample_rate, nullptr /*updatedSamplingRate*/,
4169 config->format, nullptr /*updatedFormat*/,
4170 config->channel_mask, nullptr /*updatedChannelMask*/,
4171 flags)) {
4172 continue;
4173 }
4174 // reject profiles not corresponding to a device currently available
4175 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4176 continue;
4177 }
4178 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4179 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004180 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004181 != AUDIO_DIRECT_NOT_SUPPORTED) {
4182 // Already reports offload gapless supported. No need to report offload support.
4183 continue;
4184 }
4185 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4186 != AUDIO_OUTPUT_FLAG_NONE) {
4187 // If offload gapless is reported, no need to report offload support.
4188 directMode = (audio_direct_mode_t) ((directMode &
4189 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4190 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4191 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004192 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004193 }
4194 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004195 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004196 }
4197 }
4198 }
4199 return directMode;
4200}
4201
Dorin Drimusf2196d82022-01-03 12:11:18 +01004202status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4203 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004204 if (mEffects.isNonOffloadableEffectEnabled()) {
4205 return OK;
4206 }
jiabinf1c73972022-04-14 16:28:52 -07004207 DeviceVector devices;
4208 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004209 if (status != OK) {
4210 return status;
4211 }
4212 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4213 if (devices.empty()) {
4214 return OK; // no output devices for the attributes
4215 }
jiabinf1c73972022-04-14 16:28:52 -07004216 return getProfilesForDevices(devices, audioProfilesVector,
4217 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004218}
4219
jiabina84c3d32022-12-02 18:59:55 +00004220status_t AudioPolicyManager::getSupportedMixerAttributes(
4221 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4222 ALOGV("%s, portId=%d", __func__, portId);
4223 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4224 if (deviceDescriptor == nullptr) {
4225 ALOGE("%s the requested device is currently unavailable", __func__);
4226 return BAD_VALUE;
4227 }
4228 for (const auto& hwModule : mHwModules) {
4229 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4230 if (curProfile->supportsDevice(deviceDescriptor)) {
4231 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4232 }
4233 }
4234 }
4235 return NO_ERROR;
4236}
4237
4238status_t AudioPolicyManager::setPreferredMixerAttributes(
4239 const audio_attributes_t *attr,
4240 audio_port_handle_t portId,
4241 uid_t uid,
4242 const audio_mixer_attributes_t *mixerAttributes) {
4243 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4244 "mixerBehavior=%d}, uid=%d, portId=%u",
4245 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4246 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4247 mixerAttributes->mixer_behavior, uid, portId);
4248 if (attr->usage != AUDIO_USAGE_MEDIA) {
4249 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4250 return BAD_VALUE;
4251 }
4252 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4253 if (deviceDescriptor == nullptr) {
4254 ALOGE("%s the requested device is currently unavailable", __func__);
4255 return BAD_VALUE;
4256 }
4257 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4258 ALOGE("%s(%d), type=%d, is not a usb output device",
4259 __func__, portId, deviceDescriptor->type());
4260 return BAD_VALUE;
4261 }
4262
4263 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4264 audio_flags_to_audio_output_flags(attr->flags, &flags);
4265 flags = (audio_output_flags_t) (flags |
4266 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4267 sp<IOProfile> profile = nullptr;
4268 DeviceVector devices(deviceDescriptor);
4269 for (const auto& hwModule : mHwModules) {
4270 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4271 if (curProfile->hasDynamicAudioProfile()
4272 && curProfile->isCompatibleProfile(devices,
4273 mixerAttributes->config.sample_rate,
4274 nullptr /*updatedSamplingRate*/,
4275 mixerAttributes->config.format,
4276 nullptr /*updatedFormat*/,
4277 mixerAttributes->config.channel_mask,
4278 nullptr /*updatedChannelMask*/,
4279 flags,
4280 false /*exactMatchRequiredForInputFlags*/)) {
4281 profile = curProfile;
4282 break;
4283 }
4284 }
4285 }
4286 if (profile == nullptr) {
4287 ALOGE("%s, there is no compatible profile found", __func__);
4288 return BAD_VALUE;
4289 }
4290
4291 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4292 sp<PreferredMixerAttributesInfo>::make(
4293 uid, portId, profile, flags, *mixerAttributes);
4294 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4295 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4296
4297 // If 1) there is any client from the preferred mixer configuration owner that is currently
4298 // active and matches the strategy and 2) current output is on the preferred device and the
4299 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4300 // configuration.
4301 std::vector<audio_io_handle_t> outputsToReopen;
4302 for (size_t i = 0; i < mOutputs.size(); i++) {
4303 const auto output = mOutputs.valueAt(i);
4304 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)
4305 && !output->isConfigurationMatched(mixerAttributes->config, flags)) {
4306 for (const auto& client : output->getActiveClients()) {
4307 if (client->uid() == uid && client->strategy() == strategy) {
4308 client->setIsInvalid();
4309 outputsToReopen.push_back(output->mIoHandle);
4310 }
4311 }
4312 }
4313 }
4314 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4315 config.sample_rate = mixerAttributes->config.sample_rate;
4316 config.channel_mask = mixerAttributes->config.channel_mask;
4317 config.format = mixerAttributes->config.format;
4318 for (const auto output : outputsToReopen) {
4319 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4320 }
4321
4322 return NO_ERROR;
4323}
4324
4325sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4326 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4327 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4328 if (it == mPreferredMixerAttrInfos.end()) {
4329 return nullptr;
4330 }
4331 auto mixerAttrInfoIt = it->second.find(strategy);
4332 if (mixerAttrInfoIt == it->second.end()) {
4333 return nullptr;
4334 }
4335 return mixerAttrInfoIt->second;
4336}
4337
4338status_t AudioPolicyManager::getPreferredMixerAttributes(
4339 const audio_attributes_t *attr,
4340 audio_port_handle_t portId,
4341 audio_mixer_attributes_t* mixerAttributes) {
4342 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4343 portId, mEngine->getProductStrategyForAttributes(*attr));
4344 if (info == nullptr) {
4345 return NAME_NOT_FOUND;
4346 }
4347 *mixerAttributes = info->getMixerAttributes();
4348 return NO_ERROR;
4349}
4350
4351status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4352 audio_port_handle_t portId,
4353 uid_t uid) {
4354 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4355 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4356 if (preferredMixerAttrInfo == nullptr) {
4357 return NAME_NOT_FOUND;
4358 }
4359 if (preferredMixerAttrInfo->getUid() != uid) {
4360 ALOGE("%s, requested uid=%d, owned uid=%d",
4361 __func__, uid, preferredMixerAttrInfo->getUid());
4362 return PERMISSION_DENIED;
4363 }
4364 mPreferredMixerAttrInfos[portId].erase(strategy);
4365 if (mPreferredMixerAttrInfos[portId].empty()) {
4366 mPreferredMixerAttrInfos.erase(portId);
4367 }
4368
4369 // Reconfig existing output
4370 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4371 for (size_t i = 0; i < mOutputs.size(); i++) {
4372 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4373 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4374 }
4375 }
4376 for (const auto output : potentialOutputsToReopen) {
4377 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4378 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4379 preferredMixerAttrInfo->getFlags())) {
4380 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4381 }
4382 }
4383 return NO_ERROR;
4384}
4385
Eric Laurent6a94d692014-05-20 11:18:06 -07004386status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4387 audio_port_type_t type,
4388 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004389 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004390 unsigned int *generation)
4391{
jiabin19cdba52020-11-24 11:28:58 -08004392 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4393 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004394 return BAD_VALUE;
4395 }
4396 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004397 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004398 *num_ports = 0;
4399 }
4400
4401 size_t portsWritten = 0;
4402 size_t portsMax = *num_ports;
4403 *num_ports = 0;
4404 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004405 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4406 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004407 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004408 for (const auto& dev : mAvailableOutputDevices) {
4409 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004410 continue;
4411 }
4412 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004413 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004414 }
4415 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004416 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004417 }
4418 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004419 for (const auto& dev : mAvailableInputDevices) {
4420 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004421 continue;
4422 }
4423 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004424 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004425 }
4426 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004427 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004428 }
4429 }
4430 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4431 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4432 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4433 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4434 }
4435 *num_ports += mInputs.size();
4436 }
4437 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004438 size_t numOutputs = 0;
4439 for (size_t i = 0; i < mOutputs.size(); i++) {
4440 if (!mOutputs[i]->isDuplicated()) {
4441 numOutputs++;
4442 if (portsWritten < portsMax) {
4443 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4444 }
4445 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004446 }
Eric Laurent84c70242014-06-23 08:46:27 -07004447 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004448 }
4449 }
jiabina84c3d32022-12-02 18:59:55 +00004450
Eric Laurent6a94d692014-05-20 11:18:06 -07004451 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004452 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004453 return NO_ERROR;
4454}
4455
jiabin19cdba52020-11-24 11:28:58 -08004456status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004457{
Eric Laurent99fcae42018-05-17 16:59:18 -07004458 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4459 return BAD_VALUE;
4460 }
4461 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4462 if (dev != 0) {
4463 dev->toAudioPort(port);
4464 return NO_ERROR;
4465 }
4466 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4467 if (dev != 0) {
4468 dev->toAudioPort(port);
4469 return NO_ERROR;
4470 }
4471 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4472 if (out != 0) {
4473 out->toAudioPort(port);
4474 return NO_ERROR;
4475 }
4476 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4477 if (in != 0) {
4478 in->toAudioPort(port);
4479 return NO_ERROR;
4480 }
4481 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004482}
4483
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004484status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4485 audio_patch_handle_t *handle,
4486 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004487{
François Gaffieafd4cea2019-11-18 15:50:22 +01004488 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004489 if (handle == NULL || patch == NULL) {
4490 return BAD_VALUE;
4491 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004492 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004493 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004494 return BAD_VALUE;
4495 }
4496 // only one source per audio patch supported for now
4497 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004498 return INVALID_OPERATION;
4499 }
Eric Laurent874c42872014-08-08 15:13:39 -07004500 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004501 return INVALID_OPERATION;
4502 }
Eric Laurent874c42872014-08-08 15:13:39 -07004503 for (size_t i = 0; i < patch->num_sinks; i++) {
4504 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4505 return INVALID_OPERATION;
4506 }
4507 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004508
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004509 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4510 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4511 if (srcDevice == nullptr || sinkDevice == nullptr) {
4512 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4513 return BAD_VALUE;
4514 }
4515 ALOGV("%s between source %s and sink %s", __func__,
4516 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4517 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4518 // Default attributes, default volume priority, not to infer with non raw audio patches.
4519 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4520 const struct audio_port_config *source = &patch->sources[0];
4521 sp<SourceClientDescriptor> sourceDesc =
4522 new InternalSourceClientDescriptor(
4523 portId, uid, attributes, *source, srcDevice, sinkDevice,
4524 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4525
4526 status_t status =
4527 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4528
4529 if (status != NO_ERROR) {
4530 return INVALID_OPERATION;
4531 }
4532 mAudioSources.add(portId, sourceDesc);
4533 return NO_ERROR;
4534}
4535
4536status_t AudioPolicyManager::connectAudioSourceToSink(
4537 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4538 const struct audio_patch *patch,
4539 audio_patch_handle_t &handle,
4540 uid_t uid, uint32_t delayMs)
4541{
4542 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4543 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4544 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4545 return INVALID_OPERATION;
4546 }
4547 sourceDesc->connect(handle, sinkDevice);
4548 if (isMsdPatch(handle)) {
4549 return NO_ERROR;
4550 }
4551 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4552 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4553 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4554 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4555 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4556 goto FailurePatchAdded;
4557 }
4558 status = swOutput->start();
4559 if (status != NO_ERROR) {
4560 goto FailureSourceAdded;
4561 }
4562 swOutput->addClient(sourceDesc);
4563 status = startSource(swOutput, sourceDesc, &delayMs);
4564 if (status != NO_ERROR) {
4565 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4566 goto FailureSourceActive;
4567 }
4568 if (delayMs != 0) {
4569 usleep(delayMs * 1000);
4570 }
4571 return NO_ERROR;
4572
4573FailureSourceActive:
4574 swOutput->stop();
4575 releaseOutput(sourceDesc->portId());
4576FailureSourceAdded:
4577 sourceDesc->setSwOutput(nullptr);
4578FailurePatchAdded:
4579 releaseAudioPatchInternal(handle);
4580 return INVALID_OPERATION;
4581}
4582
4583status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4584 audio_patch_handle_t *handle,
4585 uid_t uid, uint32_t delayMs,
4586 const sp<SourceClientDescriptor>& sourceDesc)
4587{
4588 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004589 sp<AudioPatch> patchDesc;
4590 ssize_t index = mAudioPatches.indexOfKey(*handle);
4591
François Gaffieafd4cea2019-11-18 15:50:22 +01004592 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4593 patch->sources[0].role,
4594 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004595#if LOG_NDEBUG == 0
4596 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004597 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4598 patch->sinks[i].role,
4599 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004600 }
4601#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004602
4603 if (index >= 0) {
4604 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004605 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4606 __func__, mUidCached, patchDesc->getUid(), uid);
4607 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004608 return INVALID_OPERATION;
4609 }
4610 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004611 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004612 }
4613
4614 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004615 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004616 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004617 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004618 return BAD_VALUE;
4619 }
Eric Laurent84c70242014-06-23 08:46:27 -07004620 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4621 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004622 if (patchDesc != 0) {
4623 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004624 ALOGV("%s source id differs for patch current id %d new id %d",
4625 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004626 return BAD_VALUE;
4627 }
4628 }
Eric Laurent874c42872014-08-08 15:13:39 -07004629 DeviceVector devices;
4630 for (size_t i = 0; i < patch->num_sinks; i++) {
4631 // Only support mix to devices connection
4632 // TODO add support for mix to mix connection
4633 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004634 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004635 return INVALID_OPERATION;
4636 }
4637 sp<DeviceDescriptor> devDesc =
4638 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4639 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004640 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004641 return BAD_VALUE;
4642 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004643
François Gaffie11d30102018-11-02 16:09:09 +01004644 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004645 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004646 NULL, // updatedSamplingRate
4647 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004648 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004649 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004650 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004651 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004652 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004653 return INVALID_OPERATION;
4654 }
4655 devices.add(devDesc);
4656 }
4657 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004658 return INVALID_OPERATION;
4659 }
Eric Laurent874c42872014-08-08 15:13:39 -07004660
Eric Laurent6a94d692014-05-20 11:18:06 -07004661 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004662 ALOGV("%s setting device %s on output %d",
4663 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004664 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004665 index = mAudioPatches.indexOfKey(*handle);
4666 if (index >= 0) {
4667 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004668 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004669 }
4670 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004671 patchDesc->setUid(uid);
4672 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004673 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004674 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004675 return INVALID_OPERATION;
4676 }
4677 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4678 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4679 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004680 // only one sink supported when connecting an input device to a mix
4681 if (patch->num_sinks > 1) {
4682 return INVALID_OPERATION;
4683 }
François Gaffie53615e22015-03-19 09:24:12 +01004684 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004685 if (inputDesc == NULL) {
4686 return BAD_VALUE;
4687 }
4688 if (patchDesc != 0) {
4689 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4690 return BAD_VALUE;
4691 }
4692 }
François Gaffie11d30102018-11-02 16:09:09 +01004693 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004694 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004695 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004696 return BAD_VALUE;
4697 }
4698
François Gaffie11d30102018-11-02 16:09:09 +01004699 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004700 patch->sinks[0].sample_rate,
4701 NULL, /*updatedSampleRate*/
4702 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004703 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004704 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004705 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004706 // FIXME for the parameter type,
4707 // and the NONE
4708 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004709 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004710 return INVALID_OPERATION;
4711 }
4712 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004713 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004714 device->toString().c_str(), inputDesc->mIoHandle);
4715 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004716 index = mAudioPatches.indexOfKey(*handle);
4717 if (index >= 0) {
4718 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004719 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004720 }
4721 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004722 patchDesc->setUid(uid);
4723 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004724 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004725 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004726 return INVALID_OPERATION;
4727 }
4728 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4729 // device to device connection
4730 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004731 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 return BAD_VALUE;
4733 }
4734 }
François Gaffie11d30102018-11-02 16:09:09 +01004735 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004736 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004737 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004738 return BAD_VALUE;
4739 }
Eric Laurent874c42872014-08-08 15:13:39 -07004740
Eric Laurent6a94d692014-05-20 11:18:06 -07004741 //update source and sink with our own data as the data passed in the patch may
4742 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004743 PatchBuilder patchBuilder;
4744 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004745
4746 // if first sink is to MSD, establish single MSD patch
4747 if (getMsdAudioOutDevices().contains(
4748 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4749 ALOGV("%s patching to MSD", __FUNCTION__);
4750 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4751 goto installPatch;
4752 }
4753
François Gaffieafd4cea2019-11-18 15:50:22 +01004754 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4755 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004756
Eric Laurent874c42872014-08-08 15:13:39 -07004757 for (size_t i = 0; i < patch->num_sinks; i++) {
4758 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004759 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004760 return INVALID_OPERATION;
4761 }
François Gaffie11d30102018-11-02 16:09:09 +01004762 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004763 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004764 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004765 return BAD_VALUE;
4766 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004767 audio_port_config sinkPortConfig = {};
4768 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4769 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004770
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004771 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4772 // volume management purpose (tracking activity)
4773 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4774 // in config XML to reach the sink so that is can be declared as available.
4775 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004776 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004777 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004778 // take care of dynamic routing for SwOutput selection,
4779 audio_attributes_t attributes = sourceDesc->attributes();
4780 audio_stream_type_t stream = sourceDesc->stream();
4781 audio_attributes_t resultAttr;
4782 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4783 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004784 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4785 config.channel_mask =
4786 (audio_channel_mask_get_representation(sourceMask)
4787 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4788 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004789 config.format = sourceDesc->config().format;
4790 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4791 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4792 bool isRequestedDeviceForExclusiveUse = false;
4793 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004794 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004795 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004796 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4797 &stream, sourceDesc->uid(), &config, &flags,
4798 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004799 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004800 if (output == AUDIO_IO_HANDLE_NONE) {
4801 ALOGV("%s no output for device %s",
4802 __FUNCTION__, sinkDevice->toString().c_str());
4803 return INVALID_OPERATION;
4804 }
4805 outputDesc = mOutputs.valueFor(output);
4806 if (outputDesc->isDuplicated()) {
4807 ALOGE("%s output is duplicated", __func__);
4808 return INVALID_OPERATION;
4809 }
François Gaffie7e39df22022-04-26 12:48:49 +02004810 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4811 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004812 } else {
4813 // Same for "raw patches" aka created from createAudioPatch API
4814 SortedVector<audio_io_handle_t> outputs =
4815 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4816 // if the sink device is reachable via an opened output stream, request to
4817 // go via this output stream by adding a second source to the patch
4818 // description
4819 output = selectOutput(outputs);
4820 if (output == AUDIO_IO_HANDLE_NONE) {
4821 ALOGE("%s no output available for internal patch sink", __func__);
4822 return INVALID_OPERATION;
4823 }
4824 outputDesc = mOutputs.valueFor(output);
4825 if (outputDesc->isDuplicated()) {
4826 ALOGV("%s output for device %s is duplicated",
4827 __func__, sinkDevice->toString().c_str());
4828 return INVALID_OPERATION;
4829 }
François Gaffie7e39df22022-04-26 12:48:49 +02004830 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004831 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004832 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004833 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004834 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004835 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004836 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4837 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004838 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4839 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004840 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004841 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004842 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004843 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004844 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004845 return INVALID_OPERATION;
4846 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004847 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004848 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004849 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004850 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004851 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004852 srcMixPortConfig.ext.mix.usecase.stream =
4853 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004854 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4855 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004856 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004857 }
Eric Laurent83b88082014-06-20 18:31:16 -07004858 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004859 }
4860 // TODO: check from routing capabilities in config file and other conflicting patches
4861
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004862installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004863 status_t status = installPatch(
4864 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004865 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004866 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004867 return INVALID_OPERATION;
4868 }
4869 } else {
4870 return BAD_VALUE;
4871 }
4872 } else {
4873 return BAD_VALUE;
4874 }
4875 return NO_ERROR;
4876}
4877
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004878status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004879{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004880 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004881 ssize_t index = mAudioPatches.indexOfKey(handle);
4882
4883 if (index < 0) {
4884 return BAD_VALUE;
4885 }
4886 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004887 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4888 __func__, mUidCached, patchDesc->getUid(), uid);
4889 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004890 return INVALID_OPERATION;
4891 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004892 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4893 for (size_t i = 0; i < mAudioSources.size(); i++) {
4894 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4895 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4896 portId = sourceDesc->portId();
4897 break;
4898 }
4899 }
4900 return portId != AUDIO_PORT_HANDLE_NONE ?
4901 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004902}
Eric Laurent6a94d692014-05-20 11:18:06 -07004903
François Gaffieafd4cea2019-11-18 15:50:22 +01004904status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004905 uint32_t delayMs,
4906 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004907{
4908 ALOGV("%s patch %d", __func__, handle);
4909 if (mAudioPatches.indexOfKey(handle) < 0) {
4910 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4911 return BAD_VALUE;
4912 }
4913 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004914 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004915 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004916 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004917 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004918 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004919 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004920 return BAD_VALUE;
4921 }
4922
François Gaffie11d30102018-11-02 16:09:09 +01004923 setOutputDevices(outputDesc,
4924 getNewOutputDevices(outputDesc, true /*fromCache*/),
4925 true,
4926 0,
4927 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004928 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4929 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004930 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004931 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004932 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 return BAD_VALUE;
4934 }
4935 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004936 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004937 true,
4938 NULL);
4939 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004940 status_t status =
4941 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4942 ALOGV("%s patch panel returned %d patchHandle %d",
4943 __func__, status, patchDesc->getAfHandle());
4944 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004945 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004946 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004947 // SW or HW Bridge
4948 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4949 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004950 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004951 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4952 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4953 outputDesc = sourceDesc->swOutput().promote();
4954 }
4955 if (outputDesc == nullptr) {
4956 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4957 // releaseOutput has already called closeOutput in case of direct output
4958 return NO_ERROR;
4959 }
François Gaffie7e39df22022-04-26 12:48:49 +02004960 patchHandle = outputDesc->getPatchHandle();
4961 // When a Sw bridge is released, the mixer used by this bridge will release its
4962 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4963 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4964 // updating hal patch handle (prevent leaks).
4965 // While using a HwBridge, force reconsidering device only if not reusing an existing
4966 // output and no more activity on output (will force to close).
4967 bool force = sourceDesc->useSwBridge() ||
4968 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4969 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4970 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4971 // Reconsider device only for cases:
4972 // 1 / Active Output
4973 // 2 / Inactive Output previously hosting HwBridge
4974 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4975 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4976 sourceDesc->canCloseOutput();
4977 setOutputDevices(outputDesc,
4978 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4979 outputDesc->devices(),
4980 force,
4981 0,
4982 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004983 } else {
4984 return BAD_VALUE;
4985 }
4986 } else {
4987 return BAD_VALUE;
4988 }
4989 return NO_ERROR;
4990}
4991
4992status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4993 struct audio_patch *patches,
4994 unsigned int *generation)
4995{
François Gaffie53615e22015-03-19 09:24:12 +01004996 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004997 return BAD_VALUE;
4998 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004999 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005000 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005001}
5002
Eric Laurente1715a42014-05-20 11:30:42 -07005003status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005004{
Eric Laurente1715a42014-05-20 11:30:42 -07005005 ALOGV("setAudioPortConfig()");
5006
5007 if (config == NULL) {
5008 return BAD_VALUE;
5009 }
5010 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5011 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005012 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5013 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005014 }
5015
Eric Laurenta121f902014-06-03 13:32:54 -07005016 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005017 if (config->type == AUDIO_PORT_TYPE_MIX) {
5018 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005019 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005020 if (outputDesc == NULL) {
5021 return BAD_VALUE;
5022 }
Eric Laurent84c70242014-06-23 08:46:27 -07005023 ALOG_ASSERT(!outputDesc->isDuplicated(),
5024 "setAudioPortConfig() called on duplicated output %d",
5025 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005026 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005027 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005028 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005029 if (inputDesc == NULL) {
5030 return BAD_VALUE;
5031 }
Eric Laurenta121f902014-06-03 13:32:54 -07005032 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005033 } else {
5034 return BAD_VALUE;
5035 }
5036 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5037 sp<DeviceDescriptor> deviceDesc;
5038 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5039 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5040 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5041 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5042 } else {
5043 return BAD_VALUE;
5044 }
5045 if (deviceDesc == NULL) {
5046 return BAD_VALUE;
5047 }
Eric Laurenta121f902014-06-03 13:32:54 -07005048 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005049 } else {
5050 return BAD_VALUE;
5051 }
5052
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005053 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005054 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5055 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005056 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005057 audioPortConfig->toAudioPortConfig(&newConfig, config);
5058 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005059 }
Eric Laurenta121f902014-06-03 13:32:54 -07005060 if (status != NO_ERROR) {
5061 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005062 }
Eric Laurente1715a42014-05-20 11:30:42 -07005063
5064 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005065}
5066
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005067void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5068{
Eric Laurentd60560a2015-04-10 11:31:20 -07005069 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005070 clearAudioPatches(uid);
5071 clearSessionRoutes(uid);
5072}
5073
Eric Laurent6a94d692014-05-20 11:18:06 -07005074void AudioPolicyManager::clearAudioPatches(uid_t uid)
5075{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005076 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005077 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005078 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005079 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005080 }
5081 }
5082}
5083
François Gaffiec005e562018-11-06 15:04:49 +01005084void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005085{
François Gaffiec005e562018-11-06 15:04:49 +01005086 // Take the first attributes following the product strategy as it is used to retrieve the routed
5087 // device. All attributes wihin a strategy follows the same "routing strategy"
5088 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5089 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005090 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005091 for (size_t j = 0; j < mOutputs.size(); j++) {
5092 if (mOutputs.keyAt(j) == ouptutToSkip) {
5093 continue;
5094 }
5095 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005096 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005097 continue;
5098 }
5099 // If the default device for this strategy is on another output mix,
5100 // invalidate all tracks in this strategy to force re connection.
5101 // Otherwise select new device on the output mix.
5102 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01005103 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
5104 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005105 }
5106 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005107 setOutputDevices(
5108 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005109 }
5110 }
5111}
5112
5113void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5114{
5115 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005116 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005117 for (size_t i = 0; i < mOutputs.size(); i++) {
5118 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005119 for (const auto& client : outputDesc->getClientIterable()) {
5120 if (client->hasPreferredDevice() && client->uid() == uid) {
5121 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005122 auto clientStrategy = client->strategy();
5123 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5124 end(affectedStrategies)) {
5125 continue;
5126 }
5127 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005128 }
5129 }
5130 }
5131 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005132 for (const auto& strategy : affectedStrategies) {
5133 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005134 }
5135
5136 // remove input routes associated with this uid
5137 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005138 for (size_t i = 0; i < mInputs.size(); i++) {
5139 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005140 for (const auto& client : inputDesc->getClientIterable()) {
5141 if (client->hasPreferredDevice() && client->uid() == uid) {
5142 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5143 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005144 }
5145 }
5146 }
5147 // reroute inputs if necessary
5148 SortedVector<audio_io_handle_t> inputsToClose;
5149 for (size_t i = 0; i < mInputs.size(); i++) {
5150 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005151 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005152 inputsToClose.add(inputDesc->mIoHandle);
5153 }
5154 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005155 for (const auto& input : inputsToClose) {
5156 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005157 }
5158}
5159
Eric Laurentd60560a2015-04-10 11:31:20 -07005160void AudioPolicyManager::clearAudioSources(uid_t uid)
5161{
5162 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005163 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5164 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005165 stopAudioSource(mAudioSources.keyAt(i));
5166 }
5167 }
5168}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005169
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005170status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5171 audio_io_handle_t *ioHandle,
5172 audio_devices_t *device)
5173{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005174 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5175 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005176 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005177 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005178
François Gaffiedf372692015-03-19 10:43:27 +01005179 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005180}
5181
Eric Laurentd60560a2015-04-10 11:31:20 -07005182status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005183 const audio_attributes_t *attributes,
5184 audio_port_handle_t *portId,
5185 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005186{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005187 ALOGV("%s", __FUNCTION__);
5188 *portId = AUDIO_PORT_HANDLE_NONE;
5189
5190 if (source == NULL || attributes == NULL || portId == NULL) {
5191 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5192 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005193 return BAD_VALUE;
5194 }
5195
Eric Laurentd60560a2015-04-10 11:31:20 -07005196 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5197 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005198 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5199 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005200 return INVALID_OPERATION;
5201 }
5202
François Gaffie11d30102018-11-02 16:09:09 +01005203 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005204 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005205 String8(source->ext.device.address),
5206 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005207 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005208 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005209 return BAD_VALUE;
5210 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005211
jiabin4ef93452019-09-10 14:29:54 -07005212 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005213
François Gaffieaaac0fd2018-11-22 17:56:39 +01005214 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005215 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005216 mEngine->getStreamTypeForAttributes(*attributes),
5217 mEngine->getProductStrategyForAttributes(*attributes),
5218 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005219
5220 status_t status = connectAudioSource(sourceDesc);
5221 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005222 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005223 }
5224 return status;
5225}
5226
Francois Gaffie601801d2021-06-22 13:27:39 +02005227sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5228 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5229{
5230 ALOGV("%s", __FUNCTION__);
5231 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5232
5233 status_t status = startAudioSource(source, attributes, &portId, uid);
5234 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5235 return mAudioSources.valueFor(portId);
5236}
5237
5238
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005239status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005240{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005241 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005242
5243 // make sure we only have one patch per source.
5244 disconnectAudioSource(sourceDesc);
5245
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005246 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005247 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5248 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5249 sourceDesc->srcDevice()->type(),
5250 String8(sourceDesc->srcDevice()->address().c_str()),
5251 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005252 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005253 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005254 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005255 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005256 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5257 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5258 return INVALID_OPERATION;
5259 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005260 PatchBuilder patchBuilder;
5261 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5262 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005263
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005264 return connectAudioSourceToSink(
5265 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005266}
5267
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005268status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005269{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005270 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5271 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005272 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005273 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005274 return BAD_VALUE;
5275 }
5276 status_t status = disconnectAudioSource(sourceDesc);
5277
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005278 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005279 return status;
5280}
5281
Andy Hung2ddee192015-12-18 17:34:44 -08005282status_t AudioPolicyManager::setMasterMono(bool mono)
5283{
5284 if (mMasterMono == mono) {
5285 return NO_ERROR;
5286 }
5287 mMasterMono = mono;
5288 // if enabling mono we close all offloaded devices, which will invalidate the
5289 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5290 // for recreating the new AudioTrack as non-offloaded PCM.
5291 //
5292 // If disabling mono, we leave all tracks as is: we don't know which clients
5293 // and tracks are able to be recreated as offloaded. The next "song" should
5294 // play back offloaded.
5295 if (mMasterMono) {
5296 Vector<audio_io_handle_t> offloaded;
5297 for (size_t i = 0; i < mOutputs.size(); ++i) {
5298 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5299 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5300 offloaded.push(desc->mIoHandle);
5301 }
5302 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005303 for (const auto& handle : offloaded) {
5304 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005305 }
5306 }
5307 // update master mono for all remaining outputs
5308 for (size_t i = 0; i < mOutputs.size(); ++i) {
5309 updateMono(mOutputs.keyAt(i));
5310 }
5311 return NO_ERROR;
5312}
5313
5314status_t AudioPolicyManager::getMasterMono(bool *mono)
5315{
5316 *mono = mMasterMono;
5317 return NO_ERROR;
5318}
5319
Eric Laurentac9cef52017-06-09 15:46:26 -07005320float AudioPolicyManager::getStreamVolumeDB(
5321 audio_stream_type_t stream, int index, audio_devices_t device)
5322{
jiabin9a3361e2019-10-01 09:38:30 -07005323 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005324}
5325
jiabin81772902018-04-02 17:52:27 -07005326status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5327 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005328 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005329{
Kriti Dang6537def2021-03-02 13:46:59 +01005330 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5331 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005332 return BAD_VALUE;
5333 }
Kriti Dang6537def2021-03-02 13:46:59 +01005334 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5335 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005336
5337 size_t formatsWritten = 0;
5338 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005339
Kriti Dang6537def2021-03-02 13:46:59 +01005340 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005341 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5342 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005343 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005344 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005345 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005346 bool formatEnabled = true;
5347 switch (forceUse) {
5348 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005349 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005350 break;
5351 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5352 formatEnabled = false;
5353 break;
5354 default: // AUTO or ALWAYS => true
5355 break;
jiabin81772902018-04-02 17:52:27 -07005356 }
5357 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5358 }
jiabin81772902018-04-02 17:52:27 -07005359 }
5360 return NO_ERROR;
5361}
5362
Kriti Dang6537def2021-03-02 13:46:59 +01005363status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5364 audio_format_t *surroundFormats) {
5365 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5366 return BAD_VALUE;
5367 }
5368 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5369 __func__, *numSurroundFormats, surroundFormats);
5370
5371 size_t formatsWritten = 0;
5372 size_t formatsMax = *numSurroundFormats;
5373 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5374
5375 // Return formats from all device profiles that have already been resolved by
5376 // checkOutputsForDevice().
5377 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5378 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5379 audio_devices_t deviceType = device->type();
5380 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5381 // returns formats reported by HDMI devices.
5382 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5383 continue;
5384 }
5385 // Formats reported by sink devices
5386 std::unordered_set<audio_format_t> formatset;
5387 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5388 formatset.insert(it->second.begin(), it->second.end());
5389 }
5390
5391 // Formats hard-coded in the in policy configuration file (if any).
5392 FormatVector encodedFormats = device->encodedFormats();
5393 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5394 // Filter the formats which are supported by the vendor hardware.
5395 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5396 if (mConfig.getSurroundFormats().count(*it) != 0) {
5397 formats.insert(*it);
5398 } else {
5399 for (const auto& pair : mConfig.getSurroundFormats()) {
5400 if (pair.second.count(*it) != 0) {
5401 formats.insert(pair.first);
5402 break;
5403 }
5404 }
5405 }
5406 }
5407 }
5408 *numSurroundFormats = formats.size();
5409 for (const auto& format: formats) {
5410 if (formatsWritten < formatsMax) {
5411 surroundFormats[formatsWritten++] = format;
5412 }
5413 }
5414 return NO_ERROR;
5415}
5416
jiabin81772902018-04-02 17:52:27 -07005417status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5418{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005419 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005420 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5421 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005422 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005423 return BAD_VALUE;
5424 }
5425
Mikhail Naganov100f0122018-11-29 11:22:16 -08005426 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5427 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005428 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005429 return INVALID_OPERATION;
5430 }
5431
Mikhail Naganov100f0122018-11-29 11:22:16 -08005432 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005433 return NO_ERROR;
5434 }
5435
Mikhail Naganov100f0122018-11-29 11:22:16 -08005436 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005437 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005438 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005439 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005440 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005441 }
5442 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005443 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005444 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005445 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005446 }
5447 }
5448
5449 sp<SwAudioOutputDescriptor> outputDesc;
5450 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005451 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5452 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005453 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5454 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005455 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005456 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005457 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5458 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5459 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005460 name.c_str(),
5461 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005462 if (status != NO_ERROR) {
5463 continue;
5464 }
5465 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5466 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5467 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005468 name.c_str(),
5469 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005470 profileUpdated |= (status == NO_ERROR);
5471 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005472 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005473 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005474 AUDIO_DEVICE_IN_HDMI);
5475 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5476 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005477 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005478 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005479 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5480 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5481 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005482 name.c_str(),
5483 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005484 if (status != NO_ERROR) {
5485 continue;
5486 }
5487 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5488 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5489 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005490 name.c_str(),
5491 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005492 profileUpdated |= (status == NO_ERROR);
5493 }
5494
jiabin81772902018-04-02 17:52:27 -07005495 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005496 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005497 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005498 }
5499
5500 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5501}
5502
Eric Laurent5ada82e2019-08-29 17:53:54 -07005503void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005504{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005505 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005506 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005507 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005508 }
5509}
5510
jiabin6012f912018-11-02 17:06:30 -07005511bool AudioPolicyManager::isHapticPlaybackSupported()
5512{
5513 for (const auto& hwModule : mHwModules) {
5514 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5515 for (const auto &outProfile : outputProfiles) {
5516 struct audio_port audioPort;
5517 outProfile->toAudioPort(&audioPort);
5518 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5519 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5520 return true;
5521 }
5522 }
5523 }
5524 }
5525 return false;
5526}
5527
Carter Hsu325a8eb2022-01-19 19:56:51 +08005528bool AudioPolicyManager::isUltrasoundSupported()
5529{
5530 bool hasUltrasoundOutput = false;
5531 bool hasUltrasoundInput = false;
5532 for (const auto& hwModule : mHwModules) {
5533 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5534 if (!hasUltrasoundOutput) {
5535 for (const auto &outProfile : outputProfiles) {
5536 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5537 hasUltrasoundOutput = true;
5538 break;
5539 }
5540 }
5541 }
5542
5543 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5544 if (!hasUltrasoundInput) {
5545 for (const auto &inputProfile : inputProfiles) {
5546 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5547 hasUltrasoundInput = true;
5548 break;
5549 }
5550 }
5551 }
5552
5553 if (hasUltrasoundOutput && hasUltrasoundInput)
5554 return true;
5555 }
5556 return false;
5557}
5558
Eric Laurent8340e672019-11-06 11:01:08 -08005559bool AudioPolicyManager::isCallScreenModeSupported()
5560{
5561 return getConfig().isCallScreenModeSupported();
5562}
5563
5564
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005565status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005566{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005567 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005568 if (!sourceDesc->isConnected()) {
5569 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5570 return NO_ERROR;
5571 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005572 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5573 if (swOutput != 0) {
5574 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005575 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005576 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005577 }
jiabinbce0c1d2020-10-05 11:20:18 -07005578 if (releaseOutput(sourceDesc->portId())) {
5579 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5580 // no need to release audio patch here but just return NO_ERROR.
5581 return NO_ERROR;
5582 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005583 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005584 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005585 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005586 // close Hwoutput and remove from mHwOutputs
5587 } else {
5588 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5589 }
5590 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005591 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005592 sourceDesc->disconnect();
5593 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005594}
5595
François Gaffiec005e562018-11-06 15:04:49 +01005596sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5597 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005598{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005599 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005600 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005601 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005602 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005603 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5604 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005605 source = sourceDesc;
5606 break;
5607 }
5608 }
5609 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005610}
5611
Eric Laurentb4f42a92022-01-17 17:37:31 +01005612bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005613 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005614 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005615{
5616 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5617 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005618 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005619 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005620 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5621 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5622 return false;
5623 }
5624 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5625 return false;
5626 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005627 }
5628
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005629 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005630 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005631 if (profile == nullptr) {
5632 return false;
5633 }
5634
5635 // The caller can have the audio config criteria ignored by either passing a null ptr or
5636 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005637 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005638 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005639
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005640 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005641 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005642 return false;
5643 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005644 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005645 return true;
5646}
5647
5648void AudioPolicyManager::checkVirtualizerClientRoutes() {
5649 std::set<audio_stream_type_t> streamsToInvalidate;
5650 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005651 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5652 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005653 audio_attributes_t attr = client->attributes();
5654 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5655 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5656 audio_config_base_t clientConfig = client->config();
5657 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005658 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005659 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005660 streamsToInvalidate.insert(client->stream());
5661 }
5662 }
5663 }
5664
5665 for (audio_stream_type_t stream : streamsToInvalidate) {
5666 mpClientInterface->invalidateStream(stream);
5667 }
5668}
5669
Eric Laurente191d1b2022-04-15 11:59:25 +02005670
5671bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5672 const sp<SwAudioOutputDescriptor>& outputDesc) {
5673 if (outputDesc->isDuplicated()) {
5674 return false;
5675 }
5676 DeviceVector devices = outputDesc->supportedDevices();
5677 for (size_t i = 0; i < mOutputs.size(); i++) {
5678 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5679 if (desc == outputDesc || desc->isDuplicated()) {
5680 continue;
5681 }
5682 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5683 if (!sharedDevices.isEmpty()
5684 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5685 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5686 return false;
5687 }
5688 }
5689 return true;
5690}
5691
5692
Eric Laurentfa0f6742021-08-17 18:39:44 +02005693status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005694 const audio_attributes_t *attr,
5695 audio_io_handle_t *output) {
5696 *output = AUDIO_IO_HANDLE_NONE;
5697
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005698 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5699 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5700 audio_config_t *configPtr = nullptr;
5701 audio_config_t config;
5702 if (mixerConfig != nullptr) {
5703 config = audio_config_initializer(mixerConfig);
5704 configPtr = &config;
5705 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005706 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005707 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005708 return BAD_VALUE;
5709 }
5710
5711 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005712 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005713 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005714 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005715 return BAD_VALUE;
5716 }
5717
Eric Laurente191d1b2022-04-15 11:59:25 +02005718 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005719 for (size_t i = 0; i < mOutputs.size(); i++) {
5720 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005721 if (!desc->isDuplicated()
5722 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5723 spatializerOutputs.push_back(desc);
5724 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005725 }
5726 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005727 mSpatializerOutput.clear();
5728 bool outputsChanged = false;
5729 for (const auto& desc : spatializerOutputs) {
5730 if (desc->mProfile == profile
5731 && (configPtr == nullptr
5732 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5733 mSpatializerOutput = desc;
5734 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5735 } else {
5736 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5737 " and devices %s", __func__, desc->mIoHandle,
5738 configPtr != nullptr ? configPtr->channel_mask : 0,
5739 devices.toString().c_str());
5740 closeOutput(desc->mIoHandle);
5741 outputsChanged = true;
5742 }
Eric Laurent39095982021-08-24 18:29:27 +02005743 }
5744
Eric Laurente191d1b2022-04-15 11:59:25 +02005745 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005746 sp<SwAudioOutputDescriptor> desc =
5747 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005748 if (desc != nullptr) {
5749 mSpatializerOutput = desc;
5750 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005751 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005752 }
5753
5754 checkVirtualizerClientRoutes();
5755
Eric Laurente191d1b2022-04-15 11:59:25 +02005756 if (outputsChanged) {
5757 mPreviousOutputs = mOutputs;
5758 mpClientInterface->onAudioPortListUpdate();
5759 }
5760
5761 if (mSpatializerOutput == nullptr) {
5762 ALOGV("%s could not open spatializer output with requested config", __func__);
5763 return BAD_VALUE;
5764 }
Eric Laurent39095982021-08-24 18:29:27 +02005765 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005766 ALOGV("%s returning new spatializer output %d", __func__, *output);
5767 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005768}
5769
Eric Laurentfa0f6742021-08-17 18:39:44 +02005770status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5771 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005772 return INVALID_OPERATION;
5773 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005774 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005775 return BAD_VALUE;
5776 }
Eric Laurent39095982021-08-24 18:29:27 +02005777
Eric Laurente191d1b2022-04-15 11:59:25 +02005778 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5779 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5780 closeOutput(mSpatializerOutput->mIoHandle);
5781 //from now on mSpatializerOutput is null
5782 checkVirtualizerClientRoutes();
5783 }
Eric Laurent39095982021-08-24 18:29:27 +02005784
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005785 return NO_ERROR;
5786}
5787
Eric Laurente552edb2014-03-10 17:42:56 -07005788// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005789// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005790// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005791uint32_t AudioPolicyManager::nextAudioPortGeneration()
5792{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005793 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005794}
5795
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005796static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005797 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5798 !audioPolicyXmlConfigFile.empty()) {
5799 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5800 if (ret == NO_ERROR) {
5801 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005802 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005803 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005804 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005805 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005806}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005807
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005808AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5809 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005810 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005811 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005812 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005813 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005814 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005815 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005816 mAudioPortGeneration(1),
5817 mBeaconMuteRefCount(0),
5818 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005819 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005820 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005821 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005822 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005823{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005824}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005825
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005826AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5827 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5828{
5829 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005830}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005831
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005832void AudioPolicyManager::loadConfig() {
5833 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005834 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005835 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005836 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005837}
5838
5839status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005840 {
5841 auto engLib = EngineLibrary::load(
5842 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5843 if (!engLib) {
5844 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5845 return NO_INIT;
5846 }
5847 mEngine = engLib->createEngine();
5848 if (mEngine == nullptr) {
5849 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5850 return NO_INIT;
5851 }
François Gaffie2110e042015-03-24 08:41:51 +01005852 }
5853 mEngine->setObserver(this);
5854 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005855 if (status != NO_ERROR) {
5856 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5857 return status;
5858 }
François Gaffie2110e042015-03-24 08:41:51 +01005859
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005860 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005861 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5862 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5863
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005864 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005865 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005866 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005867
Eric Laurent3a4311c2014-03-17 12:00:47 -07005868 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005869 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5870 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5871 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005872 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005873 }
jiabin9ff780e2018-03-19 18:19:52 -07005874 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005875 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005876 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005877 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005878 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005879 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005880 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005881 }
5882 }
5883 }
Eric Laurente552edb2014-03-10 17:42:56 -07005884
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005885 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005886
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005887 // Silence ALOGV statements
5888 property_set("log.tag." LOG_TAG, "D");
5889
Eric Laurente552edb2014-03-10 17:42:56 -07005890 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005891 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005892}
5893
Eric Laurente0720872014-03-11 09:30:41 -07005894AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005895{
Eric Laurente552edb2014-03-10 17:42:56 -07005896 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005897 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005898 }
5899 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005900 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005901 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005902 mAvailableOutputDevices.clear();
5903 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005904 mOutputs.clear();
5905 mInputs.clear();
5906 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005907 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005908 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005909}
5910
Eric Laurente0720872014-03-11 09:30:41 -07005911status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005912{
Eric Laurent87ffa392015-05-22 10:32:38 -07005913 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005914}
5915
Eric Laurente552edb2014-03-10 17:42:56 -07005916// ---
5917
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005918void AudioPolicyManager::onNewAudioModulesAvailable()
5919{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005920 DeviceVector newDevices;
5921 onNewAudioModulesAvailableInt(&newDevices);
5922 if (!newDevices.empty()) {
5923 nextAudioPortGeneration();
5924 mpClientInterface->onAudioPortListUpdate();
5925 }
5926}
5927
5928void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5929{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005930 for (const auto& hwModule : mHwModulesAll) {
5931 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5932 continue;
5933 }
5934 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5935 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5936 ALOGW("could not open HW module %s", hwModule->getName());
5937 continue;
5938 }
5939 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005940 // open all output streams needed to access attached devices.
5941 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005942 // This also validates mAvailableOutputDevices list
5943 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5944 if (!outProfile->canOpenNewIo()) {
5945 ALOGE("Invalid Output profile max open count %u for profile %s",
5946 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5947 continue;
5948 }
5949 if (!outProfile->hasSupportedDevices()) {
5950 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5951 continue;
5952 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005953 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5954 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005955 mTtsOutputAvailable = true;
5956 }
5957
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005958 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5959 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5960 sp<DeviceDescriptor> supportedDevice = 0;
5961 if (supportedDevices.contains(mDefaultOutputDevice)) {
5962 supportedDevice = mDefaultOutputDevice;
5963 } else {
5964 // choose first device present in profile's SupportedDevices also part of
5965 // mAvailableOutputDevices.
5966 if (availProfileDevices.isEmpty()) {
5967 continue;
5968 }
5969 supportedDevice = availProfileDevices.itemAt(0);
5970 }
5971 if (!mOutputDevicesAll.contains(supportedDevice)) {
5972 continue;
5973 }
5974 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5975 mpClientInterface);
5976 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005977 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5978 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005979 AUDIO_STREAM_DEFAULT,
5980 AUDIO_OUTPUT_FLAG_NONE, &output);
5981 if (status != NO_ERROR) {
5982 ALOGW("Cannot open output stream for devices %s on hw module %s",
5983 supportedDevice->toString().c_str(), hwModule->getName());
5984 continue;
5985 }
5986 for (const auto &device : availProfileDevices) {
5987 // give a valid ID to an attached device once confirmed it is reachable
5988 if (!device->isAttached()) {
5989 device->attach(hwModule);
5990 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005991 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005992 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005993 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5994 }
5995 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005996 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005997 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5998 mPrimaryOutput = outputDesc;
5999 }
Eric Laurent39095982021-08-24 18:29:27 +02006000 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006001 outputDesc->close();
6002 } else {
6003 addOutput(output, outputDesc);
6004 setOutputDevices(outputDesc,
6005 DeviceVector(supportedDevice),
6006 true,
6007 0,
6008 NULL);
6009 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006010 }
6011 // open input streams needed to access attached devices to validate
6012 // mAvailableInputDevices list
6013 for (const auto& inProfile : hwModule->getInputProfiles()) {
6014 if (!inProfile->canOpenNewIo()) {
6015 ALOGE("Invalid Input profile max open count %u for profile %s",
6016 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6017 continue;
6018 }
6019 if (!inProfile->hasSupportedDevices()) {
6020 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6021 continue;
6022 }
6023 // chose first device present in profile's SupportedDevices also part of
6024 // available input devices
6025 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6026 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6027 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006028 ALOGV("%s: Input device list is empty! for profile %s",
6029 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006030 continue;
6031 }
6032 sp<AudioInputDescriptor> inputDesc =
6033 new AudioInputDescriptor(inProfile, mpClientInterface);
6034
6035 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6036 status_t status = inputDesc->open(nullptr,
6037 availProfileDevices.itemAt(0),
6038 AUDIO_SOURCE_MIC,
6039 AUDIO_INPUT_FLAG_NONE,
6040 &input);
6041 if (status != NO_ERROR) {
6042 ALOGW("Cannot open input stream for device %s on hw module %s",
6043 availProfileDevices.toString().c_str(),
6044 hwModule->getName());
6045 continue;
6046 }
6047 for (const auto &device : availProfileDevices) {
6048 // give a valid ID to an attached device once confirmed it is reachable
6049 if (!device->isAttached()) {
6050 device->attach(hwModule);
6051 device->importAudioPortAndPickAudioProfile(inProfile, true);
6052 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006053 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006054 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6055 }
6056 }
6057 inputDesc->close();
6058 }
6059 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006060
6061 // Check if spatializer outputs can be closed until used.
6062 // mOutputs vector never contains duplicated outputs at this point.
6063 std::vector<audio_io_handle_t> outputsClosed;
6064 for (size_t i = 0; i < mOutputs.size(); i++) {
6065 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6066 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6067 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6068 outputsClosed.push_back(desc->mIoHandle);
6069 desc->close();
6070 }
6071 }
6072 for (auto output : outputsClosed) {
6073 removeOutput(output);
6074 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006075}
6076
Eric Laurent98e38192018-02-15 18:31:53 -08006077void AudioPolicyManager::addOutput(audio_io_handle_t output,
6078 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006079{
Eric Laurent1c333e22014-05-20 10:48:17 -07006080 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006081 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006082 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006083 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006084 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006085}
6086
François Gaffie53615e22015-03-19 09:24:12 +01006087void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6088{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006089 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6090 ALOGV("%s: removing primary output", __func__);
6091 mPrimaryOutput = nullptr;
6092 }
François Gaffie53615e22015-03-19 09:24:12 +01006093 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006094 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006095}
6096
Eric Laurent98e38192018-02-15 18:31:53 -08006097void AudioPolicyManager::addInput(audio_io_handle_t input,
6098 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006099{
Eric Laurent1c333e22014-05-20 10:48:17 -07006100 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006101 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006102}
Eric Laurente552edb2014-03-10 17:42:56 -07006103
François Gaffie11d30102018-11-02 16:09:09 +01006104status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006105 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006106 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006107{
François Gaffie11d30102018-11-02 16:09:09 +01006108 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006109 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006110 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006111
François Gaffie11d30102018-11-02 16:09:09 +01006112 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006113 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006114 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006115 }
Eric Laurente552edb2014-03-10 17:42:56 -07006116
Eric Laurent3b73df72014-03-11 09:06:29 -07006117 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006118 // first call getAudioPort to get the supported attributes from the HAL
6119 struct audio_port_v7 port = {};
6120 device->toAudioPort(&port);
6121 status_t status = mpClientInterface->getAudioPort(&port);
6122 if (status == NO_ERROR) {
6123 device->importAudioPort(port);
6124 }
6125
6126 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006127 for (size_t i = 0; i < mOutputs.size(); i++) {
6128 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006129 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006130 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006131 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6132 mOutputs.keyAt(i), device->toString().c_str());
6133 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006134 }
6135 }
6136 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006137 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006138 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006139 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6140 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006141 if (profile->supportsDevice(device)) {
6142 profiles.add(profile);
6143 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6144 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006145 }
6146 }
6147 }
6148
Eric Laurent7b279bb2015-12-14 10:18:23 -08006149 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006150
Eric Laurente552edb2014-03-10 17:42:56 -07006151 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006152 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006153 return BAD_VALUE;
6154 }
6155
6156 // open outputs for matching profiles if needed. Direct outputs are also opened to
6157 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6158 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006159 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006160
6161 // nothing to do if one output is already opened for this profile
6162 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006163 for (j = 0; j < outputs.size(); j++) {
6164 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006165 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006166 // matching profile: save the sample rates, format and channel masks supported
6167 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006168 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006169 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006170 }
Eric Laurente552edb2014-03-10 17:42:56 -07006171 break;
6172 }
6173 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006174 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006175 continue;
6176 }
6177
Eric Laurent3974e3b2017-12-07 17:58:43 -08006178 if (!profile->canOpenNewIo()) {
6179 ALOGW("Max Output number %u already opened for this profile %s",
6180 profile->maxOpenCount, profile->getTagName().c_str());
6181 continue;
6182 }
6183
Eric Laurent83efe1c2017-07-09 16:51:08 -07006184 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006185 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006186 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6187 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006188 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006189 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006190 profiles.removeAt(profile_index);
6191 profile_index--;
6192 } else {
6193 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006194 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006195 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006196 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6197 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006198 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006199 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006200
François Gaffie11d30102018-11-02 16:09:09 +01006201 if (device_distinguishes_on_address(deviceType)) {
6202 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6203 device->toString().c_str());
6204 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6205 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006206 }
Eric Laurente552edb2014-03-10 17:42:56 -07006207 ALOGV("checkOutputsForDevice(): adding output %d", output);
6208 }
6209 }
6210
6211 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006212 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006213 return BAD_VALUE;
6214 }
Eric Laurentd4692962014-05-05 18:13:44 -07006215 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006216 // check if one opened output is not needed any more after disconnecting one device
6217 for (size_t i = 0; i < mOutputs.size(); i++) {
6218 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006219 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006220 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006221 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006222 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006223 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006224 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006225 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6226 mOutputs.keyAt(i));
6227 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006228 }
Eric Laurente552edb2014-03-10 17:42:56 -07006229 }
6230 }
Eric Laurentd4692962014-05-05 18:13:44 -07006231 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006232 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006233 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6234 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006235 if (!profile->supportsDevice(device)) {
6236 continue;
6237 }
6238 ALOGV("checkOutputsForDevice(): "
6239 "clearing direct output profile %zu on module %s",
6240 j, hwModule->getName());
6241 profile->clearAudioProfiles();
6242 if (!profile->hasDynamicAudioProfile()) {
6243 continue;
6244 }
6245 // When a device is disconnected, if there is an IOProfile that contains dynamic
6246 // profiles and supports the disconnected device, call getAudioPort to repopulate
6247 // the capabilities of the devices that is supported by the IOProfile.
6248 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6249 if (supportedDevice == device ||
6250 !mAvailableOutputDevices.contains(supportedDevice)) {
6251 continue;
6252 }
6253 struct audio_port_v7 port;
6254 supportedDevice->toAudioPort(&port);
6255 status_t status = mpClientInterface->getAudioPort(&port);
6256 if (status == NO_ERROR) {
6257 supportedDevice->importAudioPort(port);
6258 }
Eric Laurente552edb2014-03-10 17:42:56 -07006259 }
6260 }
6261 }
6262 }
6263 return NO_ERROR;
6264}
6265
François Gaffie11d30102018-11-02 16:09:09 +01006266status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006267 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006268{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006269 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006270
François Gaffie11d30102018-11-02 16:09:09 +01006271 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006272 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006273 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006274 }
6275
Eric Laurentd4692962014-05-05 18:13:44 -07006276 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006277 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006278 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006279 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006280 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006281 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006282 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006283 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006284
François Gaffie11d30102018-11-02 16:09:09 +01006285 if (profile->supportsDevice(device)) {
6286 profiles.add(profile);
6287 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6288 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006289 }
6290 }
6291 }
6292
Eric Laurent0dd51852019-04-19 18:18:58 -07006293 if (profiles.isEmpty()) {
6294 ALOGW("%s: No input profile available for device %s",
6295 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006296 return BAD_VALUE;
6297 }
6298
6299 // open inputs for matching profiles if needed. Direct inputs are also opened to
6300 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6301 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6302
Eric Laurent1c333e22014-05-20 10:48:17 -07006303 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006304
Eric Laurentd4692962014-05-05 18:13:44 -07006305 // nothing to do if one input is already opened for this profile
6306 size_t input_index;
6307 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6308 desc = mInputs.valueAt(input_index);
6309 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006310 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006311 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006312 }
Eric Laurentd4692962014-05-05 18:13:44 -07006313 break;
6314 }
6315 }
6316 if (input_index != mInputs.size()) {
6317 continue;
6318 }
6319
Eric Laurent3974e3b2017-12-07 17:58:43 -08006320 if (!profile->canOpenNewIo()) {
6321 ALOGW("Max Input number %u already opened for this profile %s",
6322 profile->maxOpenCount, profile->getTagName().c_str());
6323 continue;
6324 }
6325
Eric Laurentfe231122017-11-17 17:48:06 -08006326 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006327 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006328 status_t status = desc->open(nullptr,
6329 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006330 AUDIO_SOURCE_MIC,
6331 AUDIO_INPUT_FLAG_NONE,
6332 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006333
Eric Laurentcf2c0212014-07-25 16:20:43 -07006334 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006335 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006336 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006337 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006338 mpClientInterface->setParameters(input, String8(param));
6339 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006340 }
François Gaffie11d30102018-11-02 16:09:09 +01006341 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006342 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006343 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006344 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006345 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006346 }
6347
Eric Laurent0dd51852019-04-19 18:18:58 -07006348 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006349 addInput(input, desc);
6350 }
6351 } // endif input != 0
6352
Eric Laurentcf2c0212014-07-25 16:20:43 -07006353 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006354 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006355 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006356 profiles.removeAt(profile_index);
6357 profile_index--;
6358 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006359 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006360 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006361 }
Eric Laurentd4692962014-05-05 18:13:44 -07006362 ALOGV("checkInputsForDevice(): adding input %d", input);
6363 }
6364 } // end scan profiles
6365
6366 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006367 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006368 return BAD_VALUE;
6369 }
6370 } else {
6371 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006372 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006373 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006374 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006375 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006376 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006377 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006378 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006379 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6380 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006381 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006382 }
6383 }
6384 }
6385 } // end disconnect
6386
6387 return NO_ERROR;
6388}
6389
6390
Eric Laurente0720872014-03-11 09:30:41 -07006391void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006392{
6393 ALOGV("closeOutput(%d)", output);
6394
François Gaffie1c878552018-11-22 16:53:21 +01006395 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6396 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006397 ALOGW("closeOutput() unknown output %d", output);
6398 return;
6399 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006400 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006401 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006402
Eric Laurente552edb2014-03-10 17:42:56 -07006403 // look for duplicated outputs connected to the output being removed.
6404 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006405 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6406 if (dupOutput->isDuplicated() &&
6407 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6408 sp<SwAudioOutputDescriptor> remainingOutput =
6409 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006410 // As all active tracks on duplicated output will be deleted,
6411 // and as they were also referenced on the other output, the reference
6412 // count for their stream type must be adjusted accordingly on
6413 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006414 const bool wasActive = remainingOutput->isActive();
6415 // Note: no-op on the closing output where all clients has already been set inactive
6416 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006417 // stop() will be a no op if the output is still active but is needed in case all
6418 // active streams refcounts where cleared above
6419 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006420 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006421 }
Eric Laurente552edb2014-03-10 17:42:56 -07006422 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6423 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6424
6425 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006426 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006427 }
6428 }
6429
Eric Laurent05b90f82014-08-27 15:32:29 -07006430 nextAudioPortGeneration();
6431
François Gaffie1c878552018-11-22 16:53:21 +01006432 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006433 if (index >= 0) {
6434 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006435 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6436 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006437 mAudioPatches.removeItemsAt(index);
6438 mpClientInterface->onAudioPatchListUpdate();
6439 }
6440
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006441 if (closingOutputWasActive) {
6442 closingOutput->stop();
6443 }
François Gaffie1c878552018-11-22 16:53:21 +01006444 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006445
François Gaffie53615e22015-03-19 09:24:12 +01006446 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006447 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006448 if (closingOutput == mSpatializerOutput) {
6449 mSpatializerOutput.clear();
6450 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006451
6452 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6453 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006454 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006455 bool directOutputOpen = false;
6456 for (size_t i = 0; i < mOutputs.size(); i++) {
6457 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6458 directOutputOpen = true;
6459 break;
6460 }
6461 }
6462 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006463 ALOGV("no direct outputs open, reset MSD patches");
6464 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6465 // how output devices for patching are resolved. Avoid by caching and reusing the
6466 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6467 // devices to patch to. This may be complicated by the fact that devices may become
6468 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006469 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006470 }
6471 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006472}
6473
6474void AudioPolicyManager::closeInput(audio_io_handle_t input)
6475{
6476 ALOGV("closeInput(%d)", input);
6477
6478 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6479 if (inputDesc == NULL) {
6480 ALOGW("closeInput() unknown input %d", input);
6481 return;
6482 }
6483
Eric Laurent6a94d692014-05-20 11:18:06 -07006484 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006485
François Gaffie11d30102018-11-02 16:09:09 +01006486 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006487 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006488 if (index >= 0) {
6489 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006490 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6491 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006492 mAudioPatches.removeItemsAt(index);
6493 mpClientInterface->onAudioPatchListUpdate();
6494 }
6495
Eric Laurentfe231122017-11-17 17:48:06 -08006496 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006497 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006498
François Gaffie11d30102018-11-02 16:09:09 +01006499 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6500 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006501 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006502 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006503 }
Eric Laurente552edb2014-03-10 17:42:56 -07006504}
6505
François Gaffie11d30102018-11-02 16:09:09 +01006506SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6507 const DeviceVector &devices,
6508 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006509{
6510 SortedVector<audio_io_handle_t> outputs;
6511
François Gaffie11d30102018-11-02 16:09:09 +01006512 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006513 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006514 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006515 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006516 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006517 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006518 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006519 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006520 outputs.add(openOutputs.keyAt(i));
6521 }
6522 }
6523 return outputs;
6524}
6525
Mikhail Naganov37977152018-07-11 15:54:44 -07006526void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6527{
6528 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6529 // output is suspended before any tracks are moved to it
6530 checkA2dpSuspend();
6531 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006532 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006533 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006534 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006535 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006536 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6537 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6538 // configuration changes will ultimately be rerouted correctly. We can still avoid
6539 // unnecessary rerouting by caching and reusing the arguments to
6540 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6541 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006542 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006543 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006544 // an event that changed routing likely occurred, inform upper layers
6545 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006546}
6547
François Gaffiec005e562018-11-06 15:04:49 +01006548bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6549 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006550{
François Gaffiec005e562018-11-06 15:04:49 +01006551 return mEngine->getProductStrategyForAttributes(lAttr) ==
6552 mEngine->getProductStrategyForAttributes(rAttr);
6553}
6554
Francois Gaffieff1eb522020-05-06 18:37:04 +02006555void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6556{
6557 for (size_t i = 0; i < mAudioSources.size(); i++) {
6558 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6559 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006560 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006561 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006562 connectAudioSource(sourceDesc);
6563 }
6564 }
6565}
6566
6567void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6568{
6569 for (size_t i = 0; i < mAudioSources.size(); i++) {
6570 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6571 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6572 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6573 disconnectAudioSource(sourceDesc);
6574 }
6575 }
6576}
6577
François Gaffiec005e562018-11-06 15:04:49 +01006578void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6579{
6580 auto psId = mEngine->getProductStrategyForAttributes(attr);
6581
6582 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6583 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006584
François Gaffie11d30102018-11-02 16:09:09 +01006585 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6586 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006587
Eric Laurentc209fe42020-06-05 18:11:23 -07006588 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006589 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006590 // take into account dynamic audio policies related changes: if a client is now associated
6591 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006592 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006593 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6594 if (desc->isDuplicated()) {
6595 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006596 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006597 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6598 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6599 continue;
6600 }
6601 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006602 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006603 client->uid(), client->session(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006604 if (status != OK) {
6605 continue;
6606 }
yucliuf4de36d2020-09-14 14:57:56 -07006607 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006608 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006609 maxLatency = desc->latency();
6610 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006611 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006612 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006613 }
6614 }
6615
Eric Laurent56ed8842022-11-15 16:04:41 +01006616 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006617 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6618 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006619 for (audio_io_handle_t srcOut : srcOutputs) {
6620 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006621 if (desc == nullptr) continue;
6622
6623 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006624 maxLatency = desc->latency();
6625 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006626
Eric Laurent56ed8842022-11-15 16:04:41 +01006627 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006628 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006629 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006630 // a client on a non direct outputs has necessarily a linear PCM format
6631 // so we can call selectOutput() safely
6632 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6633 client->flags(),
6634 client->config().format,
6635 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006636 client->config().sample_rate,
6637 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006638 if (newOutput != srcOut) {
6639 invalidate = true;
6640 break;
6641 }
6642 } else {
6643 sp<IOProfile> profile = getProfileForOutput(newDevices,
6644 client->config().sample_rate,
6645 client->config().format,
6646 client->config().channel_mask,
6647 client->flags(),
6648 true /* directOnly */);
6649 if (profile != desc->mProfile) {
6650 invalidate = true;
6651 break;
6652 }
6653 }
6654 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006655 // mute strategy while moving tracks from one output to another
6656 if (invalidate) {
6657 invalidatedOutputs.push_back(desc);
6658 if (desc->isStrategyActive(psId)) {
6659 setStrategyMute(psId, true, desc);
6660 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6661 newDevices.types());
6662 }
Eric Laurente552edb2014-03-10 17:42:56 -07006663 }
François Gaffiec005e562018-11-06 15:04:49 +01006664 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006665 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006666 connectAudioSource(source);
6667 }
Eric Laurente552edb2014-03-10 17:42:56 -07006668 }
6669
Eric Laurent56ed8842022-11-15 16:04:41 +01006670 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6671 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6672 std::to_string(srcOutputs[0]).c_str(),
6673 std::to_string(dstOutputs[0]).c_str());
6674
François Gaffiec005e562018-11-06 15:04:49 +01006675 // Move effects associated to this stream from previous output to new output
6676 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006677 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006678 }
François Gaffiec005e562018-11-06 15:04:49 +01006679 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006680 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006681 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6682 mpClientInterface->invalidateStream(stream);
6683 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006684 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006685 desc->setTracksInvalidatedStatusByStrategy(psId);
6686 }
Eric Laurente552edb2014-03-10 17:42:56 -07006687 }
6688 }
6689}
6690
Eric Laurente0720872014-03-11 09:30:41 -07006691void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006692{
François Gaffiec005e562018-11-06 15:04:49 +01006693 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6694 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6695 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006696 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006697 }
Eric Laurente552edb2014-03-10 17:42:56 -07006698}
6699
Kevin Rocard153f92d2018-12-18 18:33:28 -08006700void AudioPolicyManager::checkSecondaryOutputs() {
6701 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006702 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006703 for (size_t i = 0; i < mOutputs.size(); i++) {
6704 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6705 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006706 sp<AudioPolicyMix> primaryMix;
6707 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006708 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006709 client->uid(), client->session(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006710 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6711 for (auto &secondaryMix : secondaryMixes) {
6712 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6713 if (outputDesc != nullptr &&
6714 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6715 secondaryDescs.push_back(outputDesc);
6716 }
6717 }
6718
jiabin10a03f12021-05-07 23:46:28 +00006719 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006720 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006721 } else if (!std::equal(
6722 client->getSecondaryOutputs().begin(),
6723 client->getSecondaryOutputs().end(),
6724 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006725 if (!audio_is_linear_pcm(client->config().format)) {
6726 // If the format is not PCM, the tracks should be invalidated to get correct
6727 // behavior when the secondary output is changed.
6728 streamsToInvalidate.insert(client->stream());
6729 } else {
6730 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6731 std::vector<audio_io_handle_t> secondaryOutputIds;
6732 for (const auto &secondaryDesc: secondaryDescs) {
6733 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6734 weakSecondaryDescs.push_back(secondaryDesc);
6735 }
6736 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6737 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006738 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006739 }
6740 }
6741 }
jiabin10a03f12021-05-07 23:46:28 +00006742 if (!trackSecondaryOutputs.empty()) {
6743 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6744 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006745 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006746 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006747 mpClientInterface->invalidateStream(stream);
6748 }
6749}
6750
Eric Laurent2517af32020-11-25 15:31:27 +01006751bool AudioPolicyManager::isScoRequestedForComm() const {
6752 AudioDeviceTypeAddrVector devices;
6753 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6754 for (const auto &device : devices) {
6755 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6756 return true;
6757 }
6758 }
6759 return false;
6760}
6761
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006762bool AudioPolicyManager::isHearingAidUsedForComm() const {
6763 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6764 true /*fromCache*/);
6765 for (const auto &device : devices) {
6766 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6767 return true;
6768 }
6769 }
6770 return false;
6771}
6772
6773
Eric Laurente0720872014-03-11 09:30:41 -07006774void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006775{
François Gaffie53615e22015-03-19 09:24:12 +01006776 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006777 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006778 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006779 return;
6780 }
6781
Eric Laurent3a4311c2014-03-17 12:00:47 -07006782 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006783 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6784 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006785 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006786
6787 // if suspended, restore A2DP output if:
6788 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006789 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006790 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006791 //
Eric Laurentf732e072016-08-03 19:30:28 -07006792 // if not suspended, suspend A2DP output if:
6793 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006794 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006795 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006796 //
6797 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006798 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006799 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006800 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006801 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006802
6803 mpClientInterface->restoreOutput(a2dpOutput);
6804 mA2dpSuspended = false;
6805 }
6806 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006807 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006808 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006809 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006810 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006811
6812 mpClientInterface->suspendOutput(a2dpOutput);
6813 mA2dpSuspended = true;
6814 }
6815 }
6816}
6817
François Gaffie11d30102018-11-02 16:09:09 +01006818DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6819 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006820{
François Gaffie11d30102018-11-02 16:09:09 +01006821 DeviceVector devices;
6822
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006823 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006824 if (index >= 0) {
6825 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006826 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006827 ALOGV("%s device %s forced by patch %d", __func__,
6828 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6829 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006830 }
6831 }
6832
Dean Wheatley514b4312020-06-17 21:45:00 +10006833 // Do not retrieve engine device for outputs through MSD
6834 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6835 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6836 return outputDesc->devices();
6837 }
6838
Eric Laurent97ac8712018-07-27 18:59:02 -07006839 // Honor explicit routing requests only if no client using default routing is active on this
6840 // input: a specific app can not force routing for other apps by setting a preferred device.
6841 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006842 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006843 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006844 if (device != nullptr) {
6845 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006846 }
6847
François Gaffiea807ef92018-11-05 10:44:33 +01006848 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6849 // of setForceUse / Default Bus device here
6850 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6851 if (device != nullptr) {
6852 return DeviceVector(device);
6853 }
6854
François Gaffiec005e562018-11-06 15:04:49 +01006855 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6856 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6857 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306858 auto hasStreamActive = [&](auto stream) {
6859 return hasStream(streams, stream) && isStreamActive(stream, 0);
6860 };
Eric Laurent484e9272018-06-07 17:29:23 -07006861
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306862 auto doGetOutputDevicesForVoice = [&]() {
6863 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006864 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306865 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006866 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6867 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306868 };
6869
6870 // With low-latency playing on speaker, music on WFD, when the first low-latency
6871 // output is stopped, getNewOutputDevices checks for a product strategy
6872 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006873 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306874 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6875 // stream is associated to the output descriptor.
6876 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6877 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6878 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6879 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006880 // Retrieval of devices for voice DL is done on primary output profile, cannot
6881 // check the route (would force modifying configuration file for this profile)
6882 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6883 break;
6884 }
Eric Laurente552edb2014-03-10 17:42:56 -07006885 }
François Gaffiec005e562018-11-06 15:04:49 +01006886 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006887 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006888}
6889
François Gaffie11d30102018-11-02 16:09:09 +01006890sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6891 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006892{
François Gaffie11d30102018-11-02 16:09:09 +01006893 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006894
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006895 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006896 if (index >= 0) {
6897 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006898 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006899 ALOGV("getNewInputDevice() device %s forced by patch %d",
6900 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6901 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006902 }
6903 }
6904
Eric Laurent97ac8712018-07-27 18:59:02 -07006905 // Honor explicit routing requests only if no client using default routing is active on this
6906 // input: a specific app can not force routing for other apps by setting a preferred device.
6907 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006908 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6909 if (device != nullptr) {
6910 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006911 }
6912
Eric Laurentdc95a252018-04-12 12:46:56 -07006913 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006914 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006915 audio_attributes_t attributes;
6916 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006917 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006918 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6919 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006920 attributes = topClient->attributes();
6921 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006922 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006923 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006924 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6925 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006926 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006927 }
6928
Francois Gaffie716e1432019-01-14 16:58:59 +01006929 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6930 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006931 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006932 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006933 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006934 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006935
Eric Laurente552edb2014-03-10 17:42:56 -07006936 return device;
6937}
6938
Eric Laurent794fde22016-03-11 09:50:45 -08006939bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6940 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006941 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006942}
6943
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006944status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006945 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006946 if (devices == nullptr) {
6947 return BAD_VALUE;
6948 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006949
Andy Hung6d23c0f2022-02-16 09:37:15 -08006950 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07006951 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
6952 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08006953 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006954 for (const auto& device : curDevices) {
6955 devices->push_back(device->getDeviceTypeAddr());
6956 }
6957 return NO_ERROR;
6958}
6959
Eric Laurente0720872014-03-11 09:30:41 -07006960void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006961 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006962 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006963 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006964 updateDevicesAndOutputs();
6965 break;
6966 default:
6967 break;
6968 }
6969}
6970
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006971uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006972
6973 // skip beacon mute management if a dedicated TTS output is available
6974 if (mTtsOutputAvailable) {
6975 return 0;
6976 }
6977
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006978 switch(event) {
6979 case STARTING_OUTPUT:
6980 mBeaconMuteRefCount++;
6981 break;
6982 case STOPPING_OUTPUT:
6983 if (mBeaconMuteRefCount > 0) {
6984 mBeaconMuteRefCount--;
6985 }
6986 break;
6987 case STARTING_BEACON:
6988 mBeaconPlayingRefCount++;
6989 break;
6990 case STOPPING_BEACON:
6991 if (mBeaconPlayingRefCount > 0) {
6992 mBeaconPlayingRefCount--;
6993 }
6994 break;
6995 }
6996
6997 if (mBeaconMuteRefCount > 0) {
6998 // any playback causes beacon to be muted
6999 return setBeaconMute(true);
7000 } else {
7001 // no other playback: unmute when beacon starts playing, mute when it stops
7002 return setBeaconMute(mBeaconPlayingRefCount == 0);
7003 }
7004}
7005
7006uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7007 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7008 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7009 // keep track of muted state to avoid repeating mute/unmute operations
7010 if (mBeaconMuted != mute) {
7011 // mute/unmute AUDIO_STREAM_TTS on all outputs
7012 ALOGV("\t muting %d", mute);
7013 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007014 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7015 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7016 ALOGV("\t no tts volume source available");
7017 return 0;
7018 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007019 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007020 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007021 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007022 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007023 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007024 maxLatency = latency;
7025 }
7026 }
7027 mBeaconMuted = mute;
7028 return maxLatency;
7029 }
7030 return 0;
7031}
7032
Eric Laurente0720872014-03-11 09:30:41 -07007033void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007034{
François Gaffiec005e562018-11-06 15:04:49 +01007035 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007036 mPreviousOutputs = mOutputs;
7037}
7038
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007039uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007040 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007041 uint32_t delayMs)
7042{
7043 // mute/unmute strategies using an incompatible device combination
7044 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7045 // if unmuting, unmute only after the specified delay
7046 if (outputDesc->isDuplicated()) {
7047 return 0;
7048 }
7049
7050 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007051 DeviceVector devices = outputDesc->devices();
7052 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007053
François Gaffiec005e562018-11-06 15:04:49 +01007054 auto productStrategies = mEngine->getOrderedProductStrategies();
7055 for (const auto &productStrategy : productStrategies) {
7056 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7057 DeviceVector curDevices =
7058 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7059 curDevices = curDevices.filter(outputDesc->supportedDevices());
7060 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007061 bool doMute = false;
7062
François Gaffiec005e562018-11-06 15:04:49 +01007063 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007064 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007065 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7066 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007067 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007068 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007069 }
Eric Laurent99401132014-05-07 19:48:15 -07007070 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007071 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007072 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007073 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007074 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007075 continue;
7076 }
François Gaffiec005e562018-11-06 15:04:49 +01007077 ALOGVV("%s() %s (curDevice %s)", __func__,
7078 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7079 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7080 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007081 if (mute) {
7082 // FIXME: should not need to double latency if volume could be applied
7083 // immediately by the audioflinger mixer. We must account for the delay
7084 // between now and the next time the audioflinger thread for this output
7085 // will process a buffer (which corresponds to one buffer size,
7086 // usually 1/2 or 1/4 of the latency).
7087 if (muteWaitMs < desc->latency() * 2) {
7088 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007089 }
7090 }
7091 }
7092 }
7093 }
7094 }
7095
Eric Laurent99401132014-05-07 19:48:15 -07007096 // temporary mute output if device selection changes to avoid volume bursts due to
7097 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007098 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007099 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007100
Eric Laurentdc462862016-07-19 12:29:53 -07007101 if (muteWaitMs < tempMuteWaitMs) {
7102 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007103 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007104
7105 // If recommended duration is defined, replace temporary mute duration to avoid
7106 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7107 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7108 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7109 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7110 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7111
François Gaffieaaac0fd2018-11-22 17:56:39 +01007112 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7113 // make sure that we do not start the temporary mute period too early in case of
7114 // delayed device change
7115 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7116 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007117 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007118 }
7119 }
7120
Eric Laurente552edb2014-03-10 17:42:56 -07007121 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7122 if (muteWaitMs > delayMs) {
7123 muteWaitMs -= delayMs;
7124 usleep(muteWaitMs * 1000);
7125 return muteWaitMs;
7126 }
7127 return 0;
7128}
7129
François Gaffie11d30102018-11-02 16:09:09 +01007130uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7131 const DeviceVector &devices,
7132 bool force,
7133 int delayMs,
7134 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007135 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007136{
François Gaffie11d30102018-11-02 16:09:09 +01007137 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007138 uint32_t muteWaitMs;
7139
7140 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007141 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7142 nullptr /* patchHandle */, requiresMuteCheck);
7143 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7144 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007145 return muteWaitMs;
7146 }
Eric Laurente552edb2014-03-10 17:42:56 -07007147
7148 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007149 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007150 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007151 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007152
François Gaffie11d30102018-11-02 16:09:09 +01007153 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7154
7155 if (!filteredDevices.isEmpty()) {
7156 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007157 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007158
7159 // if the outputs are not materially active, there is no need to mute.
7160 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007161 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007162 } else {
7163 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7164 muteWaitMs = 0;
7165 }
Eric Laurente552edb2014-03-10 17:42:56 -07007166
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007167 bool outputRouted = outputDesc->isRouted();
7168
Eric Laurent79ea9582020-06-11 18:49:24 -07007169 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7170 // output profile or if new device is not supported AND previous device(s) is(are) still
7171 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007172 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007173 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7174 // restore previous device after evaluating strategy mute state
7175 outputDesc->setDevices(prevDevices);
7176 return muteWaitMs;
7177 }
7178
Eric Laurente552edb2014-03-10 17:42:56 -07007179 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007180 // the requested device is AUDIO_DEVICE_NONE
7181 // OR the requested device is the same as current device
7182 // AND force is not specified
7183 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007184 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007185 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007186 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7187 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007188 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7189 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7190 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7191 }
Eric Laurente552edb2014-03-10 17:42:56 -07007192 return muteWaitMs;
7193 }
7194
François Gaffie11d30102018-11-02 16:09:09 +01007195 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007196
Eric Laurente552edb2014-03-10 17:42:56 -07007197 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007198 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007199 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007200 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007201 PatchBuilder patchBuilder;
7202 patchBuilder.addSource(outputDesc);
7203 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7204 for (const auto &filteredDevice : filteredDevices) {
7205 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007206 }
7207
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007208 // Add half reported latency to delayMs when muteWaitMs is null in order
7209 // to avoid disordered sequence of muting volume and changing devices.
7210 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7211 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007212 }
Eric Laurente552edb2014-03-10 17:42:56 -07007213
7214 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007215 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007216
7217 return muteWaitMs;
7218}
7219
Eric Laurentc75307b2015-03-17 15:29:32 -07007220status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007221 int delayMs,
7222 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007223{
Eric Laurent6a94d692014-05-20 11:18:06 -07007224 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007225 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7226 return INVALID_OPERATION;
7227 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007228 if (patchHandle) {
7229 index = mAudioPatches.indexOfKey(*patchHandle);
7230 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007231 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007232 }
7233 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007234 return INVALID_OPERATION;
7235 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007236 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007237 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007238 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007239 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007240 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007241 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007242 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007243 return status;
7244}
7245
7246status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007247 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007248 bool force,
7249 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007250{
7251 status_t status = NO_ERROR;
7252
Eric Laurent1f2f2232014-06-02 12:01:23 -07007253 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007254 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7255 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007256
François Gaffie11d30102018-11-02 16:09:09 +01007257 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007258 PatchBuilder patchBuilder;
7259 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007260 // AUDIO_SOURCE_HOTWORD is for internal use only:
7261 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007262 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7263 auto result = usecase;
7264 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7265 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7266 }
7267 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007268 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007269 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007270 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007271 }
7272 }
7273 return status;
7274}
7275
Eric Laurent6a94d692014-05-20 11:18:06 -07007276status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7277 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007278{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007279 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007280 ssize_t index;
7281 if (patchHandle) {
7282 index = mAudioPatches.indexOfKey(*patchHandle);
7283 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007284 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007285 }
7286 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007287 return INVALID_OPERATION;
7288 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007289 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007290 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007291 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007292 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007293 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007294 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007295 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007296 return status;
7297}
7298
François Gaffie11d30102018-11-02 16:09:09 +01007299sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007300 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007301 audio_format_t& format,
7302 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007303 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007304{
7305 // Choose an input profile based on the requested capture parameters: select the first available
7306 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007307 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007308 //
7309 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7310 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007311
jiabin2fd710d2022-05-02 23:20:22 +00007312 const audio_input_flags_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ;
7313 const audio_input_flags_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007314
jiabin2fd710d2022-05-02 23:20:22 +00007315 for (;;) {
7316 sp<IOProfile> firstInexact = nullptr;
7317 uint32_t updatedSamplingRate = 0;
7318 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7319 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7320 for (const auto& hwModule : mHwModules) {
7321 for (const auto& profile : hwModule->getInputProfiles()) {
7322 // profile->log();
7323 //updatedFormat = format;
7324 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7325 &samplingRate /*updatedSamplingRate*/,
7326 format,
7327 &format, /*updatedFormat*/
7328 channelMask,
7329 &channelMask /*updatedChannelMask*/,
7330 // FIXME ugly cast
7331 (audio_output_flags_t) flags,
7332 true /*exactMatchRequiredForInputFlags*/)) {
7333 return profile;
7334 }
7335 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7336 samplingRate,
7337 &updatedSamplingRate,
7338 format,
7339 &updatedFormat,
7340 channelMask,
7341 &updatedChannelMask,
7342 // FIXME ugly cast
7343 (audio_output_flags_t) flags,
7344 false /*exactMatchRequiredForInputFlags*/)) {
7345 firstInexact = profile;
7346 }
7347 }
7348 }
7349
7350 if (firstInexact != nullptr) {
7351 samplingRate = updatedSamplingRate;
7352 format = updatedFormat;
7353 channelMask = updatedChannelMask;
7354 return firstInexact;
7355 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7356 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7357 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7358 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7359 flags = AUDIO_INPUT_FLAG_NONE;
7360 } else { // fail
7361 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7362 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7363 samplingRate, format, channelMask, oriFlags);
7364 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007365 }
7366 }
jiabin2fd710d2022-05-02 23:20:22 +00007367
7368 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007369}
7370
François Gaffieaaac0fd2018-11-22 17:56:39 +01007371float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7372 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007373 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007374 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007375{
jiabin9a3361e2019-10-01 09:38:30 -07007376 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007377
7378 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7379 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7380 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7381 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007382 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7383 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7384 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7385 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7386 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007387
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007388 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007389 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7390 mOutputs.isActive(ringVolumeSrc, 0)) {
7391 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007392 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007393 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007394 }
7395
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007396 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007397 if ((volumeSource != callVolumeSrc && (isInCall() ||
7398 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007399 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007400 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7401 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007402 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7403 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7404 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007405 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007406 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007407 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007408 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007409 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007410 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007411 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7412 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7413 // programmatically muted.
7414 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7415 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7416 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007417 bool exemptFromCapping =
7418 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7419 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007420 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7421 volumeSource, volumeDb);
7422 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007423 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7424 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7425 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007426 }
7427 }
Eric Laurente552edb2014-03-10 17:42:56 -07007428 // if a headset is connected, apply the following rules to ring tones and notifications
7429 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007430 // - always attenuate notifications volume by 6dB
7431 // - attenuate ring tones volume by 6dB unless music is not playing and
7432 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007433 // - if music is playing, always limit the volume to current music volume,
7434 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007435 if (!Intersection(deviceTypes,
7436 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7437 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007438 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7439 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007440 ((volumeSource == alarmVolumeSrc ||
7441 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007442 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7443 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7444 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007445 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7446 curves.canBeMuted()) {
7447
Eric Laurente552edb2014-03-10 17:42:56 -07007448 // when the phone is ringing we must consider that music could have been paused just before
7449 // by the music application and behave as if music was active if the last music track was
7450 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007451 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007452 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007453 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007454 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007455 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7456 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007457 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007458 float musicVolDb = computeVolume(musicCurves,
7459 musicVolumeSrc,
7460 musicCurves.getVolumeIndex(musicDevice),
7461 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007462 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7463 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7464 if (volumeDb > minVolDb) {
7465 volumeDb = minVolDb;
7466 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007467 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007468 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7469 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7470 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007471 // on A2DP, also ensure notification volume is not too low compared to media when
7472 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007473 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007474 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007475 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7476 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007477 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7478 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007479 }
7480 }
jiabin9a3361e2019-10-01 09:38:30 -07007481 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007482 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007483 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007484 }
7485 }
7486
François Gaffie43c73442018-11-08 08:21:55 +01007487 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007488}
7489
Eric Laurent3839bc02018-07-10 18:33:34 -07007490int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007491 VolumeSource fromVolumeSource,
7492 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007493{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007494 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007495 return srcIndex;
7496 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007497 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7498 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007499 float minSrc = (float)srcCurves.getVolumeIndexMin();
7500 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7501 float minDst = (float)dstCurves.getVolumeIndexMin();
7502 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007503
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007504 // preserve mute request or correct range
7505 if (srcIndex < minSrc) {
7506 if (srcIndex == 0) {
7507 return 0;
7508 }
7509 srcIndex = minSrc;
7510 } else if (srcIndex > maxSrc) {
7511 srcIndex = maxSrc;
7512 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007513 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7514}
7515
François Gaffieaaac0fd2018-11-22 17:56:39 +01007516status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7517 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007518 int index,
7519 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007520 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007521 int delayMs,
7522 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007523{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007524 // do not change actual attributes volume if the attributes is muted
7525 if (outputDesc->isMuted(volumeSource)) {
7526 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7527 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007528 return NO_ERROR;
7529 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007530 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7531 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7532 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7533 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007534
Eric Laurent2517af32020-11-25 15:31:27 +01007535 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007536 bool isHAUsed = isHearingAidUsedForComm();
7537
Eric Laurente552edb2014-03-10 17:42:56 -07007538 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007539 // if sco and call follow same curves, bypass forceUseForComm
7540 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007541 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007542 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007543 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007544 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007545 // Do not return an error here as AudioService will always set both voice call
7546 // and bluetooth SCO volumes due to stream aliasing.
7547 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007548 }
jiabin9a3361e2019-10-01 09:38:30 -07007549 if (deviceTypes.empty()) {
7550 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007551 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007552
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007553 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7554 ALOGE("invalid volume index range");
7555 return BAD_VALUE;
7556 }
7557
jiabin9a3361e2019-10-01 09:38:30 -07007558 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7559 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007560 // Force VoIP volume to max for bluetooth SCO device except if muted
7561 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007562 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007563 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007564 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007565 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007566 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007567 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007568
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007569 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007570 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007571 // 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 +01007572 if (isVoiceVolSrc) {
7573 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007574 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007575 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007576 }
Eric Laurent18fba842016-03-31 14:41:26 -07007577 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007578 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7579 mLastVoiceVolume = voiceVolume;
7580 }
7581 }
Eric Laurente552edb2014-03-10 17:42:56 -07007582 return NO_ERROR;
7583}
7584
Eric Laurentc75307b2015-03-17 15:29:32 -07007585void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007586 const DeviceTypeSet& deviceTypes,
7587 int delayMs,
7588 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007589{
jiabincd510522020-01-22 09:40:55 -08007590 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007591 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7592 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7593 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007594 curves.getVolumeIndex(deviceTypes),
7595 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007596 }
7597}
7598
François Gaffiec005e562018-11-06 15:04:49 +01007599void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7600 bool on,
7601 const sp<AudioOutputDescriptor>& outputDesc,
7602 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007603 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007604{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007605 std::vector<VolumeSource> sourcesToMute;
7606 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7607 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7608 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007609 VolumeSource source = toVolumeSource(attributes, false);
7610 if ((source != VOLUME_SOURCE_NONE) &&
7611 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7612 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007613 sourcesToMute.push_back(source);
7614 }
Eric Laurente552edb2014-03-10 17:42:56 -07007615 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007616 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007617 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007618 }
7619
Eric Laurente552edb2014-03-10 17:42:56 -07007620}
7621
François Gaffieaaac0fd2018-11-22 17:56:39 +01007622void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7623 bool on,
7624 const sp<AudioOutputDescriptor>& outputDesc,
7625 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007626 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007627{
jiabin9a3361e2019-10-01 09:38:30 -07007628 if (deviceTypes.empty()) {
7629 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007630 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007631 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007632 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007633 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007634 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007635 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007636 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7637 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007638 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007639 }
7640 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007641 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7642 // ignored
7643 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007644 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007645 if (!outputDesc->isMuted(volumeSource)) {
7646 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007647 return;
7648 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007649 if (outputDesc->decMuteCount(volumeSource) == 0) {
7650 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007651 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007652 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007653 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007654 delayMs);
7655 }
7656 }
7657}
7658
François Gaffie53615e22015-03-19 09:24:12 +01007659bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7660{
François Gaffiec005e562018-11-06 15:04:49 +01007661 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007662 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7663 return true;
7664 }
7665
7666 // has known usage?
7667 switch (paa->usage) {
7668 case AUDIO_USAGE_UNKNOWN:
7669 case AUDIO_USAGE_MEDIA:
7670 case AUDIO_USAGE_VOICE_COMMUNICATION:
7671 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7672 case AUDIO_USAGE_ALARM:
7673 case AUDIO_USAGE_NOTIFICATION:
7674 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7675 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7676 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7677 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7678 case AUDIO_USAGE_NOTIFICATION_EVENT:
7679 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7680 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7681 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7682 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007683 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007684 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007685 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007686 case AUDIO_USAGE_EMERGENCY:
7687 case AUDIO_USAGE_SAFETY:
7688 case AUDIO_USAGE_VEHICLE_STATUS:
7689 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007690 break;
7691 default:
7692 return false;
7693 }
7694 return true;
7695}
7696
François Gaffie2110e042015-03-24 08:41:51 +01007697audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7698{
7699 return mEngine->getForceUse(usage);
7700}
7701
Eric Laurent96d1dda2022-03-14 17:14:19 +01007702bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007703 return isStateInCall(mEngine->getPhoneState());
7704}
7705
Eric Laurent96d1dda2022-03-14 17:14:19 +01007706bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007707 return is_state_in_call(state);
7708}
7709
Eric Laurent74b71512019-11-06 17:21:57 -08007710bool AudioPolicyManager::isCallAudioAccessible()
7711{
7712 audio_mode_t mode = mEngine->getPhoneState();
7713 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007714 || (mode == AUDIO_MODE_CALL_SCREEN)
7715 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007716}
7717
Eric Laurentd60560a2015-04-10 11:31:20 -07007718void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7719{
7720 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007721 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007722 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007723 sourceDesc->sinkDevice()->equals(deviceDesc))
7724 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007725 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007726 }
7727 }
7728
7729 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7730 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7731 bool release = false;
7732 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7733 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7734 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7735 source->ext.device.type == deviceDesc->type()) {
7736 release = true;
7737 }
7738 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007739 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007740 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7741 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7742 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007743 sink->ext.device.type == deviceDesc->type() &&
7744 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7745 || strncmp(sink->ext.device.address, address,
7746 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007747 release = true;
7748 }
7749 }
7750 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007751 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7752 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007753 }
7754 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007755
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007756 mInputs.clearSessionRoutesForDevice(deviceDesc);
7757
Francois Gaffie716e1432019-01-14 16:58:59 +01007758 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007759}
7760
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007761void AudioPolicyManager::modifySurroundFormats(
7762 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007763 std::unordered_set<audio_format_t> enforcedSurround(
7764 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007765 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7766 for (const auto& pair : mConfig.getSurroundFormats()) {
7767 allSurround.insert(pair.first);
7768 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7769 }
Phil Burk09bc4612016-02-24 15:58:15 -08007770
7771 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7772 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007773 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007774 // This is the resulting set of formats depending on the surround mode:
7775 // 'all surround' = allSurround
7776 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7777 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7778 // 'manual surround' = mManualSurroundFormats
7779 // AUTO: formats v 'enforced surround'
7780 // ALWAYS: formats v 'all surround' v 'enforced surround'
7781 // NEVER: formats ^ 'non-surround'
7782 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007783
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007784 std::unordered_set<audio_format_t> formatSet;
7785 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7786 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007787 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007788 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007789 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007790 formatSet.insert(*formatIter);
7791 }
7792 }
7793 } else {
7794 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7795 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007796 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007797
jiabin81772902018-04-02 17:52:27 -07007798 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007799 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007800 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7801 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7802 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007803 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007804 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7805 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7806 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007807 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007808 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007809 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007810 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007811 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007812 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007813}
7814
jiabin06e4bab2019-07-29 10:13:34 -07007815void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7816 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007817 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7818 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7819
7820 // If NEVER, then remove support for channelMasks > stereo.
7821 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007822 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7823 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007824 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007825 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007826 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007827 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007828 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007829 }
7830 }
jiabin81772902018-04-02 17:52:27 -07007831 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7832 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7833 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007834 bool supports5dot1 = false;
7835 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007836 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007837 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7838 supports5dot1 = true;
7839 break;
7840 }
7841 }
7842 // If not then add 5.1 support.
7843 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007844 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007845 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007846 }
Phil Burk09bc4612016-02-24 15:58:15 -08007847 }
7848}
7849
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007850void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007851 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007852 AudioProfileVector &profiles)
7853{
7854 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007855 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007856
François Gaffie112b0af2015-11-19 16:13:25 +01007857 // Format MUST be checked first to update the list of AudioProfile
7858 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007859 reply = mpClientInterface->getParameters(
7860 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007861 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007862 AudioParameter repliedParameters(reply);
7863 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007864 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007865 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7866 return;
7867 }
Phil Burk09bc4612016-02-24 15:58:15 -08007868 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007869 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007870 if (device == AUDIO_DEVICE_OUT_HDMI
7871 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007872 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007873 }
jiabin3e277cc2019-09-10 14:27:34 -07007874 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007875 }
François Gaffie112b0af2015-11-19 16:13:25 +01007876
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007877 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007878 ChannelMaskSet channelMasks;
7879 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007880 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007881 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007882
7883 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007884 reply = mpClientInterface->getParameters(
7885 ioHandle,
7886 requestedParameters.toString() + ";" +
7887 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007888 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007889 AudioParameter repliedParameters(reply);
7890 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007891 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007892 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007893 }
7894 }
7895 if (profiles.hasDynamicChannelsFor(format)) {
7896 reply = mpClientInterface->getParameters(ioHandle,
7897 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007898 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007899 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007900 AudioParameter repliedParameters(reply);
7901 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007902 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007903 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007904 if (device == AUDIO_DEVICE_OUT_HDMI
7905 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007906 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007907 }
François Gaffie112b0af2015-11-19 16:13:25 +01007908 }
7909 }
jiabin3e277cc2019-09-10 14:27:34 -07007910 addDynamicAudioProfileAndSort(
7911 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007912 }
7913}
Eric Laurentd60560a2015-04-10 11:31:20 -07007914
Mikhail Naganovdc769682018-05-04 15:34:08 -07007915status_t AudioPolicyManager::installPatch(const char *caller,
7916 audio_patch_handle_t *patchHandle,
7917 AudioIODescriptorInterface *ioDescriptor,
7918 const struct audio_patch *patch,
7919 int delayMs)
7920{
7921 ssize_t index = mAudioPatches.indexOfKey(
7922 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7923 *patchHandle : ioDescriptor->getPatchHandle());
7924 sp<AudioPatch> patchDesc;
7925 status_t status = installPatch(
7926 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7927 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007928 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007929 }
7930 return status;
7931}
7932
7933status_t AudioPolicyManager::installPatch(const char *caller,
7934 ssize_t index,
7935 audio_patch_handle_t *patchHandle,
7936 const struct audio_patch *patch,
7937 int delayMs,
7938 uid_t uid,
7939 sp<AudioPatch> *patchDescPtr)
7940{
7941 sp<AudioPatch> patchDesc;
7942 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7943 if (index >= 0) {
7944 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007945 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007946 }
7947
7948 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7949 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7950 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7951 if (status == NO_ERROR) {
7952 if (index < 0) {
7953 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007954 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007955 } else {
7956 patchDesc->mPatch = *patch;
7957 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007958 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007959 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007960 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007961 }
7962 nextAudioPortGeneration();
7963 mpClientInterface->onAudioPatchListUpdate();
7964 }
7965 if (patchDescPtr) *patchDescPtr = patchDesc;
7966 return status;
7967}
7968
jiabinbce0c1d2020-10-05 11:20:18 -07007969bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7970{
7971 const TrackClientVector activeClients = output->getActiveClients();
7972 if (activeClients.empty()) {
7973 return true;
7974 }
7975 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7976 if (index < 0) {
7977 ALOGE("%s, no audio patch found while there are active clients on output %d",
7978 __func__, output->getId());
7979 return false;
7980 }
7981 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7982 DeviceVector routedDevices;
7983 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7984 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7985 patchDesc->mPatch.sinks[i].id);
7986 if (device == nullptr) {
7987 ALOGE("%s, no audio device found with id(%d)",
7988 __func__, patchDesc->mPatch.sinks[i].id);
7989 return false;
7990 }
7991 routedDevices.add(device);
7992 }
7993 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007994 if (client->isInvalid()) {
7995 // No need to take care about invalidated clients.
7996 continue;
7997 }
jiabinbce0c1d2020-10-05 11:20:18 -07007998 sp<DeviceDescriptor> preferredDevice =
7999 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8000 if (mEngine->getOutputDevicesForAttributes(
8001 client->attributes(), preferredDevice, false) == routedDevices) {
8002 return false;
8003 }
8004 }
8005 return true;
8006}
8007
8008sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008009 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008010 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8011 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008012{
8013 for (const auto& device : devices) {
8014 // TODO: This should be checking if the profile supports the device combo.
8015 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008016 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8017 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008018 return nullptr;
8019 }
8020 }
8021 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8022 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008023 status_t status = desc->open(halConfig, mixerConfig, devices,
8024 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008025 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008026 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008027 return nullptr;
8028 }
8029
8030 // Here is where the out_set_parameters() for card & device gets called
8031 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8032 const audio_devices_t deviceType = device->type();
8033 const String8 &address = String8(device->address().c_str());
8034 if (!address.isEmpty()) {
8035 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8036 mpClientInterface->setParameters(output, String8(param));
8037 free(param);
8038 }
8039 updateAudioProfiles(device, output, profile->getAudioProfiles());
8040 if (!profile->hasValidAudioProfile()) {
8041 ALOGW("%s() missing param", __func__);
8042 desc->close();
8043 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008044 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8045 // Reopen the output with the best audio profile picked by APM when the profile supports
8046 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008047 desc->close();
8048 output = AUDIO_IO_HANDLE_NONE;
8049 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8050 profile->pickAudioProfile(
8051 config.sample_rate, config.channel_mask, config.format);
8052 config.offload_info.sample_rate = config.sample_rate;
8053 config.offload_info.channel_mask = config.channel_mask;
8054 config.offload_info.format = config.format;
8055
jiabina84c3d32022-12-02 18:59:55 +00008056 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008057 if (status != NO_ERROR) {
8058 return nullptr;
8059 }
8060 }
8061
8062 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008063
baek.kim -61c20122022-07-27 10:05:32 +00008064 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8065 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8066
jiabinbce0c1d2020-10-05 11:20:18 -07008067 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8068 sp<AudioPolicyMix> policyMix;
8069 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8070 policyMix->setOutput(desc);
8071 desc->mPolicyMix = policyMix;
8072 } else {
8073 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8074 address.string());
8075 }
8076
baek.kim -61c20122022-07-27 10:05:32 +00008077 } else if (hasPrimaryOutput() && speaker != nullptr
8078 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008079 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8080 // no duplicated output for:
8081 // - direct outputs
8082 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008083 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008084 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8085
8086 //TODO: configure audio effect output stage here
8087
8088 // open a duplicating output thread for the new output and the primary output
8089 sp<SwAudioOutputDescriptor> dupOutputDesc =
8090 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8091 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8092 if (status == NO_ERROR) {
8093 // add duplicated output descriptor
8094 addOutput(duplicatedOutput, dupOutputDesc);
8095 } else {
8096 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8097 mPrimaryOutput->mIoHandle, output);
8098 desc->close();
8099 removeOutput(output);
8100 nextAudioPortGeneration();
8101 return nullptr;
8102 }
8103 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008104 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8105 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8106 mPrimaryOutput = desc;
8107 }
jiabinbce0c1d2020-10-05 11:20:18 -07008108 return desc;
8109}
8110
jiabinf1c73972022-04-14 16:28:52 -07008111status_t AudioPolicyManager::getDevicesForAttributes(
8112 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8113 // Devices are determined in the following precedence:
8114 //
8115 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8116 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8117 //
8118 // If no such dynamic policy then
8119 // 2) Devices containing an active client using setPreferredDevice
8120 // with same strategy as the attributes.
8121 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8122 //
8123 // If no corresponding active client with setPreferredDevice then
8124 // 3) Devices associated with the strategy determined by the attributes
8125 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8126 //
8127 // See related getOutputForAttrInt().
8128
8129 // check dynamic policies but only for primary descriptors (secondary not used for audible
8130 // audio routing, only used for duplication for playback capture)
8131 sp<AudioPolicyMix> policyMix;
8132 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02008133 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE, policyMix,
jiabinf1c73972022-04-14 16:28:52 -07008134 nullptr /* secondaryMixes */);
8135 if (status != OK) {
8136 return status;
8137 }
8138
8139 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8140 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8141 // as they are unaffected by device/stream volume
8142 // (per SwAudioOutputDescriptor::isFixedVolume()).
8143 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8144 ) {
8145 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8146 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8147 devices.add(deviceDesc);
8148 } else {
8149 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8150 // which selects setPreferredDevice if active. This means forVolume call
8151 // will take an active setPreferredDevice, if such exists.
8152
8153 devices = mEngine->getOutputDevicesForAttributes(
8154 attr, nullptr /* preferredDevice */, false /* fromCache */);
8155 }
8156
8157 if (forVolume) {
8158 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8159 // for single volume control in AudioService (such relationship should exist if
8160 // SPEAKER_SAFE is present).
8161 //
8162 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8163 DeviceVector speakerSafeDevices =
8164 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8165 if (!speakerSafeDevices.isEmpty()) {
8166 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8167 devices.remove(speakerSafeDevices);
8168 }
8169 }
8170
8171 return NO_ERROR;
8172}
8173
8174status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8175 AudioProfileVector& audioProfiles,
8176 uint32_t flags,
8177 bool isInput) {
8178 for (const auto& hwModule : mHwModules) {
8179 // the MSD module checks for different conditions
8180 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8181 continue;
8182 }
8183 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8184 : hwModule->getOutputProfiles();
8185 for (const auto& profile : ioProfiles) {
8186 if (!profile->areAllDevicesSupported(devices) ||
8187 !profile->isCompatibleProfileForFlags(
8188 flags, false /*exactMatchRequiredForInputFlags*/)) {
8189 continue;
8190 }
8191 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8192 }
8193 }
8194
8195 if (!isInput) {
8196 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8197 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8198 if (msdModule != nullptr) {
8199 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8200 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8201 for (const auto &profile: msdModule->getOutputProfiles()) {
8202 if (!profile->asAudioPort()->isDirectOutput()) {
8203 continue;
8204 }
8205 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8206 }
8207 } else {
8208 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8209 }
8210 }
8211 }
8212
8213 return NO_ERROR;
8214}
8215
jiabina84c3d32022-12-02 18:59:55 +00008216status_t AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8217 const audio_config_t *config,
8218 audio_output_flags_t flags,
8219 const char* caller) {
8220 closeOutput(outputDesc->mIoHandle);
8221 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8222 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8223 if (preferredOutput == nullptr) {
8224 ALOGE("%s failed to reopen output device=%d, caller=%s",
8225 __func__, outputDesc->devices()[0]->getId(), caller);
8226 return BAD_VALUE;
8227 }
8228 return NO_ERROR;
8229}
8230
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008231} // namespace android