blob: f08d4adda4916b08a74e59bf832d88f683d11484 [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) {
143 // TODO: b/211601178 Forward 'port' to Audio HAL via mHwModules. For now, only device_type,
144 // device_address and device_name are forwarded.
145 if (port.ext.getTag() != AudioPortExt::device) {
146 return BAD_VALUE;
147 }
148 audio_devices_t device_type;
149 std::string device_address;
150 if (status_t status = aidl2legacy_AudioDevice_audio_device(
151 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
152 status != OK) {
153 return status;
154 };
155 const char* device_name = port.name.c_str();
156 // connect/disconnect only 1 device at a time
157 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
158 return BAD_VALUE;
159
160 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
161 device_type, device_address.c_str(), device_name, encodedFormat,
162 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
163 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
164}
165
François Gaffie11d30102018-11-02 16:09:09 +0100166status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800167 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100168 const char* device_address,
169 const char* device_name,
170 audio_format_t encodedFormat) {
171 media::AudioPort aidlPort;
172 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
173 status == OK) {
174 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
175 } else {
176 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
177 return status;
178 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179}
Paul McLeane743a472015-01-28 11:07:31 -0800180
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
182 audio_policy_dev_state_t state)
183{
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700185 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700186 SortedVector <audio_io_handle_t> outputs;
187
François Gaffie11d30102018-11-02 16:09:09 +0100188 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 // save a copy of the opened output descriptors before any output is opened or closed
191 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
192 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700193 switch (state)
194 {
195 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800196 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700197 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100198 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700199 return INVALID_OPERATION;
200 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800201 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700202 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Eric Laurente552edb2014-03-10 17:42:56 -0700204 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200205 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700206 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700207 }
208
François Gaffie44481e72016-04-20 07:49:57 +0200209 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
210 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100211 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200212
François Gaffie11d30102018-11-02 16:09:09 +0100213 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
214 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200215
Francois Gaffie716e1432019-01-14 16:58:59 +0100216 mHwModules.cleanUpForDevice(device);
217
François Gaffie11d30102018-11-02 16:09:09 +0100218 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700219 return INVALID_OPERATION;
220 }
François Gaffie2110e042015-03-24 08:41:51 +0100221
jiabin1c4794b2020-05-05 10:08:05 -0700222 // Populate encapsulation information when a output device is connected.
223 device->setEncapsulationInfoFromHal(mpClientInterface);
224
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700225 // outputs should never be empty here
226 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
227 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100228 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800229
Eric Laurent3ae5f312015-02-03 17:12:08 -0800230 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700231 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700232 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700235 return INVALID_OPERATION;
236 }
237
François Gaffie11d30102018-11-02 16:09:09 +0100238 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700239
Paul McLeane743a472015-01-28 11:07:31 -0800240 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100241 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700242
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100244 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700245
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100246 mOutputs.clearSessionRoutesForDevice(device);
247
François Gaffie11d30102018-11-02 16:09:09 +0100248 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100249
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800250 // Reset active device codec
251 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
252
Kriti Dangef6be8f2020-11-05 11:58:19 +0100253 // remove device from mReportedFormatsMap cache
254 mReportedFormatsMap.erase(device);
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 } break;
257
258 default:
François Gaffie11d30102018-11-02 16:09:09 +0100259 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700260 return BAD_VALUE;
261 }
262
Eric Laurent736a1022019-03-27 18:28:46 -0700263 // Propagate device availability to Engine
264 setEngineDeviceConnectionState(device, state);
265
Eric Laurentae970022019-01-29 14:25:04 -0800266 // No need to evaluate playback routing when connecting a remote submix
267 // output device used by a dynamic policy of type recorder as no
268 // playback use case is affected.
269 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700270 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800271 for (audio_io_handle_t output : outputs) {
272 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800273 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
274 if (policyMix != nullptr
275 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700276 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800277 doCheckForDeviceAndOutputChanges = false;
278 break;
279 }
280 }
281 }
282
283 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700284 // outputs must be closed after checkOutputForAllStrategies() is executed
285 if (!outputs.isEmpty()) {
286 for (audio_io_handle_t output : outputs) {
287 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100288 // close unused outputs after device disconnection or direct outputs that have
289 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200290 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
291 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurent39095982021-08-24 18:29:27 +0200292 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200293 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700294 closeOutput(output);
295 }
Eric Laurente552edb2014-03-10 17:42:56 -0700296 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
298 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800301 };
302
303 if (doCheckForDeviceAndOutputChanges) {
304 checkForDeviceAndOutputChanges(checkCloseOutputs);
305 } else {
306 checkCloseOutputs();
307 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100308 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700309 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100310 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700311 const DeviceVector activeMediaDevices =
312 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700313 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700314 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530315 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
316 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100317 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700318 // do not force device change on duplicated output because if device is 0, it will
319 // also force a device 0 for the two outputs it is duplicated to which may override
320 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100321 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100322 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700323 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 // always force when disconnecting (a non-duplicated device)
325 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100326 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 }
jiabinbce0c1d2020-10-05 11:20:18 -0700328 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000329 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700330 desc->supportsDevicesForPlayback(activeMediaDevices)) {
331 // Reopen the output to query the dynamic profiles when there is not active
332 // clients or all active clients will be rerouted. Otherwise, set the flag
333 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
334 // can be reopened to query dynamic profiles when all clients are inactive.
335 if (areAllActiveTracksRerouted(desc)) {
336 outputsToReopen.push_back(mOutputs.keyAt(i));
337 } else {
338 desc->mPendingReopenToQueryProfiles = true;
339 }
340 }
341 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
342 // Clear the flag that previously set for re-querying profiles.
343 desc->mPendingReopenToQueryProfiles = false;
344 }
345 }
346 for (const auto& output : outputsToReopen) {
347 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
348 closeOutput(output);
349 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700350 }
351
Eric Laurentd60560a2015-04-10 11:31:20 -0700352 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100353 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700354 }
355
Eric Laurent72aa32f2014-05-30 18:51:48 -0700356 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700357 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700358 } // end if is output device
359
Eric Laurente552edb2014-03-10 17:42:56 -0700360 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700361 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100362 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700363 switch (state)
364 {
365 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700366 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100368 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700369 return INVALID_OPERATION;
370 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700371
372 if (mAvailableInputDevices.add(device) < 0) {
373 return NO_MEMORY;
374 }
375
François Gaffie44481e72016-04-20 07:49:57 +0200376 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
377 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100378 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200379
Eric Laurent0dd51852019-04-19 18:18:58 -0700380 if (checkInputsForDevice(device, state) != NO_ERROR) {
381 mAvailableInputDevices.remove(device);
382
François Gaffie11d30102018-11-02 16:09:09 +0100383 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100384
385 mHwModules.cleanUpForDevice(device);
386
Eric Laurentd4692962014-05-05 18:13:44 -0700387 return INVALID_OPERATION;
388 }
389
Eric Laurentd4692962014-05-05 18:13:44 -0700390 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700391
392 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700393 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700394 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700396 return INVALID_OPERATION;
397 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700398
François Gaffie11d30102018-11-02 16:09:09 +0100399 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700400
401 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100402 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700403
François Gaffie11d30102018-11-02 16:09:09 +0100404 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700405
406 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100407
408 // remove device from mReportedFormatsMap cache
409 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 default:
François Gaffie11d30102018-11-02 16:09:09 +0100413 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700414 return BAD_VALUE;
415 }
416
Eric Laurent736a1022019-03-27 18:28:46 -0700417 // Propagate device availability to Engine
418 setEngineDeviceConnectionState(device, state);
419
Eric Laurent0dd51852019-04-19 18:18:58 -0700420 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700421 // As the input device list can impact the output device selection, update
422 // getDeviceForStrategy() cache
423 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700424
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100425 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200426 // Reconnect Audio Source
427 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
428 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
429 checkAudioSourceForAttributes(attributes);
430 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700431 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100432 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700433 }
434
Eric Laurentb52c1522014-05-20 11:27:36 -0700435 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700436 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700437 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700438
François Gaffie11d30102018-11-02 16:09:09 +0100439 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700440 return BAD_VALUE;
441}
442
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100443status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
444 const char* device_name,
445 media::AudioPort* aidlPort) {
446 DeviceDescriptorBase devDescr(device, device_address);
447 devDescr.setName(device_name);
448 return devDescr.writeToParcelable(aidlPort);
449}
450
Eric Laurent736a1022019-03-27 18:28:46 -0700451void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
452 audio_policy_dev_state_t state) {
453
454 // the Engine does not have to know about remote submix devices used by dynamic audio policies
455 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
456 return;
457 }
458 mEngine->setDeviceConnectionState(device, state);
459}
460
461
Eric Laurente0720872014-03-11 09:30:41 -0700462audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100463 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700464{
Eric Laurent634b7142016-04-20 13:48:02 -0700465 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800466 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
467 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700468 (strlen(device_address) != 0)/*matchAddress*/);
469
470 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100471 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700472 device, device_address);
473 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
474 }
François Gaffie53615e22015-03-19 09:24:12 +0100475
Eric Laurent3a4311c2014-03-17 12:00:47 -0700476 DeviceVector *deviceVector;
477
Eric Laurente552edb2014-03-10 17:42:56 -0700478 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700479 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700480 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700481 deviceVector = &mAvailableInputDevices;
482 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100483 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700484 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700485 }
Eric Laurent634b7142016-04-20 13:48:02 -0700486
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800487 return (deviceVector->getDevice(
488 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700489 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800490}
491
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800492status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
493 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800494 const char *device_name,
495 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800496{
497 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700498 String8 reply;
499 AudioParameter param;
500 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800502 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
503 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800505 // connect/disconnect only 1 device at a time
506 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
507
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700509 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800511 // Nothing to do: device is not connected
512 return NO_ERROR;
513 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800514 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800515
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700516 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 // configure codecs.
518 // Handle two specific cases by sending a set parameter to
519 // configure A2DP codecs. No need to toggle device state.
520 // Case 1: A2DP active device switches from primary to primary
521 // module
522 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200523 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700524 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
526 if (availablePrimaryOutputDevices().contains(devDesc) &&
527 (module != 0 && module->getHandle() == primaryHandle)) {
528 reply = mpClientInterface->getParameters(
529 AUDIO_IO_HANDLE_NONE,
530 String8(AudioParameter::keyReconfigA2dpSupported));
531 AudioParameter repliedParameters(reply);
532 repliedParameters.getInt(
533 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
534 if (isReconfigA2dpSupported) {
535 const String8 key(AudioParameter::keyReconfigA2dp);
536 param.add(key, String8("true"));
537 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
538 devDesc->setEncodedFormat(encodedFormat);
539 return NO_ERROR;
540 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700541 }
542 }
cnx421bd2dcc42020-07-11 14:58:44 +0800543 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
544 for (size_t i = 0; i < mOutputs.size(); i++) {
545 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
546 // mute media strategies and delay device switch by the largest
547 // This avoid sending the music tail into the earpiece or headset.
548 setStrategyMute(musicStrategy, true, desc);
549 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
550 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
551 nullptr, true /*fromCache*/).types());
552 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800553 // Toggle the device state: UNAVAILABLE -> AVAILABLE
554 // This will force reading again the device configuration
555 status = setDeviceConnectionState(device,
556 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800557 device_address, device_name,
558 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800559 if (status != NO_ERROR) {
560 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
561 status);
562 return status;
563 }
564
565 status = setDeviceConnectionState(device,
566 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800567 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 if (status != NO_ERROR) {
569 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
570 status);
571 return status;
572 }
573
574 return NO_ERROR;
575}
576
Pattydd807582021-11-04 21:01:03 +0800577status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
578 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800579{
Pattydd807582021-11-04 21:01:03 +0800580 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800581 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800582 std::unordered_set<audio_format_t> formatSet;
583 sp<HwModule> primaryModule =
584 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700585 if (primaryModule == nullptr) {
586 ALOGE("%s() unable to get primary module", __func__);
587 return NO_INIT;
588 }
Pattydd807582021-11-04 21:01:03 +0800589
590 DeviceTypeSet audioDeviceSet;
591
592 switch(device) {
593 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
594 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
595 break;
596 case AUDIO_DEVICE_OUT_BLE_HEADSET:
597 audioDeviceSet = getAudioDeviceOutAllBleSet();
598 break;
599 default:
600 ALOGE("%s() device type 0x%08x not supported", __func__, device);
601 return BAD_VALUE;
602 }
603
jiabin9a3361e2019-10-01 09:38:30 -0700604 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800605 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800606 for (const auto& device : declaredDevices) {
607 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800608 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800609 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800610 return status;
611}
612
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100613DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
614{
615 DeviceVector rxSinkdevices{};
616 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
617 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
618 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
619 auto rxSinkDevice = rxSinkdevices.itemAt(0);
620 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
621 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
622 // retrieve Rx Source device descriptor
623 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
624 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
625
626 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
627 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
628 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
629 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
630 return DeviceVector(rxSinkDevice);
631 }
632 }
633 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
634 // the device returned is not necessarily reachable via this output
635 // (filter later by setOutputDevices())
636 return getNewOutputDevices(mPrimaryOutput, fromCache);
637}
638
639status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
640{
641 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
642 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
643 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
644 }
645 return INVALID_OPERATION;
646}
647
648status_t AudioPolicyManager::updateCallRoutingInternal(
649 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700650{
651 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100652 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700653 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700654 if(!hasPrimaryOutput() ||
655 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100656 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700657 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100658 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100659
Francois Gaffie716e1432019-01-14 16:58:59 +0100660 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100661 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100663
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100664 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100665 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700666
Francois Gaffie601801d2021-06-22 13:27:39 +0200667 disconnectTelephonyAudioSource(mCallRxSourceClient);
668 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700669
François Gaffie9eb18552018-11-05 10:33:26 +0100670 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700671 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100672 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700673 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100674 // retrieve Rx Source and Tx Sink device descriptors
675 sp<DeviceDescriptor> rxSourceDevice =
676 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
677 String8(),
678 AUDIO_FORMAT_DEFAULT);
679 sp<DeviceDescriptor> txSinkDevice =
680 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
681 String8(),
682 AUDIO_FORMAT_DEFAULT);
683
684 // RX and TX Telephony device are declared by Primary Audio HAL
685 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
686 (telephonyRxModule->getHalVersionMajor() >= 3)) {
687 if (rxSourceDevice == 0 || txSinkDevice == 0) {
688 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100689 ALOGE("%s() no telephony Tx and/or RX device", __func__);
690 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100691 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100692 // createAudioPatchInternal now supports both HW / SW bridging
693 createRxPatch = true;
694 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100695 } else {
696 // If the RX device is on the primary HW module, then use legacy routing method for
697 // voice calls via setOutputDevice() on primary output.
698 // Otherwise, create two audio patches for TX and RX path.
699 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
700 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700701 // If the TX device is also on the primary HW module, setOutputDevice() will take care
702 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100703 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
704 (txSinkDevice != 0);
705 }
706 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
707 // Otherwise, create two audio patches for TX and RX path.
708 if (!createRxPatch) {
709 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700710 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200711 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800712 // If the TX device is on the primary HW module but RX device is
713 // on other HW module, SinkMetaData of telephony input should handle it
714 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700715 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700716 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100717 // terminate active capture if on the same HW module as the call TX source device
718 // FIXME: would be better to refine to only inputs whose profile connects to the
719 // call TX device but this information is not in the audio patch and logic here must be
720 // symmetric to the one in startInput()
721 for (const auto& activeDesc : mInputs.getActiveInputs()) {
722 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
723 closeActiveClients(activeDesc);
724 }
725 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200726 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800727 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100728 if (waitMs != nullptr) {
729 *waitMs = muteWaitMs;
730 }
731 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800732}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700733
Mikhail Naganov100f0122018-11-29 11:22:16 -0800734bool AudioPolicyManager::isDeviceOfModule(
735 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
736 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
737 if (module != 0) {
738 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
739 .indexOf(devDesc) != NAME_NOT_FOUND
740 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
741 .indexOf(devDesc) != NAME_NOT_FOUND;
742 }
743 return false;
744}
745
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200746void AudioPolicyManager::connectTelephonyRxAudioSource()
747{
Francois Gaffie601801d2021-06-22 13:27:39 +0200748 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200749 const struct audio_port_config source = {
750 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
751 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
752 };
753 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200754 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
755 ALOGE_IF(mCallRxSourceClient == nullptr,
756 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200757}
758
Francois Gaffie601801d2021-06-22 13:27:39 +0200759void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200760{
Francois Gaffie601801d2021-06-22 13:27:39 +0200761 if (clientDesc == nullptr) {
762 return;
763 }
764 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
765 "%s error stopping audio source", __func__);
766 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200767}
768
769void AudioPolicyManager::connectTelephonyTxAudioSource(
770 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
771 uint32_t delayMs)
772{
Francois Gaffie601801d2021-06-22 13:27:39 +0200773 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200774 if (srcDevice == nullptr || sinkDevice == nullptr) {
775 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
776 return;
777 }
778 PatchBuilder patchBuilder;
779 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
780 ALOGV("%s between source %s and sink %s", __func__,
781 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200782 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200783 const audio_attributes_t aa = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
784 struct audio_port_config source = {};
785 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200786 mCallTxSourceClient = new InternalSourceClientDescriptor(
787 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200788 mCommunnicationStrategy, toVolumeSource(aa));
789 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
790 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200791 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
792 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200793 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
794 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200795 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200796 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200797}
798
Eric Laurente0720872014-03-11 09:30:41 -0700799void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700800{
801 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100802 // store previous phone state for management of sonification strategy below
803 int oldState = mEngine->getPhoneState();
804
805 if (mEngine->setPhoneState(state) != NO_ERROR) {
806 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700807 return;
808 }
François Gaffie2110e042015-03-24 08:41:51 +0100809 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700810 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700811 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700812 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800813 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700814 }
815
François Gaffie2110e042015-03-24 08:41:51 +0100816 /**
817 * Switching to or from incall state or switching between telephony and VoIP lead to force
818 * routing command.
819 */
Eric Laurent74b71512019-11-06 17:21:57 -0800820 bool force = ((isStateInCall(oldState) != isStateInCall(state))
821 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700822
823 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700824 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700825
Eric Laurente552edb2014-03-10 17:42:56 -0700826 int delayMs = 0;
827 if (isStateInCall(state)) {
828 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100829 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
830 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700831 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700832 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700833 // mute media and sonification strategies and delay device switch by the largest
834 // latency of any output where either strategy is active.
835 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100836 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
837 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
838 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700839 (delayMs < (int)desc->latency()*2)) {
840 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700841 }
François Gaffiec005e562018-11-06 15:04:49 +0100842 setStrategyMute(musicStrategy, true, desc);
843 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
844 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
845 nullptr, true /*fromCache*/).types());
846 setStrategyMute(sonificationStrategy, true, desc);
847 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
848 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
849 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700850 }
851 }
852
Eric Laurent87ffa392015-05-22 10:32:38 -0700853 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700854 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100855 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700856 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100857 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
858 // force routing command to audio hardware when ending call
859 // even if no device change is needed
860 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
861 rxDevices = mPrimaryOutput->devices();
862 }
863 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200864 disconnectTelephonyAudioSource(mCallRxSourceClient);
865 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100866 }
François Gaffie11d30102018-11-02 16:09:09 +0100867 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700868 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700869 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700870
871 // reevaluate routing on all outputs in case tracks have been started during the call
872 for (size_t i = 0; i < mOutputs.size(); i++) {
873 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100874 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200875 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
876 bool forceRouting = !newDevices.isEmpty();
877 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
878 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700879 }
880 }
881
Eric Laurente552edb2014-03-10 17:42:56 -0700882 if (isStateInCall(state)) {
883 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700884 // force reevaluating accessibility routing when call starts
885 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700886 }
887
888 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100889 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
890 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700891}
892
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700893audio_mode_t AudioPolicyManager::getPhoneState() {
894 return mEngine->getPhoneState();
895}
896
Eric Laurente0720872014-03-11 09:30:41 -0700897void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100898 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700899{
François Gaffie2110e042015-03-24 08:41:51 +0100900 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700901 if (config == mEngine->getForceUse(usage)) {
902 return;
903 }
Eric Laurente552edb2014-03-10 17:42:56 -0700904
François Gaffie2110e042015-03-24 08:41:51 +0100905 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
906 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
907 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700908 }
François Gaffie2110e042015-03-24 08:41:51 +0100909 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
910 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
911 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700912
913 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700914 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800915
Eric Laurent22fcda22019-05-17 16:28:47 -0700916 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
917 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
918 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
919 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
920 }
921
Eric Laurentdc462862016-07-19 12:29:53 -0700922 //FIXME: workaround for truncated touch sounds
923 // to be removed when the problem is handled by system UI
924 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700925 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
926 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
927 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700928
929 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100930 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700931}
932
Eric Laurente0720872014-03-11 09:30:41 -0700933void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700934{
935 ALOGV("setSystemProperty() property %s, value %s", property, value);
936}
937
Dorin Drimusecc9f422022-03-09 17:57:40 +0100938// Find an MSD output profile compatible with the parameters passed.
939// When "directOnly" is set, restrict search to profiles for direct outputs.
940sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
941 const DeviceVector& devices,
942 uint32_t samplingRate,
943 audio_format_t format,
944 audio_channel_mask_t channelMask,
945 audio_output_flags_t flags,
946 bool directOnly)
947{
948 flags = getRelevantFlags(flags, directOnly);
949
950 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
951 if (msdModule != nullptr) {
952 // for the msd module check if there are patches to the output devices
953 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
954 HwModuleCollection modules;
955 modules.add(msdModule);
956 return searchCompatibleProfileHwModules(
957 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
958 flags, directOnly);
959 }
960 }
961 return nullptr;
962}
963
Michael Chana94fbb22018-04-24 14:31:19 +1000964// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
965// search to profiles for direct outputs.
966sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100967 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000968 uint32_t samplingRate,
969 audio_format_t format,
970 audio_channel_mask_t channelMask,
971 audio_output_flags_t flags,
972 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700973{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100974 flags = getRelevantFlags(flags, directOnly);
975
976 return searchCompatibleProfileHwModules(
977 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
978}
979
980audio_output_flags_t AudioPolicyManager::getRelevantFlags (
981 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000982 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100983 // only retain flags that will drive the direct output profile selection
984 // if explicitly requested
985 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000986 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100987 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
988 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +1000989 }
Dorin Drimusecc9f422022-03-09 17:57:40 +0100990 return flags;
991}
Eric Laurent861a6282015-05-18 15:40:16 -0700992
Dorin Drimusecc9f422022-03-09 17:57:40 +0100993sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
994 const HwModuleCollection& hwModules,
995 const DeviceVector& devices,
996 uint32_t samplingRate,
997 audio_format_t format,
998 audio_channel_mask_t channelMask,
999 audio_output_flags_t flags,
1000 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001001 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001002 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001003 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001004 if (!curProfile->isCompatibleProfile(devices,
1005 samplingRate, NULL /*updatedSamplingRate*/,
1006 format, NULL /*updatedFormat*/,
1007 channelMask, NULL /*updatedChannelMask*/,
1008 flags)) {
1009 continue;
1010 }
1011 // reject profiles not corresponding to a device currently available
1012 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1013 continue;
1014 }
1015 // reject profiles if connected device does not support codec
1016 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1017 continue;
1018 }
1019 if (!directOnly) {
1020 return curProfile;
1021 }
1022
1023 // when searching for direct outputs, if several profiles are compatible, give priority
1024 // to one with offload capability
1025 if (profile != 0 &&
1026 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001027 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001028 }
1029 profile = curProfile;
1030 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1031 break;
1032 }
Eric Laurente552edb2014-03-10 17:42:56 -07001033 }
1034 }
Eric Laurent861a6282015-05-18 15:40:16 -07001035 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001036}
1037
Eric Laurentfa0f6742021-08-17 18:39:44 +02001038sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001039 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001040{
1041 for (const auto& hwModule : mHwModules) {
1042 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001043 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001044 continue;
1045 }
1046 // reject profiles not corresponding to a device currently available
1047 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1048 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1049 continue;
1050 }
1051 if (!devices.empty()) {
1052 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1053 != devices.size()) {
1054 continue;
1055 }
1056 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001057 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1058 return curProfile;
1059 }
1060 }
1061 return nullptr;
1062}
1063
Eric Laurentf4e63452017-11-06 19:31:46 +00001064audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001065{
François Gaffiec005e562018-11-06 15:04:49 +01001066 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001067
1068 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1069 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1070 // format, flags, etc. This may result in some discrepancy for functions that utilize
1071 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1072 // and AudioSystem::getOutputSamplingRate().
1073
François Gaffie11d30102018-11-02 16:09:09 +01001074 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001075 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001076
François Gaffie11d30102018-11-02 16:09:09 +01001077 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1078 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001079 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001080}
1081
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001082status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1083 const audio_attributes_t *srcAttr,
1084 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001085{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001086 if (srcAttr != NULL) {
1087 if (!isValidAttributes(srcAttr)) {
1088 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1089 __func__,
1090 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1091 srcAttr->tags);
1092 return BAD_VALUE;
1093 }
1094 *dstAttr = *srcAttr;
1095 } else {
1096 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1097 ALOGE("%s: invalid stream type", __func__);
1098 return BAD_VALUE;
1099 }
François Gaffiec005e562018-11-06 15:04:49 +01001100 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001101 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001102
1103 // Only honor audibility enforced when required. The client will be
1104 // forced to reconnect if the forced usage changes.
1105 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001106 dstAttr->flags = static_cast<audio_flags_mask_t>(
1107 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001108 }
1109
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001110 return NO_ERROR;
1111}
1112
Kevin Rocard153f92d2018-12-18 18:33:28 -08001113status_t AudioPolicyManager::getOutputForAttrInt(
1114 audio_attributes_t *resultAttr,
1115 audio_io_handle_t *output,
1116 audio_session_t session,
1117 const audio_attributes_t *attr,
1118 audio_stream_type_t *stream,
1119 uid_t uid,
1120 const audio_config_t *config,
1121 audio_output_flags_t *flags,
1122 audio_port_handle_t *selectedDeviceId,
1123 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001124 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001125 output_type_t *outputType,
1126 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001127{
François Gaffiec005e562018-11-06 15:04:49 +01001128 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001129 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001130 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001131 const sp<DeviceDescriptor> requestedDevice =
1132 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1133
Eric Laurent8a1095a2019-11-08 14:44:16 -08001134 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001135 *isSpatialized = false;
1136
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001137 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1138 if (status != NO_ERROR) {
1139 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001140 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001141 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001142 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001143 }
François Gaffiec005e562018-11-06 15:04:49 +01001144 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001145
François Gaffiec005e562018-11-06 15:04:49 +01001146 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1147 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001148
Kevin Rocard153f92d2018-12-18 18:33:28 -08001149 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1150 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1151 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001152 sp<AudioPolicyMix> primaryMix;
1153 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001154 if (status != OK) {
1155 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001156 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001157
Kevin Rocard153f92d2018-12-18 18:33:28 -08001158 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001159 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001160
1161 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001162 if ((usePrimaryOutputFromPolicyMixes
1163 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001164 && !audio_is_linear_pcm(config->format)) {
1165 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001166 return BAD_VALUE;
1167 }
1168 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001169 sp<DeviceDescriptor> deviceDesc =
1170 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1171 primaryMix->mDeviceAddress,
1172 AUDIO_FORMAT_DEFAULT);
1173 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001174 if (deviceDesc != nullptr
1175 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001176 audio_io_handle_t newOutput;
1177 status = openDirectOutput(
1178 *stream, session, config,
1179 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1180 DeviceVector(deviceDesc), &newOutput);
1181 if (status != NO_ERROR) {
1182 policyDesc = nullptr;
1183 } else {
1184 policyDesc = mOutputs.valueFor(newOutput);
1185 primaryMix->setOutput(policyDesc);
1186 }
1187 }
1188 if (policyDesc != nullptr) {
1189 policyDesc->mPolicyMix = primaryMix;
1190 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001191 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001192
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001193 ALOGV("getOutputForAttr() returns output %d", *output);
1194 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1195 *outputType = API_OUT_MIX_PLAYBACK;
1196 } else {
1197 *outputType = API_OUTPUT_LEGACY;
1198 }
1199 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001200 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001201 }
François Gaffiec005e562018-11-06 15:04:49 +01001202 // Virtual sources must always be dynamicaly or explicitly routed
1203 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1204 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1205 return BAD_VALUE;
1206 }
1207 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1208 // in order to let the choice of the order to future vendor engine
1209 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001210
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001211 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001212 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001213 }
1214
Nadav Barb2f18162018-07-18 13:01:53 +03001215 // Set incall music only if device was explicitly set, and fallback to the device which is
1216 // chosen by the engine if not.
1217 // FIXME: provide a more generic approach which is not device specific and move this back
1218 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001219 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001220 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001221 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001222 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001223 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001224 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001225 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001226 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001227 }
1228 }
1229
François Gaffiec005e562018-11-06 15:04:49 +01001230 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1231 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1232 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001233
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001234 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001235 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001236 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001237 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001238 ALOGV("%s() Using MSD devices %s instead of devices %s",
1239 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001240 } else {
1241 *output = AUDIO_IO_HANDLE_NONE;
1242 }
1243 }
1244 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001245 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001246 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001247 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001248 if (*output == AUDIO_IO_HANDLE_NONE) {
1249 return INVALID_OPERATION;
1250 }
Paul McLeanaa981192015-03-21 09:55:15 -07001251
François Gaffiec005e562018-11-06 15:04:49 +01001252 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001253 for (auto &outputDevice : outputDevices) {
1254 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1255 *selectedDeviceId = outputDevice->getId();
1256 break;
1257 }
1258 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001259
Eric Laurent8a1095a2019-11-08 14:44:16 -08001260 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1261 *outputType = API_OUTPUT_TELEPHONY_TX;
1262 } else {
1263 *outputType = API_OUTPUT_LEGACY;
1264 }
1265
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001266 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1267
1268 return NO_ERROR;
1269}
1270
1271status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1272 audio_io_handle_t *output,
1273 audio_session_t session,
1274 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001275 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001276 const audio_config_t *config,
1277 audio_output_flags_t *flags,
1278 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001279 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001280 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001281 output_type_t *outputType,
1282 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001283{
1284 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1285 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1286 return INVALID_OPERATION;
1287 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001288 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001289 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001290 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001291 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001292 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001293 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001294 const sp<DeviceDescriptor> requestedDevice =
1295 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1296
1297 // Prevent from storing invalid requested device id in clients
1298 const audio_port_handle_t sanitizedRequestedPortId =
1299 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1300 *selectedDeviceId = sanitizedRequestedPortId;
1301
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001302 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001303 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001304 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001305 if (status != NO_ERROR) {
1306 return status;
1307 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001308 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001309 if (secondaryOutputs != nullptr) {
1310 for (auto &secondaryMix : secondaryMixes) {
1311 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1312 if (outputDesc != nullptr &&
1313 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1314 secondaryOutputs->push_back(outputDesc->mIoHandle);
1315 weakSecondaryOutputDescs.push_back(outputDesc);
1316 }
1317 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001318 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001319
Eric Laurent8fc147b2018-07-22 19:13:55 -07001320 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001321 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001322 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001323 };
jiabin4ef93452019-09-10 14:29:54 -07001324 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001325
Eric Laurentc209fe42020-06-05 18:11:23 -07001326 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001327 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001328 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001329 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001330 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001331 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001332 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001333 std::move(weakSecondaryOutputDescs),
1334 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001335 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001336
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001337 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1338 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001339
Eric Laurente83b55d2014-11-14 10:06:21 -08001340 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001341}
1342
Eric Laurentc529cf62020-04-17 18:19:10 -07001343status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1344 audio_session_t session,
1345 const audio_config_t *config,
1346 audio_output_flags_t flags,
1347 const DeviceVector &devices,
1348 audio_io_handle_t *output) {
1349
1350 *output = AUDIO_IO_HANDLE_NONE;
1351
1352 // skip direct output selection if the request can obviously be attached to a mixed output
1353 // and not explicitly requested
1354 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1355 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1356 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1357 return NAME_NOT_FOUND;
1358 }
1359
1360 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1361 // This prevents creating an offloaded track and tearing it down immediately after start
1362 // when audioflinger detects there is an active non offloadable effect.
1363 // FIXME: We should check the audio session here but we do not have it in this context.
1364 // This may prevent offloading in rare situations where effects are left active by apps
1365 // in the background.
1366 sp<IOProfile> profile;
1367 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1368 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1369 profile = getProfileForOutput(
1370 devices, config->sample_rate, config->format, config->channel_mask,
1371 flags, true /* directOnly */);
1372 }
1373
1374 if (profile == nullptr) {
1375 return NAME_NOT_FOUND;
1376 }
1377
1378 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1379 for (size_t i = 0; i < mOutputs.size(); i++) {
1380 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1381 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1382 // reuse direct output if currently open by the same client
1383 // and configured with same parameters
1384 if ((config->sample_rate == desc->getSamplingRate()) &&
1385 (config->format == desc->getFormat()) &&
1386 (config->channel_mask == desc->getChannelMask()) &&
1387 (session == desc->mDirectClientSession)) {
1388 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001389 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001390 mOutputs.keyAt(i), session);
1391 *output = mOutputs.keyAt(i);
1392 return NO_ERROR;
1393 }
1394 }
1395 }
1396
1397 if (!profile->canOpenNewIo()) {
1398 return NAME_NOT_FOUND;
1399 }
1400
1401 sp<SwAudioOutputDescriptor> outputDesc =
1402 new SwAudioOutputDescriptor(profile, mpClientInterface);
1403
Michael Chan6fb34492020-12-08 15:44:49 +11001404 // An MSD patch may be using the only output stream that can service this request. Release
1405 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001406 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001407
Eric Laurentf1f22e72021-07-13 14:04:14 +02001408 status_t status =
1409 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001410
1411 // only accept an output with the requested parameters
1412 if (status != NO_ERROR ||
1413 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1414 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1415 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1416 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1417 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1418 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1419 config->channel_mask, outputDesc->getChannelMask());
1420 if (*output != AUDIO_IO_HANDLE_NONE) {
1421 outputDesc->close();
1422 }
1423 // fall back to mixer output if possible when the direct output could not be open
1424 if (audio_is_linear_pcm(config->format) &&
1425 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1426 return NAME_NOT_FOUND;
1427 }
1428 *output = AUDIO_IO_HANDLE_NONE;
1429 return BAD_VALUE;
1430 }
1431 outputDesc->mDirectOpenCount = 1;
1432 outputDesc->mDirectClientSession = session;
1433
1434 addOutput(*output, outputDesc);
1435 mPreviousOutputs = mOutputs;
1436 ALOGV("%s returns new direct output %d", __func__, *output);
1437 mpClientInterface->onAudioPortListUpdate();
1438 return NO_ERROR;
1439}
1440
François Gaffie11d30102018-11-02 16:09:09 +01001441audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1442 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001443 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001444 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001445 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001446 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001447 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001448 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001449{
Andy Hungc88b0642018-04-27 15:42:35 -07001450 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001451
jiabine375d412019-02-26 12:54:53 -08001452 // Discard haptic channel mask when forcing muting haptic channels.
1453 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001454 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1455 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001456
Eric Laurente552edb2014-03-10 17:42:56 -07001457 // open a direct output if required by specified parameters
1458 //force direct flag if offload flag is set: offloading implies a direct output stream
1459 // and all common behaviors are driven by checking only the direct flag
1460 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001461 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1462 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001463 }
Nadav Bar766fb022018-01-07 12:18:03 +02001464 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1465 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001466 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001467
1468 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1469
Eric Laurente83b55d2014-11-14 10:06:21 -08001470 // only allow deep buffering for music stream type
1471 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001472 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001473 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001474 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001475 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1476 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001477 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001478 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001479 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001480 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001481 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001482 audio_is_linear_pcm(config->format) &&
1483 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001484 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001485 AUDIO_OUTPUT_FLAG_DIRECT);
1486 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001487 }
Eric Laurente552edb2014-03-10 17:42:56 -07001488
Carter Hsua3abb402021-10-26 11:11:20 +08001489 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1490 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1491 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1492 }
1493
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001494 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001495 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001496 && canBeSpatializedInt(attr, config,
1497 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001498 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001499 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001500 }
1501
Eric Laurentc529cf62020-04-17 18:19:10 -07001502 audio_config_t directConfig = *config;
1503 directConfig.channel_mask = channelMask;
1504 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1505 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001506 return output;
1507 }
1508
Eric Laurent14cbfca2016-03-17 09:42:16 -07001509 // A request for HW A/V sync cannot fallback to a mixed output because time
1510 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001511 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001512 return AUDIO_IO_HANDLE_NONE;
1513 }
1514
Eric Laurente552edb2014-03-10 17:42:56 -07001515 // ignoring channel mask due to downmix capability in mixer
1516
1517 // open a non direct output
1518
1519 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001520 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001521 // get which output is suitable for the specified stream. The actual
1522 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001523 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001524
Eric Laurent8838a382014-09-08 16:44:28 -07001525 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001526 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001527 output = selectOutput(
1528 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001529 }
François Gaffie11d30102018-11-02 16:09:09 +01001530 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001531 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001532 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001533
Eric Laurente552edb2014-03-10 17:42:56 -07001534 return output;
1535}
1536
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001537sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001538 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1539 mAvailableInputDevices);
1540 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1541}
1542
1543DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1544 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1545 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001546}
1547
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001548const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001549 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001550 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1551 if (msdModule != 0) {
1552 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1553 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1554 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1555 const struct audio_port_config *source = &patch->mPatch.sources[j];
1556 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1557 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001558 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001559 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001560 }
1561 }
1562 }
1563 return msdPatches;
1564}
1565
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001566bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1567 ssize_t index = mAudioPatches.indexOfKey(handle);
1568 if (index < 0) {
1569 return false;
1570 }
1571 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1572 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1573 if (msdModule == nullptr) {
1574 return false;
1575 }
1576 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1577 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1578 return true;
1579 }
1580 index = getMsdOutputPatches().indexOfKey(handle);
1581 if (index < 0) {
1582 return false;
1583 }
1584 return true;
1585}
1586
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001587status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1588 const InputProfileCollection &inputProfiles,
1589 const OutputProfileCollection &outputProfiles,
1590 const sp<DeviceDescriptor> &sourceDevice,
1591 const sp<DeviceDescriptor> &sinkDevice,
1592 AudioProfileVector& sourceProfiles,
1593 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001594 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001595 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001596 return NO_INIT;
1597 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001598 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001599 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001600 return NO_INIT;
1601 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001602 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001603 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1604 inProfile->supportsDevice(sourceDevice)) {
1605 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001606 }
1607 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001608 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001609 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001610 outProfile->supportsDevice(sinkDevice)) {
1611 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001612 }
1613 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001614 return NO_ERROR;
1615}
1616
1617status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1618 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1619 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1620{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001621 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001622 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1623 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1624 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001625 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001626 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1627 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001628 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001629 }
1630 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1631 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1632 sinkConfig->format = bestSinkConfig.format;
1633 // For encoded streams force direct flag to prevent downstream mixing.
1634 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1635 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001636 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1637 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001638 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001639 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1640 // raw and IEC61937 framed streams.
1641 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1642 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1643 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001644 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1645 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1646 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1647 sourceConfig->format = bestSinkConfig.format;
1648 // Copy input stream directly without any processing (e.g. resampling).
1649 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1650 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1651 if (hwAvSync) {
1652 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1653 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1654 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1655 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1656 }
1657 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1658 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1659 sinkConfig->config_mask |= config_mask;
1660 sourceConfig->config_mask |= config_mask;
1661 return NO_ERROR;
1662}
1663
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001664PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1665 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001666{
1667 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001668 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1669 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1670 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1671 if (deviceModule == nullptr) {
1672 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1673 return patchBuilder;
1674 }
1675 const InputProfileCollection inputProfiles = msdIsSource ?
1676 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1677 const OutputProfileCollection outputProfiles = msdIsSource ?
1678 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1679
1680 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1681 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1682 device : getMsdAudioOutDevices().itemAt(0);
1683 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1684
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001685 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1686 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001687 AudioProfileVector sourceProfiles;
1688 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001689 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1690 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001691 for (auto hwAvSync : { true, false }) {
1692 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1693 sourceProfiles, sinkProfiles) != NO_ERROR) {
1694 continue;
1695 }
1696 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1697 &sinkConfig) == NO_ERROR) {
1698 // Found a matching config. Re-create PatchBuilder with this config.
1699 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1700 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001701 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001702 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001703 " supporting PCM format conversion.", __func__);
1704 return patchBuilder;
1705}
1706
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001707status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001708 DeviceVector devices;
1709 if (outputDevices != nullptr && outputDevices->size() > 0) {
1710 devices.add(*outputDevices);
1711 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001712 // Use media strategy for unspecified output device. This should only
1713 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1714 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001715 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001716 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001717 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001718 }
Michael Chan6fb34492020-12-08 15:44:49 +11001719 std::vector<PatchBuilder> patchesToCreate;
1720 for (auto i = 0u; i < devices.size(); ++i) {
1721 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001722 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001723 }
1724 // Retain only the MSD patches associated with outputDevices request.
1725 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001726 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001727 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1728 auto retainedPatch = false;
1729 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1730 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1731 patchesToRemove.removeItemsAt(i);
1732 retainedPatch = true;
1733 break;
1734 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001735 }
Michael Chan6fb34492020-12-08 15:44:49 +11001736 if (retainedPatch) {
1737 it = patchesToCreate.erase(it);
1738 continue;
1739 }
1740 ++it;
1741 }
1742 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1743 return NO_ERROR;
1744 }
1745 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1746 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001747 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001748 }
Michael Chan6fb34492020-12-08 15:44:49 +11001749 status_t status = NO_ERROR;
1750 for (const auto &p : patchesToCreate) {
1751 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1752 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1753 char message[256];
1754 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1755 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1756 currStatus == NO_ERROR ? "Success" : "Error",
1757 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1758 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1759 if (currStatus == NO_ERROR) {
1760 ALOGD("%s", message);
1761 } else {
1762 ALOGE("%s", message);
1763 if (status == NO_ERROR) {
1764 status = currStatus;
1765 }
1766 }
1767 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001768 return status;
1769}
1770
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001771void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1772 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001773 for (size_t i = 0; i < msdPatches.size(); i++) {
1774 const auto& patch = msdPatches[i];
1775 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1776 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1777 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1778 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1779 releaseAudioPatch(patch->getHandle(), mUidCached);
1780 break;
1781 }
1782 }
1783 }
1784}
1785
Dorin Drimus94d94412022-02-02 09:05:02 +01001786bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1787 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1788 AudioPatchCollection msdPatches = getMsdOutputPatches();
1789 for (size_t i = 0; i < msdPatches.size(); i++) {
1790 const auto& patch = msdPatches[i];
1791 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1792 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1793 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1794 const auto& foundDevice = devicesToCheck.getDevice(
1795 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1796 if (foundDevice != nullptr) {
1797 devicesToCheck.remove(foundDevice);
1798 if (devicesToCheck.isEmpty()) {
1799 return true;
1800 }
1801 }
1802 }
1803 }
1804 }
1805 return false;
1806}
1807
Eric Laurente0720872014-03-11 09:30:41 -07001808audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001809 audio_output_flags_t flags,
1810 audio_format_t format,
1811 audio_channel_mask_t channelMask,
1812 uint32_t samplingRate,
1813 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001814{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001815 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1816 "%s called with format %#x", __func__, format);
1817
jiabinebb6af42020-06-09 17:31:17 -07001818 // Return the output that haptic-generating attached to when 1) session id is specified,
1819 // 2) haptic-generating effect exists for given session id and 3) the output that
1820 // haptic-generating effect attached to is in given outputs.
1821 if (sessionId != AUDIO_SESSION_NONE) {
1822 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1823 sessionId, FX_IID_HAPTICGENERATOR);
1824 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1825 return hapticGeneratingOutput;
1826 }
1827 }
1828
Eric Laurent16c66dd2019-05-01 17:54:10 -07001829 // Flags disqualifying an output: the match must happen before calling selectOutput()
1830 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1831 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1832
1833 // Flags expressing a functional request: must be honored in priority over
1834 // other criteria
1835 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1836 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001837 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1838 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001839 // Flags expressing a performance request: have lower priority than serving
1840 // requested sampling rate or channel mask
1841 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1842 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1843 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1844
1845 const audio_output_flags_t functionalFlags =
1846 (audio_output_flags_t)(flags & kFunctionalFlags);
1847 const audio_output_flags_t performanceFlags =
1848 (audio_output_flags_t)(flags & kPerformanceFlags);
1849
1850 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1851
Eric Laurente552edb2014-03-10 17:42:56 -07001852 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001853 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001854 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001855 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001856 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001857 // with tiebreak preferring the minimum number of extra functional flags
1858 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001859 // 3: the output supporting the exact channel mask
1860 // 4: the output with a higher channel count than requested
1861 // 5: the output with a higher sampling rate than requested
1862 // 6: the output with the highest number of requested performance flags
1863 // 7: the output with the bit depth the closest to the requested one
1864 // 8: the primary output
1865 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001866
Eric Laurent16c66dd2019-05-01 17:54:10 -07001867 // matching criteria values in priority order for best matching output so far
1868 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001869
Eric Laurent16c66dd2019-05-01 17:54:10 -07001870 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1871 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1872 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001873
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001874 for (audio_io_handle_t output : outputs) {
1875 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001876 // matching criteria values in priority order for current output
1877 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001878
Eric Laurent16c66dd2019-05-01 17:54:10 -07001879 if (outputDesc->isDuplicated()) {
1880 continue;
1881 }
1882 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1883 continue;
1884 }
Eric Laurent8838a382014-09-08 16:44:28 -07001885
Eric Laurent16c66dd2019-05-01 17:54:10 -07001886 // If haptic channel is specified, use the haptic output if present.
1887 // When using haptic output, same audio format and sample rate are required.
1888 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001889 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001890 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1891 continue;
1892 }
1893 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001894 && format == outputDesc->getFormat()
1895 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001896 currentMatchCriteria[0] = outputHapticChannelCount;
1897 }
1898
1899 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001900 const int matchingFunctionalFlags =
1901 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1902 const int totalFunctionalFlags =
1903 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1904 // Prefer matching functional flags, but subtract unnecessary functional flags.
1905 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001906
1907 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001908 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1909 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001910 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1911 channelCount <= outputChannelCount) {
1912 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001913 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1914 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001915 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001916 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001917 currentMatchCriteria[3] = outputChannelCount;
1918 }
1919
1920 // sampling rate match
1921 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001922 samplingRate <= outputDesc->getSamplingRate()) {
1923 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001924 }
1925
1926 // performance flags match
1927 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1928
1929 // format match
1930 if (format != AUDIO_FORMAT_INVALID) {
1931 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001932 PolicyAudioPort::kFormatDistanceMax -
1933 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001934 }
1935
1936 // primary output match
1937 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1938
1939 // compare match criteria by priority then value
1940 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1941 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1942 bestMatchCriteria = currentMatchCriteria;
1943 bestOutput = output;
1944
1945 std::stringstream result;
1946 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1947 std::ostream_iterator<int>(result, " "));
1948 ALOGV("%s new bestOutput %d criteria %s",
1949 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001950 }
1951 }
1952
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001954}
1955
Eric Laurent8fc147b2018-07-22 19:13:55 -07001956status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001957{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001958 ALOGV("%s portId %d", __FUNCTION__, portId);
1959
1960 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1961 if (outputDesc == 0) {
1962 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001963 return BAD_VALUE;
1964 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001965 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001966
Eric Laurent8fc147b2018-07-22 19:13:55 -07001967 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001968 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001969
Eric Laurent733ce942017-12-07 12:18:25 -08001970 status_t status = outputDesc->start();
1971 if (status != NO_ERROR) {
1972 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001973 }
1974
Eric Laurent97ac8712018-07-27 18:59:02 -07001975 uint32_t delayMs;
1976 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001977
1978 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001979 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001980 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001981 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001982 if (delayMs != 0) {
1983 usleep(delayMs * 1000);
1984 }
1985
1986 return status;
1987}
1988
Eric Laurent97ac8712018-07-27 18:59:02 -07001989status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1990 const sp<TrackClientDescriptor>& client,
1991 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001992{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001993 // cannot start playback of STREAM_TTS if any other output is being used
1994 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001995
1996 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001997 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001998 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001999 auto clientStrategy = client->strategy();
2000 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002001 if (stream == AUDIO_STREAM_TTS) {
2002 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002003 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002004 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002005 return INVALID_OPERATION;
2006 } else {
2007 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2008 }
2009 } else {
2010 // some playback other than beacon starts
2011 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2012 }
2013
Eric Laurent77305a62016-07-25 16:39:22 -07002014 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002015 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002016 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002017
François Gaffie11d30102018-11-02 16:09:09 +01002018 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002019 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002020 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002021 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002022 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002023 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002024 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002025 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002026 } else {
2027 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002028 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002029 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2030 AUDIO_FORMAT_DEFAULT);
2031 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2032 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002033 }
2034
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002035 // requiresMuteCheck is false when we can bypass mute strategy.
2036 // It covers a common case when there is no materially active audio
2037 // and muting would result in unnecessary delay and dropped audio.
2038 const uint32_t outputLatencyMs = outputDesc->latency();
2039 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
2040
Eric Laurente552edb2014-03-10 17:42:56 -07002041 // increment usage count for this stream on the requested output:
2042 // NOTE that the usage count is the same for duplicated output and hardware output which is
2043 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002044 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002045
2046 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002047 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2048 client->isPreferredDeviceForExclusiveUse()) {
2049 // Preferred device may be exclusive, use only if no other active clients on this output
2050 devices = DeviceVector(
2051 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2052 } else {
2053 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2054 }
François Gaffie11d30102018-11-02 16:09:09 +01002055 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002056 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002057 }
2058 }
Eric Laurente552edb2014-03-10 17:42:56 -07002059
François Gaffiec005e562018-11-06 15:04:49 +01002060 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002061 selectOutputForMusicEffects();
2062 }
2063
François Gaffie1c878552018-11-22 16:53:21 +01002064 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002065 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002066 if (devices.isEmpty()) {
2067 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002068 }
François Gaffiec005e562018-11-06 15:04:49 +01002069 bool shouldWait =
2070 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2071 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2072 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002073 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002074 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002075 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002076 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002077 // An output has a shared device if
2078 // - managed by the same hw module
2079 // - supports the currently selected device
2080 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002081 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002082
Eric Laurent77305a62016-07-25 16:39:22 -07002083 // force a device change if any other output is:
2084 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002085 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002086 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002087 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002088 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002089 // change the device currently selected by the other output.
2090 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002091 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002092 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002093 force = true;
2094 }
2095 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002096 // a notification so that audio focus effect can propagate, or that a mute/unmute
2097 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002098 const uint32_t latencyMs = desc->latency();
2099 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2100
2101 if (shouldWait && isActive && (waitMs < latencyMs)) {
2102 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002103 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002104
2105 // Require mute check if another output is on a shared device
2106 // and currently active to have proper drain and avoid pops.
2107 // Note restoring AudioTracks onto this output needs to invoke
2108 // a volume ramp if there is no mute.
2109 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002110 }
2111 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002112
2113 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002114 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002115
Eric Laurente552edb2014-03-10 17:42:56 -07002116 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002117 auto &curves = getVolumeCurves(client->attributes());
2118 checkAndSetVolume(curves, client->volumeSource(),
2119 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002120 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002121 outputDesc->devices().types(), 0 /*delay*/,
2122 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002123
2124 // update the outputs if starting an output with a stream that can affect notification
2125 // routing
2126 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002127
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002128 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002129 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002130 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2131 }
Eric Laurentdc462862016-07-19 12:29:53 -07002132
2133 if (waitMs > muteWaitMs) {
2134 *delayMs = waitMs - muteWaitMs;
2135 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002136
2137 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2138 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2139 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2140 // change occurs after the MixerThread starts and causes a stream volume
2141 // glitch.
2142 //
2143 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002144 }
Eric Laurentdc462862016-07-19 12:29:53 -07002145
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002146 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002147 mEngine->getForceUse(
2148 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002149 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002150 }
2151
Eric Laurent97ac8712018-07-27 18:59:02 -07002152 // Automatically enable the remote submix input when output is started on a re routing mix
2153 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002154 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2155 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002156 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2157 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2158 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002159 "remote-submix",
2160 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002161 }
2162
Eric Laurente552edb2014-03-10 17:42:56 -07002163 return NO_ERROR;
2164}
2165
Eric Laurent8fc147b2018-07-22 19:13:55 -07002166status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002167{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002168 ALOGV("%s portId %d", __FUNCTION__, portId);
2169
2170 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2171 if (outputDesc == 0) {
2172 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002173 return BAD_VALUE;
2174 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002175 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002176
Eric Laurent97ac8712018-07-27 18:59:02 -07002177 ALOGV("stopOutput() output %d, stream %d, session %d",
2178 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002179
Eric Laurent97ac8712018-07-27 18:59:02 -07002180 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002181
Eric Laurent733ce942017-12-07 12:18:25 -08002182 if (status == NO_ERROR ) {
2183 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002184 }
2185 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002186}
2187
Eric Laurent97ac8712018-07-27 18:59:02 -07002188status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2189 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002190{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002191 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002192 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002193 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002194
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002195 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2196
François Gaffie1c878552018-11-22 16:53:21 +01002197 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2198 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002199 // Automatically disable the remote submix input when output is stopped on a
2200 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002201 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002202 if (isSingleDeviceType(
2203 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002204 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002205 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002206 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2207 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002208 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002209 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002210 }
2211 }
2212 bool forceDeviceUpdate = false;
2213 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002214 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002215 forceDeviceUpdate = true;
2216 }
2217
Eric Laurente552edb2014-03-10 17:42:56 -07002218 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002219 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002220
Eric Laurente552edb2014-03-10 17:42:56 -07002221 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002222 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002223 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002224 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002225
2226 // If the routing does not change, if an output is routed on a device using HwGain
2227 // (aka setAudioPortConfig) and there are still active clients following different
2228 // volume group(s), force reapply volume
2229 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2230 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2231
Eric Laurente552edb2014-03-10 17:42:56 -07002232 // delay the device switch by twice the latency because stopOutput() is executed when
2233 // the track stop() command is received and at that time the audio track buffer can
2234 // still contain data that needs to be drained. The latency only covers the audio HAL
2235 // and kernel buffers. Also the latency does not always include additional delay in the
2236 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002237 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2238 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002239
2240 // force restoring the device selection on other active outputs if it differs from the
2241 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002242 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002243 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002244 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002245 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002246 desc->isActive() &&
2247 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002248 (newDevices != desc->devices())) {
2249 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2250 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002251
François Gaffie11d30102018-11-02 16:09:09 +01002252 setOutputDevices(desc, newDevices2, force, delayMs);
2253
Eric Laurent57de36c2016-09-28 16:59:11 -07002254 // re-apply device specific volume if not done by setOutputDevice()
2255 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002256 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002257 }
Eric Laurente552edb2014-03-10 17:42:56 -07002258 }
2259 }
2260 // update the outputs if stopping one with a stream that can affect notification routing
2261 handleNotificationRoutingForStream(stream);
2262 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002263
2264 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2265 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002266 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002267 }
2268
François Gaffiec005e562018-11-06 15:04:49 +01002269 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002270 selectOutputForMusicEffects();
2271 }
Eric Laurente552edb2014-03-10 17:42:56 -07002272 return NO_ERROR;
2273 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002274 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002275 return INVALID_OPERATION;
2276 }
2277}
2278
jiabinbce0c1d2020-10-05 11:20:18 -07002279bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002280{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002281 ALOGV("%s portId %d", __FUNCTION__, portId);
2282
2283 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2284 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002285 // If an output descriptor is closed due to a device routing change,
2286 // then there are race conditions with releaseOutput from tracks
2287 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2288 // destroyed shortly thereafter.
2289 //
2290 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002291 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002292 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002293 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002294
2295 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002296
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302297 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2298 if (outputDesc->isClientActive(client)) {
2299 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2300 stopOutput(portId);
2301 }
2302
Eric Laurent8fc147b2018-07-22 19:13:55 -07002303 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2304 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002305 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002306 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002307 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002308 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002309 if (--outputDesc->mDirectOpenCount == 0) {
2310 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002311 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002312 }
2313 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302314
Andy Hung39efb7a2018-09-26 15:39:28 -07002315 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002316 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2317 // The output is pending reopened to query dynamic profiles and
2318 // there is no active clients
2319 closeOutput(outputDesc->mIoHandle);
2320 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2321 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2322 if (newOutputDesc == nullptr) {
2323 ALOGE("%s failed to open output", __func__);
2324 }
2325 return true;
2326 }
2327 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002328}
2329
Eric Laurentcaf7f482014-11-25 17:50:47 -08002330status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2331 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002332 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002333 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002334 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002335 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002336 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002337 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002338 input_type_t *inputType,
2339 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002340{
François Gaffiec005e562018-11-06 15:04:49 +01002341 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002342 "flags %#x attributes=%s requested device ID %d",
2343 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2344 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002345
Eric Laurentad2e7b92017-09-14 20:06:42 -07002346 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002347 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002348 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002349 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002350 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002351 sp<AudioInputDescriptor> inputDesc;
2352 sp<RecordClientDescriptor> clientDesc;
2353 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002354 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002355 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002356
2357 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2358 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2359 return INVALID_OPERATION;
2360 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002361
Francois Gaffie716e1432019-01-14 16:58:59 +01002362 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2363 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002364 }
2365
Paul McLean466dc8e2015-04-17 13:15:36 -06002366 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002367 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002368 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002369
Eric Laurentad2e7b92017-09-14 20:06:42 -07002370 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2371 // possible
2372 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2373 *input != AUDIO_IO_HANDLE_NONE) {
2374 ssize_t index = mInputs.indexOfKey(*input);
2375 if (index < 0) {
2376 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2377 status = BAD_VALUE;
2378 goto error;
2379 }
2380 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002381 RecordClientVector clients = inputDesc->getClientsForSession(session);
2382 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002383 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2384 status = BAD_VALUE;
2385 goto error;
2386 }
2387 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2388 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002389 // corresponds to a new client and is only permitted from the same UID.
2390 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002391 if (clients.size() > 1) {
2392 for (const auto& client : clients) {
2393 // The client map is ordered by key values (portId) and portIds are allocated
2394 // incrementaly. So the first client in this list is the one opened by audio flinger
2395 // when the mmap stream is created and should be ignored as it does not correspond
2396 // to an actual client
2397 if (client == *clients.cbegin()) {
2398 continue;
2399 }
2400 if (uid != client->uid() && !client->isSilenced()) {
2401 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2402 uid, client->portId(), client->uid());
2403 status = INVALID_OPERATION;
2404 goto error;
2405 }
Eric Laurent331679c2018-04-16 17:03:16 -07002406 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002407 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002408 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002409 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002410
Eric Laurentfecbceb2021-02-09 14:46:43 +01002411 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002412 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002413 }
2414
2415 *input = AUDIO_IO_HANDLE_NONE;
2416 *inputType = API_INPUT_INVALID;
2417
Francois Gaffie716e1432019-01-14 16:58:59 +01002418 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002419
Francois Gaffie716e1432019-01-14 16:58:59 +01002420 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2421 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2422 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002423 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002424 ALOGW("%s could not find input mix for attr %s",
2425 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002426 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002427 }
jiabinc1de2df2019-05-07 14:26:40 -07002428 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2429 String8(attr->tags + strlen("addr=")),
2430 AUDIO_FORMAT_DEFAULT);
2431 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002432 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002433 __func__, attributes.source, attributes.tags);
2434 status = BAD_VALUE;
2435 goto error;
2436 }
2437
Kevin Rocard25f9b052019-02-27 15:08:54 -08002438 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2439 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2440 } else {
2441 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2442 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002443 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002444 if (explicitRoutingDevice != nullptr) {
2445 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002446 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002447 // Prevent from storing invalid requested device id in clients
2448 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002449 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002450 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2451 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002452 }
François Gaffie11d30102018-11-02 16:09:09 +01002453 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002454 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002455 status = BAD_VALUE;
2456 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002457 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002458 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2459 *inputType = API_INPUT_MIX_CAPTURE;
2460 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002461 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2462 // there is an external policy, but this input is attached to a mix of recorders,
2463 // meaning it receives audio injected into the framework, so the recorder doesn't
2464 // know about it and is therefore considered "legacy"
2465 *inputType = API_INPUT_LEGACY;
2466 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002467 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002468 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002469 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002470 } else {
2471 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002472 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002473
Eric Laurent599c7582015-12-07 18:05:55 -08002474 }
2475
François Gaffiec005e562018-11-06 15:04:49 +01002476 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002477 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002478 status = INVALID_OPERATION;
2479 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002480 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002481
Eric Laurent8f42ea12018-08-08 09:08:25 -07002482exit:
2483
François Gaffiec005e562018-11-06 15:04:49 +01002484 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2485 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002486
Francois Gaffie716e1432019-01-14 16:58:59 +01002487 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002488 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002489 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002490
Mikhail Naganov2996f672019-04-18 12:29:59 -07002491 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002492 requestedDeviceId, attributes.source, flags,
2493 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002494 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002495 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002496
2497 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2498 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002499
Eric Laurent599c7582015-12-07 18:05:55 -08002500 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002501
2502error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002503 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002504}
2505
2506
François Gaffie11d30102018-11-02 16:09:09 +01002507audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002508 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002509 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002510 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002511 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002512 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002513{
2514 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002515 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002516 bool isSoundTrigger = false;
2517
François Gaffiec005e562018-11-06 15:04:49 +01002518 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002519 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2520 if (index >= 0) {
2521 input = mSoundTriggerSessions.valueFor(session);
2522 isSoundTrigger = true;
2523 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2524 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2525 } else {
2526 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002527 }
François Gaffiec005e562018-11-06 15:04:49 +01002528 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002529 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002530 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002531 }
2532
Carter Hsua3abb402021-10-26 11:11:20 +08002533 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2534 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2535 }
2536
Andy Hungf129b032015-04-07 13:45:50 -07002537 // find a compatible input profile (not necessarily identical in parameters)
2538 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002539 // sampling rate and flags may be updated by getInputProfile
2540 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2541 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002542 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002543 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002544 audio_input_flags_t profileFlags = flags;
2545 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002546 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002547 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002548 profileFlags);
2549 if (profile != 0) {
2550 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002551 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2552 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002553 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002554 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2555 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002556 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002557 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002558 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002559 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002560 }
Eric Laurente552edb2014-03-10 17:42:56 -07002561 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002562 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002563 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002564 if (samplingRate == 0) {
2565 samplingRate = profileSamplingRate;
2566 }
Eric Laurente552edb2014-03-10 17:42:56 -07002567
Eric Laurent322b4d22015-04-03 15:57:54 -07002568 if (profile->getModuleHandle() == 0) {
2569 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002570 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002571 }
2572
Eric Laurentec376dc2021-04-08 20:41:22 +02002573 // Reuse an already opened input if a client with the same session ID already exists
2574 // on that input
2575 for (size_t i = 0; i < mInputs.size(); i++) {
2576 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2577 if (desc->mProfile != profile) {
2578 continue;
2579 }
2580 RecordClientVector clients = desc->clientsList();
2581 for (const auto &client : clients) {
2582 if (session == client->session()) {
2583 return desc->mIoHandle;
2584 }
2585 }
2586 }
2587
Eric Laurent3974e3b2017-12-07 17:58:43 -08002588 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002589 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002590 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002591 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002592 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002593 continue;
2594 }
2595 // if sound trigger, reuse input if used by other sound trigger on same session
2596 // else
2597 // reuse input if active client app is not in IDLE state
2598 //
2599 RecordClientVector clients = desc->clientsList();
2600 bool doClose = false;
2601 for (const auto& client : clients) {
2602 if (isSoundTrigger != client->isSoundTrigger()) {
2603 continue;
2604 }
2605 if (client->isSoundTrigger()) {
2606 if (session == client->session()) {
2607 return desc->mIoHandle;
2608 }
2609 continue;
2610 }
2611 if (client->active() && client->appState() != APP_STATE_IDLE) {
2612 return desc->mIoHandle;
2613 }
2614 doClose = true;
2615 }
2616 if (doClose) {
2617 closeInput(desc->mIoHandle);
2618 } else {
2619 i++;
2620 }
2621 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002622 }
2623
Eric Laurentfe231122017-11-17 17:48:06 -08002624 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002625
Eric Laurentfe231122017-11-17 17:48:06 -08002626 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2627 lConfig.sample_rate = profileSamplingRate;
2628 lConfig.channel_mask = profileChannelMask;
2629 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002630
François Gaffie11d30102018-11-02 16:09:09 +01002631 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002632
2633 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002634 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002635 (profileSamplingRate != lConfig.sample_rate) ||
2636 !audio_formats_match(profileFormat, lConfig.format) ||
2637 (profileChannelMask != lConfig.channel_mask)) {
2638 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002639 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002640 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002641 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002642 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002643 }
Eric Laurent599c7582015-12-07 18:05:55 -08002644 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002645 }
2646
Eric Laurentc722f302014-12-10 11:21:49 -08002647 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002648
Eric Laurent599c7582015-12-07 18:05:55 -08002649 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002650 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002651
Eric Laurent599c7582015-12-07 18:05:55 -08002652 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002653}
2654
Eric Laurent4eb58f12018-12-07 16:41:02 -08002655status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002656{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002657 ALOGV("%s portId %d", __FUNCTION__, portId);
2658
2659 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2660 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002661 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002662 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002663 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002664 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002665 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002666 if (client->active()) {
2667 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2668 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002669 }
2670
Eric Laurent8f42ea12018-08-08 09:08:25 -07002671 audio_session_t session = client->session();
2672
Eric Laurent4eb58f12018-12-07 16:41:02 -08002673 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002674
Eric Laurent4eb58f12018-12-07 16:41:02 -08002675 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002676
Eric Laurent4eb58f12018-12-07 16:41:02 -08002677 status_t status = inputDesc->start();
2678 if (status != NO_ERROR) {
2679 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002680 }
Eric Laurente552edb2014-03-10 17:42:56 -07002681
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002682 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002683 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002684 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002685
Eric Laurent8f42ea12018-08-08 09:08:25 -07002686 // indicate active capture to sound trigger service if starting capture from a mic on
2687 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002688 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002689 if (device != nullptr) {
2690 status = setInputDevice(input, device, true /* force */);
2691 } else {
2692 ALOGW("%s no new input device can be found for descriptor %d",
2693 __FUNCTION__, inputDesc->getId());
2694 status = BAD_VALUE;
2695 }
Eric Laurente552edb2014-03-10 17:42:56 -07002696
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002697 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002698 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002699 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002700 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002701 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2702 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002703 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002704 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002705
François Gaffie11d30102018-11-02 16:09:09 +01002706 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2707 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002708 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002709 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002710 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002711
Eric Laurent8f42ea12018-08-08 09:08:25 -07002712 // automatically enable the remote submix output when input is started if not
2713 // used by a policy mix of type MIX_TYPE_RECORDERS
2714 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002715 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002716 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002717 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002718 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002719 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2720 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002721 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002722 if (address != "") {
2723 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2724 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002725 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002726 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002727 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002728 } else if (status != NO_ERROR) {
2729 // Restore client activity state.
2730 inputDesc->setClientActive(client, false);
2731 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002732 }
2733
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002734 ALOGV("%s input %d source = %d status = %d exit",
2735 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002736
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002737 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002738}
2739
Eric Laurent8fc147b2018-07-22 19:13:55 -07002740status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002741{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002742 ALOGV("%s portId %d", __FUNCTION__, portId);
2743
2744 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2745 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002746 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002747 return BAD_VALUE;
2748 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002749 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002750 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002751 if (!client->active()) {
2752 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002753 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002754 }
Carter Hsue6139d52021-07-08 10:30:20 +08002755 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002756 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002757
Eric Laurent8f42ea12018-08-08 09:08:25 -07002758 inputDesc->stop();
2759 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002760 auto current_source = inputDesc->source();
2761 setInputDevice(input, getNewInputDevice(inputDesc),
2762 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002763 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002764 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002765 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002766 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002767 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2768 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002769 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002770 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002771
2772 // automatically disable the remote submix output when input is stopped if not
2773 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002774 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002775 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002776 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002777 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002778 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2779 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002780 }
2781 if (address != "") {
2782 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2783 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002784 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002785 }
2786 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002787 resetInputDevice(input);
2788
2789 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2790 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002791 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2792 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002793 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002794 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002795 }
2796 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002797 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002798 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002799}
2800
Eric Laurent8fc147b2018-07-22 19:13:55 -07002801void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002802{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002803 ALOGV("%s portId %d", __FUNCTION__, portId);
2804
2805 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2806 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002807 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002808 return;
2809 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002810 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002811 audio_io_handle_t input = inputDesc->mIoHandle;
2812
Eric Laurent8f42ea12018-08-08 09:08:25 -07002813 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002814
Andy Hung39efb7a2018-09-26 15:39:28 -07002815 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002816
Andy Hung39efb7a2018-09-26 15:39:28 -07002817 if (inputDesc->getClientCount() > 0) {
2818 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002819 return;
2820 }
2821
Eric Laurent05b90f82014-08-27 15:32:29 -07002822 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002823 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002824 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002825}
2826
Eric Laurent8f42ea12018-08-08 09:08:25 -07002827void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002828{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002829 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002830
2831 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002832 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002833 }
2834}
2835
Eric Laurent8f42ea12018-08-08 09:08:25 -07002836void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2837{
2838 stopInput(portId);
2839 releaseInput(portId);
2840}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002841
Eric Laurent0dd51852019-04-19 18:18:58 -07002842void AudioPolicyManager::checkCloseInputs() {
2843 // After connecting or disconnecting an input device, close input if:
2844 // - it has no client (was just opened to check profile) OR
2845 // - none of its supported devices are connected anymore OR
2846 // - one of its clients cannot be routed to one of its supported
2847 // devices anymore. Otherwise update device selection
2848 std::vector<audio_io_handle_t> inputsToClose;
2849 for (size_t i = 0; i < mInputs.size(); i++) {
2850 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2851 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002852 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002853 inputsToClose.push_back(mInputs.keyAt(i));
2854 } else {
2855 bool close = false;
2856 for (const auto& client : input->clientsList()) {
2857 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002858 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002859 if (!input->supportedDevices().contains(device)) {
2860 close = true;
2861 break;
2862 }
2863 }
2864 if (close) {
2865 inputsToClose.push_back(mInputs.keyAt(i));
2866 } else {
2867 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2868 }
2869 }
2870 }
2871
2872 for (const audio_io_handle_t handle : inputsToClose) {
2873 ALOGV("%s closing input %d", __func__, handle);
2874 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002875 }
Eric Laurentd4692962014-05-05 18:13:44 -07002876}
2877
François Gaffie251c7f02018-11-07 10:41:08 +01002878void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002879{
2880 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002881 if (indexMin < 0 || indexMax < 0) {
2882 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2883 return;
2884 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002885 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002886
2887 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002888 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2889 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002890 continue;
2891 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002892 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002893 }
Eric Laurente552edb2014-03-10 17:42:56 -07002894}
2895
Eric Laurente0720872014-03-11 09:30:41 -07002896status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002897 int index,
2898 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002899{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002900 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002901 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2902 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2903 return NO_ERROR;
2904 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002905 ALOGV("%s: stream %s attributes=%s", __func__,
2906 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002907 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002908}
2909
Eric Laurente0720872014-03-11 09:30:41 -07002910status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002911 int *index,
2912 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002913{
François Gaffiec005e562018-11-06 15:04:49 +01002914 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2915 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002916 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002917 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002918 deviceTypes = mEngine->getOutputDevicesForStream(
2919 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002920 }
jiabin9a3361e2019-10-01 09:38:30 -07002921 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002922}
2923
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002924status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002925 int index,
2926 audio_devices_t device)
2927{
2928 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002929 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2930 if (group == VOLUME_GROUP_NONE) {
2931 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002932 return BAD_VALUE;
2933 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002934 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002935 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002936 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002937 VolumeSource vs = toVolumeSource(group);
2938 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2939
2940 status = setVolumeCurveIndex(index, device, curves);
2941 if (status != NO_ERROR) {
2942 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2943 return status;
2944 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002945
jiabin9a3361e2019-10-01 09:38:30 -07002946 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002947 auto curCurvAttrs = curves.getAttributes();
2948 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2949 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002950 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002951 } else if (!curves.getStreamTypes().empty()) {
2952 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002953 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002954 } else {
2955 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2956 return BAD_VALUE;
2957 }
jiabin9a3361e2019-10-01 09:38:30 -07002958 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2959 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002960
François Gaffiecfe17322018-11-07 13:41:29 +01002961 // update volume on all outputs and streams matching the following:
2962 // - The requested stream (or a stream matching for volume control) is active on the output
2963 // - The device (or devices) selected by the engine for this stream includes
2964 // the requested device
2965 // - For non default requested device, currently selected device on the output is either the
2966 // requested device or one of the devices selected by the engine for this stream
2967 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2968 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002969 for (size_t i = 0; i < mOutputs.size(); i++) {
2970 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002971 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002972
jiabin9a3361e2019-10-01 09:38:30 -07002973 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2974 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002975 }
François Gaffieed91f582020-01-31 10:35:37 +01002976 if (!(desc->isActive(vs) || isInCall())) {
2977 continue;
2978 }
2979 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2980 curDevices.find(device) == curDevices.end()) {
2981 continue;
2982 }
2983 bool applyVolume = false;
2984 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2985 curSrcDevices.insert(device);
2986 applyVolume = (curSrcDevices.find(
2987 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2988 } else {
2989 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2990 }
2991 if (!applyVolume) {
2992 continue; // next output
2993 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002994 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2995 // If a higher priority strategy is active, and the output is routed to a device with a
2996 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002997 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002998 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02002999 // If the volume source is active with higher priority source, ensure at least Sw Muted
3000 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003001 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3002 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3003 false /*preferredDevice*/);
3004 if (activeClients.empty()) {
3005 continue;
3006 }
3007 bool isPreempted = false;
3008 bool isHigherPriority = productStrategy < strategy;
3009 for (const auto &client : activeClients) {
3010 if (isHigherPriority && (client->volumeSource() != vs)) {
3011 ALOGV("%s: Strategy=%d (\nrequester:\n"
3012 " group %d, volumeGroup=%d attributes=%s)\n"
3013 " higher priority source active:\n"
3014 " volumeGroup=%d attributes=%s) \n"
3015 " on output %zu, bailing out", __func__, productStrategy,
3016 group, group, toString(attributes).c_str(),
3017 client->volumeSource(), toString(client->attributes()).c_str(), i);
3018 applyVolume = false;
3019 isPreempted = true;
3020 break;
3021 }
3022 // However, continue for loop to ensure no higher prio clients running on output
3023 if (client->volumeSource() == vs) {
3024 applyVolume = true;
3025 }
3026 }
3027 if (isPreempted || applyVolume) {
3028 break;
3029 }
3030 }
3031 if (!applyVolume) {
3032 continue; // next output
3033 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003034 }
François Gaffieed91f582020-01-31 10:35:37 +01003035 //FIXME: workaround for truncated touch sounds
3036 // delayed volume change for system stream to be removed when the problem is
3037 // handled by system UI
3038 status_t volStatus = checkAndSetVolume(
3039 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003040 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003041 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3042 if (volStatus != NO_ERROR) {
3043 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003044 }
3045 }
François Gaffiecfe17322018-11-07 13:41:29 +01003046 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3047 return status;
3048}
3049
François Gaffieaaac0fd2018-11-22 17:56:39 +01003050status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003051 audio_devices_t device,
3052 IVolumeCurves &volumeCurves)
3053{
3054 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3055 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003056 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3057 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003058 (index > volumeCurves.getVolumeIndexMax())) {
3059 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3060 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3061 return BAD_VALUE;
3062 }
3063 if (!audio_is_output_device(device)) {
3064 return BAD_VALUE;
3065 }
3066
3067 // Force max volume if stream cannot be muted
3068 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3069
François Gaffieaaac0fd2018-11-22 17:56:39 +01003070 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003071 volumeCurves.addCurrentVolumeIndex(device, index);
3072 return NO_ERROR;
3073}
3074
3075status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3076 int &index,
3077 audio_devices_t device)
3078{
3079 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3080 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003081 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003082 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003083 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3084 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003085 }
jiabin9a3361e2019-10-01 09:38:30 -07003086 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003087}
3088
3089status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3090 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003091 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003092{
jiabin9a3361e2019-10-01 09:38:30 -07003093 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003094 return BAD_VALUE;
3095 }
jiabin9a3361e2019-10-01 09:38:30 -07003096 index = curves.getVolumeIndex(deviceTypes);
3097 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003098 return NO_ERROR;
3099}
3100
3101status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3102 int &index)
3103{
3104 index = getVolumeCurves(attr).getVolumeIndexMin();
3105 return NO_ERROR;
3106}
3107
3108status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3109 int &index)
3110{
3111 index = getVolumeCurves(attr).getVolumeIndexMax();
3112 return NO_ERROR;
3113}
3114
Eric Laurent36829f92017-04-07 19:04:42 -07003115audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003116{
3117 // select one output among several suitable for global effects.
3118 // The priority is as follows:
3119 // 1: An offloaded output. If the effect ends up not being offloadable,
3120 // AudioFlinger will invalidate the track and the offloaded output
3121 // will be closed causing the effect to be moved to a PCM output.
3122 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003123 // 3: The primary output
3124 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003125
François Gaffiec005e562018-11-06 15:04:49 +01003126 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3127 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003128 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003129
Eric Laurent36829f92017-04-07 19:04:42 -07003130 if (outputs.size() == 0) {
3131 return AUDIO_IO_HANDLE_NONE;
3132 }
Eric Laurente552edb2014-03-10 17:42:56 -07003133
Eric Laurent36829f92017-04-07 19:04:42 -07003134 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3135 bool activeOnly = true;
3136
3137 while (output == AUDIO_IO_HANDLE_NONE) {
3138 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3139 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3140 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3141
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003142 for (audio_io_handle_t output : outputs) {
3143 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003144 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003145 continue;
3146 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003147 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3148 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003149 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003150 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003151 }
3152 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003153 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003154 }
3155 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003156 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003157 }
3158 }
3159 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3160 output = outputOffloaded;
3161 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3162 output = outputDeepBuffer;
3163 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3164 output = outputPrimary;
3165 } else {
3166 output = outputs[0];
3167 }
3168 activeOnly = false;
3169 }
3170
3171 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003172 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003173 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3174 mMusicEffectOutput = output;
3175 }
3176
3177 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003178 return output;
3179}
3180
Eric Laurent36829f92017-04-07 19:04:42 -07003181audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3182{
3183 return selectOutputForMusicEffects();
3184}
3185
Eric Laurente0720872014-03-11 09:30:41 -07003186status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003187 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003188 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003189 int session,
3190 int id)
3191{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003192 if (session != AUDIO_SESSION_DEVICE) {
3193 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003194 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003195 index = mInputs.indexOfKey(io);
3196 if (index < 0) {
3197 ALOGW("registerEffect() unknown io %d", io);
3198 return INVALID_OPERATION;
3199 }
Eric Laurente552edb2014-03-10 17:42:56 -07003200 }
3201 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003202 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3203 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3204 || strategy == PRODUCT_STRATEGY_NONE));
3205 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003206}
3207
Eric Laurentc241b0d2018-11-28 09:08:49 -08003208status_t AudioPolicyManager::unregisterEffect(int id)
3209{
3210 if (mEffects.getEffect(id) == nullptr) {
3211 return INVALID_OPERATION;
3212 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003213 if (mEffects.isEffectEnabled(id)) {
3214 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3215 setEffectEnabled(id, false);
3216 }
3217 return mEffects.unregisterEffect(id);
3218}
3219
3220status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3221{
3222 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3223 if (effect == nullptr) {
3224 return INVALID_OPERATION;
3225 }
3226
3227 status_t status = mEffects.setEffectEnabled(id, enabled);
3228 if (status == NO_ERROR) {
3229 mInputs.trackEffectEnabled(effect, enabled);
3230 }
3231 return status;
3232}
3233
Eric Laurent6c796322019-04-09 14:13:17 -07003234
3235status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3236{
3237 mEffects.moveEffects(ids, io);
3238 return NO_ERROR;
3239}
3240
Eric Laurentc75307b2015-03-17 15:29:32 -07003241bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3242{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003243 auto vs = toVolumeSource(stream, false);
3244 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003245}
3246
3247bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3248{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003249 auto vs = toVolumeSource(stream, false);
3250 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003251}
3252
Eric Laurente0720872014-03-11 09:30:41 -07003253bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003254{
3255 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003256 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003257 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003258 return true;
3259 }
3260 }
3261 return false;
3262}
3263
Eric Laurent275e8e92014-11-30 15:14:47 -08003264// Register a list of custom mixes with their attributes and format.
3265// When a mix is registered, corresponding input and output profiles are
3266// added to the remote submix hw module. The profile contains only the
3267// parameters (sampling rate, format...) specified by the mix.
3268// The corresponding input remote submix device is also connected.
3269//
3270// When a remote submix device is connected, the address is checked to select the
3271// appropriate profile and the corresponding input or output stream is opened.
3272//
3273// When capture starts, getInputForAttr() will:
3274// - 1 look for a mix matching the address passed in attribtutes tags if any
3275// - 2 if none found, getDeviceForInputSource() will:
3276// - 2.1 look for a mix matching the attributes source
3277// - 2.2 if none found, default to device selection by policy rules
3278// At this time, the corresponding output remote submix device is also connected
3279// and active playback use cases can be transferred to this mix if needed when reconnecting
3280// after AudioTracks are invalidated
3281//
3282// When playback starts, getOutputForAttr() will:
3283// - 1 look for a mix matching the address passed in attribtutes tags if any
3284// - 2 if none found, look for a mix matching the attributes usage
3285// - 3 if none found, default to device and output selection by policy rules.
3286
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003287status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003288{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003289 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3290 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003291 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003292 sp<HwModule> rSubmixModule;
3293 // examine each mix's route type
3294 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003295 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003296 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3297 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3298 ALOGE("Unsupported Policy Mix %zu of %zu: "
3299 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3300 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003301 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003302 break;
3303 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003304 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3305 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003306 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003307 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3308 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003309 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003310 rSubmixModule = mHwModules.getModuleFromName(
3311 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3312 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003313 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003314 i);
3315 res = INVALID_OPERATION;
3316 break;
3317 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003318 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003319
Eric Laurent97ac8712018-07-27 18:59:02 -07003320 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003321 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003322 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003323 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003324 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3325 } else {
3326 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3327 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003328 }
François Gaffie036e1e92015-03-19 10:16:24 +01003329
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003330 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003331 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003332 res = INVALID_OPERATION;
3333 break;
3334 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003335 audio_config_t outputConfig = mix.mFormat;
3336 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003337 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3338 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003339 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3340 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003341 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003342 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003343 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003344 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003345
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003346 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003347 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3348 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3349 ALOGE("Failed to set remote submix device available, type %u, address %s",
3350 mix.mDeviceType, address.string());
3351 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003352 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003353 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3354 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003355 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003356 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003357 i, mixes.size(), type, address.string());
3358
3359 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3360 mix.mDeviceType, mix.mDeviceAddress,
3361 String8(), AUDIO_FORMAT_DEFAULT);
3362 if (device == nullptr) {
3363 res = INVALID_OPERATION;
3364 break;
3365 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003366
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003367 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003368 // First try to find an already opened output supporting the device
3369 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003370 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003371
Eric Laurentc529cf62020-04-17 18:19:10 -07003372 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003373 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003374 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3375 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003376 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003377 } else {
3378 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003379 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003380 }
3381 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003382 // If no output found, try to find a direct output profile supporting the device
3383 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3384 sp<HwModule> module = mHwModules[i];
3385 for (size_t j = 0;
3386 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3387 j++) {
3388 sp<IOProfile> profile = module->getOutputProfiles()[j];
3389 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3390 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3391 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3392 address.string());
3393 res = INVALID_OPERATION;
3394 } else {
3395 foundOutput = true;
3396 }
3397 }
3398 }
3399 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003400 if (res != NO_ERROR) {
3401 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003402 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003403 res = INVALID_OPERATION;
3404 break;
3405 } else if (!foundOutput) {
3406 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003407 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003408 res = INVALID_OPERATION;
3409 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003410 } else {
3411 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003412 }
Eric Laurentc722f302014-12-10 11:21:49 -08003413 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003414 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003415 if (res != NO_ERROR) {
3416 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003417 } else if (checkOutputs) {
3418 checkForDeviceAndOutputChanges();
3419 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003420 }
3421 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003422}
3423
3424status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3425{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003426 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003427 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003428 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003429 sp<HwModule> rSubmixModule;
3430 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003431 for (const auto& mix : mixes) {
3432 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003433
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003434 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003435 rSubmixModule = mHwModules.getModuleFromName(
3436 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3437 if (rSubmixModule == 0) {
3438 res = INVALID_OPERATION;
3439 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003440 }
3441 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003442
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003443 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003444
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003445 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003446 res = INVALID_OPERATION;
3447 continue;
3448 }
3449
Kevin Rocard04ed0462019-05-02 17:53:24 -07003450 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3451 if (getDeviceConnectionState(device, address.string()) ==
3452 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3453 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3454 address.string(), "remote-submix",
3455 AUDIO_FORMAT_DEFAULT);
3456 if (res != OK) {
3457 ALOGE("Error making RemoteSubmix device unavailable for mix "
3458 "with type %d, address %s", device, address.string());
3459 }
3460 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003461 }
jiabin5740f082019-08-19 15:08:30 -07003462 rSubmixModule->removeOutputProfile(address.c_str());
3463 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003464
Kevin Rocard153f92d2018-12-18 18:33:28 -08003465 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003466 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003467 res = INVALID_OPERATION;
3468 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003469 } else {
3470 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003471 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003472 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003473 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003474 if (res == NO_ERROR && checkOutputs) {
3475 checkForDeviceAndOutputChanges();
3476 updateCallAndOutputRouting();
3477 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003478 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003479}
3480
Mikhail Naganov100f0122018-11-29 11:22:16 -08003481void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3482{
3483 size_t i = 0;
3484 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3485 for (const auto& fmt : mManualSurroundFormats) {
3486 if (i++ != 0) dst->append(", ");
3487 std::string sfmt;
3488 FormatConverter::toString(fmt, sfmt);
3489 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3490 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3491 }
3492}
3493
Eric Laurentc529cf62020-04-17 18:19:10 -07003494// Returns true if all devices types match the predicate and are supported by one HW module
3495bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003496 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003497 std::function<bool(audio_devices_t)> predicate,
3498 const char *context) {
3499 for (size_t i = 0; i < devices.size(); i++) {
3500 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003501 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003502 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003503 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003504 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003505 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003506 return false;
3507 }
3508 }
3509 return true;
3510}
3511
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003512status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003513 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003514 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003515 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3516 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003517 }
3518 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003519 if (res != NO_ERROR) {
3520 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3521 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003522 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003523
3524 checkForDeviceAndOutputChanges();
3525 updateCallAndOutputRouting();
3526
3527 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003528}
3529
3530status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3531 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003532 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3533 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003534 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003535 __FUNCTION__, uid);
3536 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003537 }
3538
Eric Laurentc529cf62020-04-17 18:19:10 -07003539 checkForDeviceAndOutputChanges();
3540 updateCallAndOutputRouting();
3541
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003542 return res;
3543}
3544
Eric Laurent2517af32020-11-25 15:31:27 +01003545
jiabin0a488932020-08-07 17:32:40 -07003546status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3547 device_role_t role,
3548 const AudioDeviceTypeAddrVector &devices) {
3549 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3550 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003551
Eric Laurentc529cf62020-04-17 18:19:10 -07003552 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003553 return BAD_VALUE;
3554 }
jiabin0a488932020-08-07 17:32:40 -07003555 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003556 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003557 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3558 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003559 return status;
3560 }
3561
3562 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003563
3564 bool forceVolumeReeval = false;
3565 // FIXME: workaround for truncated touch sounds
3566 // to be removed when the problem is handled by system UI
3567 uint32_t delayMs = 0;
3568 if (strategy == mCommunnicationStrategy) {
3569 forceVolumeReeval = true;
3570 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3571 updateInputRouting();
3572 }
3573 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003574
3575 return NO_ERROR;
3576}
3577
3578void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3579{
3580 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003581 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003582 // Only apply special touch sound delay once
3583 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003584 }
3585 for (size_t i = 0; i < mOutputs.size(); i++) {
3586 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3587 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003588 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3589 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003590 // As done in setDeviceConnectionState, we could also fix default device issue by
3591 // preventing the force re-routing in case of default dev that distinguishes on address.
3592 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003593 bool forceRouting = !newDevices.isEmpty();
3594 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3595 true /*requiresMuteCheck*/,
3596 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003597 // Only apply special touch sound delay once
3598 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003599 }
3600 if (forceVolumeReeval && !newDevices.isEmpty()) {
3601 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3602 }
3603 }
3604}
3605
Eric Laurent2517af32020-11-25 15:31:27 +01003606void AudioPolicyManager::updateInputRouting() {
3607 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303608 // Skip for hotword recording as the input device switch
3609 // is handled within sound trigger HAL
3610 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3611 continue;
3612 }
Eric Laurent2517af32020-11-25 15:31:27 +01003613 auto newDevice = getNewInputDevice(activeDesc);
3614 // Force new input selection if the new device can not be reached via current input
3615 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3616 setInputDevice(activeDesc->mIoHandle, newDevice);
3617 } else {
3618 closeInput(activeDesc->mIoHandle);
3619 }
3620 }
3621}
3622
jiabin0a488932020-08-07 17:32:40 -07003623status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3624 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003625{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003626 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003627
jiabin0a488932020-08-07 17:32:40 -07003628 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003629 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003630 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3631 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003632 return status;
3633 }
3634
3635 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003636
3637 bool forceVolumeReeval = false;
3638 // FIXME: workaround for truncated touch sounds
3639 // to be removed when the problem is handled by system UI
3640 uint32_t delayMs = 0;
3641 if (strategy == mCommunnicationStrategy) {
3642 forceVolumeReeval = true;
3643 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3644 updateInputRouting();
3645 }
3646 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003647
3648 return NO_ERROR;
3649}
3650
jiabin0a488932020-08-07 17:32:40 -07003651status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3652 device_role_t role,
3653 AudioDeviceTypeAddrVector &devices) {
3654 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003655}
3656
Jiabin Huang3b98d322020-09-03 17:54:16 +00003657status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3658 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3659 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3660 dumpAudioDeviceTypeAddrVector(devices).c_str());
3661
Mikhail Naganov55773032020-10-01 15:08:13 -07003662 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003663 return BAD_VALUE;
3664 }
3665 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3666 ALOGW_IF(status != NO_ERROR,
3667 "Engine could not set preferred devices %s for audio source %d role %d",
3668 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3669
3670 return status;
3671}
3672
3673status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3674 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3675 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3676 dumpAudioDeviceTypeAddrVector(devices).c_str());
3677
Mikhail Naganov55773032020-10-01 15:08:13 -07003678 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003679 return BAD_VALUE;
3680 }
3681 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3682 ALOGW_IF(status != NO_ERROR,
3683 "Engine could not add preferred devices %s for audio source %d role %d",
3684 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3685
Eric Laurent2517af32020-11-25 15:31:27 +01003686 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003687 return status;
3688}
3689
3690status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3691 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3692{
3693 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3694 dumpAudioDeviceTypeAddrVector(devices).c_str());
3695
Mikhail Naganov55773032020-10-01 15:08:13 -07003696 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003697 return BAD_VALUE;
3698 }
3699
3700 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3701 audioSource, role, devices);
3702 ALOGW_IF(status != NO_ERROR,
3703 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3704
Eric Laurent2517af32020-11-25 15:31:27 +01003705 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003706 return status;
3707}
3708
3709status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3710 device_role_t role) {
3711 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3712
3713 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3714 ALOGW_IF(status != NO_ERROR,
3715 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3716
Eric Laurent2517af32020-11-25 15:31:27 +01003717 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003718 return status;
3719}
3720
3721status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3722 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3723 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3724}
3725
Oscar Azucena90e77632019-11-27 17:12:28 -08003726status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003727 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003728 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003729 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3730 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003731 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003732 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3733 if (status != NO_ERROR) {
3734 ALOGE("%s() could not set device affinity for userId %d",
3735 __FUNCTION__, userId);
3736 return status;
3737 }
3738
3739 // reevaluate outputs for all devices
3740 checkForDeviceAndOutputChanges();
3741 updateCallAndOutputRouting();
3742
3743 return NO_ERROR;
3744}
3745
3746status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003747 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003748 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3749 if (status != NO_ERROR) {
3750 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3751 __FUNCTION__, userId);
3752 return status;
3753 }
3754
3755 // reevaluate outputs for all devices
3756 checkForDeviceAndOutputChanges();
3757 updateCallAndOutputRouting();
3758
3759 return NO_ERROR;
3760}
3761
Andy Hungc29d82b2018-10-05 12:23:17 -07003762void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003763{
Andy Hungc29d82b2018-10-05 12:23:17 -07003764 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003765 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003766 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003767 std::string stateLiteral;
3768 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003769 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003770 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3771 "communications", "media", "record", "dock", "system",
3772 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3773 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3774 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003775 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3776 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3777 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3778 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3779 dst->append(" (MANUAL: ");
3780 dumpManualSurroundFormats(dst);
3781 dst->append(")");
3782 }
3783 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003784 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003785 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3786 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003787 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003788 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003789
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003790 dst->append("\n");
3791 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3792 dst->append("\n");
3793 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003794 mHwModulesAll.dump(dst);
3795 mOutputs.dump(dst);
3796 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003797 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003798 mAudioPatches.dump(dst);
3799 mPolicyMixes.dump(dst);
3800 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003801
Kevin Rocardb99cc752019-03-21 20:52:24 -07003802 dst->appendFormat(" AllowedCapturePolicies:\n");
3803 for (auto& policy : mAllowedCapturePolicies) {
3804 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3805 }
3806
François Gaffiec005e562018-11-06 15:04:49 +01003807 dst->appendFormat("\nPolicy Engine dump:\n");
3808 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003809}
3810
3811status_t AudioPolicyManager::dump(int fd)
3812{
3813 String8 result;
3814 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003815 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003816 return NO_ERROR;
3817}
3818
Kevin Rocardb99cc752019-03-21 20:52:24 -07003819status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3820{
3821 mAllowedCapturePolicies[uid] = capturePolicy;
3822 return NO_ERROR;
3823}
3824
Eric Laurente552edb2014-03-10 17:42:56 -07003825// This function checks for the parameters which can be offloaded.
3826// This can be enhanced depending on the capability of the DSP and policy
3827// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003828audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003829{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003830 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003831 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003832 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003833 offloadInfo.format,
3834 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3835 offloadInfo.has_video);
3836
jiabin2b9d5a12021-12-10 01:06:29 +00003837 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003838 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003839 }
3840
3841 // See if there is a profile to support this.
3842 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003843 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003844 offloadInfo.sample_rate,
3845 offloadInfo.format,
3846 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003847 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3848 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003849 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3850 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3851 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003852 if (profile == nullptr) {
3853 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3854 }
3855 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3856 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3857 }
3858 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003859}
3860
Michael Chana94fbb22018-04-24 14:31:19 +10003861bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3862 const audio_attributes_t& attributes) {
3863 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003864 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003865 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3866 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003867 config.sample_rate,
3868 config.format,
3869 config.channel_mask,
3870 output_flags,
3871 true /* directOnly */);
3872 ALOGV("%s() profile %sfound with name: %s, "
3873 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3874 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003875 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003876 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003877
3878 // also try the MSD module if compatible profile not found
3879 if (profile == nullptr) {
3880 profile = getMsdProfileForOutput(outputDevices,
3881 config.sample_rate,
3882 config.format,
3883 config.channel_mask,
3884 output_flags,
3885 true /* directOnly */);
3886 ALOGV("%s() MSD profile %sfound with name: %s, "
3887 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3888 __FUNCTION__, profile != 0 ? "" : "NOT ",
3889 (profile != 0 ? profile->getTagName().c_str() : "null"),
3890 config.sample_rate, config.format, config.channel_mask, output_flags);
3891 }
3892 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003893}
3894
jiabin2b9d5a12021-12-10 01:06:29 +00003895bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3896 bool durationIgnored) {
3897 if (mMasterMono) {
3898 return false; // no offloading if mono is set.
3899 }
3900
3901 // Check if offload has been disabled
3902 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3903 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3904 return false;
3905 }
3906
3907 // Check if stream type is music, then only allow offload as of now.
3908 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3909 {
3910 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3911 return false;
3912 }
3913
3914 //TODO: enable audio offloading with video when ready
3915 const bool allowOffloadWithVideo =
3916 property_get_bool("audio.offload.video", false /* default_value */);
3917 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3918 ALOGV("%s: has_video == true, returning false", __func__);
3919 return false;
3920 }
3921
3922 //If duration is less than minimum value defined in property, return false
3923 const int min_duration_secs = property_get_int32(
3924 "audio.offload.min.duration.secs", -1 /* default_value */);
3925 if (!durationIgnored) {
3926 if (min_duration_secs >= 0) {
3927 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3928 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3929 __func__, min_duration_secs);
3930 return false;
3931 }
3932 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3933 ALOGV("%s: Offload denied by duration < default min(=%u)",
3934 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3935 return false;
3936 }
3937 }
3938
3939 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3940 // creating an offloaded track and tearing it down immediately after start when audioflinger
3941 // detects there is an active non offloadable effect.
3942 // FIXME: We should check the audio session here but we do not have it in this context.
3943 // This may prevent offloading in rare situations where effects are left active by apps
3944 // in the background.
3945 if (mEffects.isNonOffloadableEffectEnabled()) {
3946 return false;
3947 }
3948
3949 return true;
3950}
3951
3952audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
3953 const audio_config_t *config) {
3954 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
3955 offloadInfo.format = config->format;
3956 offloadInfo.sample_rate = config->sample_rate;
3957 offloadInfo.channel_mask = config->channel_mask;
3958 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
3959 offloadInfo.has_video = false;
3960 offloadInfo.is_streaming = false;
3961 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
3962
3963 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
3964 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3965 audio_flags_to_audio_output_flags(attr->flags, &flags);
3966 // only retain flags that will drive compressed offload or passthrough
3967 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
3968 if (offloadPossible) {
3969 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
3970 }
3971 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
3972
Dorin Drimusfae3c642022-03-17 18:36:30 +01003973 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00003974 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01003975 DeviceVector outputDevices = engineOutputDevices;
3976 // the MSD module checks for different conditions and output devices
3977 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
3978 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
3979 continue;
3980 }
3981 outputDevices = getMsdAudioOutDevices();
3982 }
jiabin2b9d5a12021-12-10 01:06:29 +00003983 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00003984 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00003985 config->sample_rate, nullptr /*updatedSamplingRate*/,
3986 config->format, nullptr /*updatedFormat*/,
3987 config->channel_mask, nullptr /*updatedChannelMask*/,
3988 flags)) {
3989 continue;
3990 }
3991 // reject profiles not corresponding to a device currently available
3992 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
3993 continue;
3994 }
3995 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
3996 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00003997 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00003998 != AUDIO_DIRECT_NOT_SUPPORTED) {
3999 // Already reports offload gapless supported. No need to report offload support.
4000 continue;
4001 }
4002 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4003 != AUDIO_OUTPUT_FLAG_NONE) {
4004 // If offload gapless is reported, no need to report offload support.
4005 directMode = (audio_direct_mode_t) ((directMode &
4006 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4007 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4008 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004009 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004010 }
4011 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004012 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004013 }
4014 }
4015 }
4016 return directMode;
4017}
4018
Dorin Drimusf2196d82022-01-03 12:11:18 +01004019status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4020 AudioProfileVector& audioProfilesVector) {
4021 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004022 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004023 if (status != OK) {
4024 return status;
4025 }
4026 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4027 if (devices.empty()) {
4028 return OK; // no output devices for the attributes
4029 }
4030
4031 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004032 // the MSD module checks for different conditions
4033 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4034 continue;
4035 }
4036 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4037 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004038 continue;
4039 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004040 // allow only profiles that support all the available and routed devices
4041 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004042 != devices.size()) {
4043 continue;
4044 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004045 audioProfilesVector.addAllValidProfiles(
4046 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004047 }
4048 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004049
4050 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4051 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4052 if (msdModule != nullptr) {
4053 if (msdHasPatchesToAllDevices(devices)) {
4054 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4055 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4056 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4057 continue;
4058 }
4059 audioProfilesVector.addAllValidProfiles(
4060 outputProfile->asAudioPort()->getAudioProfiles());
4061 }
4062 } else {
4063 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4064 }
4065 }
4066
Dorin Drimusf2196d82022-01-03 12:11:18 +01004067 return NO_ERROR;
4068}
4069
Eric Laurent6a94d692014-05-20 11:18:06 -07004070status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4071 audio_port_type_t type,
4072 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004073 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004074 unsigned int *generation)
4075{
jiabin19cdba52020-11-24 11:28:58 -08004076 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4077 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004078 return BAD_VALUE;
4079 }
4080 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004081 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004082 *num_ports = 0;
4083 }
4084
4085 size_t portsWritten = 0;
4086 size_t portsMax = *num_ports;
4087 *num_ports = 0;
4088 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004089 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4090 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004091 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004092 for (const auto& dev : mAvailableOutputDevices) {
4093 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004094 continue;
4095 }
4096 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004097 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004098 }
4099 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004100 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004101 }
4102 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004103 for (const auto& dev : mAvailableInputDevices) {
4104 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004105 continue;
4106 }
4107 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004108 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004109 }
4110 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004111 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004112 }
4113 }
4114 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4115 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4116 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4117 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4118 }
4119 *num_ports += mInputs.size();
4120 }
4121 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004122 size_t numOutputs = 0;
4123 for (size_t i = 0; i < mOutputs.size(); i++) {
4124 if (!mOutputs[i]->isDuplicated()) {
4125 numOutputs++;
4126 if (portsWritten < portsMax) {
4127 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4128 }
4129 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004130 }
Eric Laurent84c70242014-06-23 08:46:27 -07004131 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004132 }
4133 }
4134 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004135 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004136 return NO_ERROR;
4137}
4138
jiabin19cdba52020-11-24 11:28:58 -08004139status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004140{
Eric Laurent99fcae42018-05-17 16:59:18 -07004141 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4142 return BAD_VALUE;
4143 }
4144 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4145 if (dev != 0) {
4146 dev->toAudioPort(port);
4147 return NO_ERROR;
4148 }
4149 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4150 if (dev != 0) {
4151 dev->toAudioPort(port);
4152 return NO_ERROR;
4153 }
4154 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4155 if (out != 0) {
4156 out->toAudioPort(port);
4157 return NO_ERROR;
4158 }
4159 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4160 if (in != 0) {
4161 in->toAudioPort(port);
4162 return NO_ERROR;
4163 }
4164 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004165}
4166
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004167status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4168 audio_patch_handle_t *handle,
4169 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004170{
François Gaffieafd4cea2019-11-18 15:50:22 +01004171 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004172 if (handle == NULL || patch == NULL) {
4173 return BAD_VALUE;
4174 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004175 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004176 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004177 return BAD_VALUE;
4178 }
4179 // only one source per audio patch supported for now
4180 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004181 return INVALID_OPERATION;
4182 }
Eric Laurent874c42872014-08-08 15:13:39 -07004183 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004184 return INVALID_OPERATION;
4185 }
Eric Laurent874c42872014-08-08 15:13:39 -07004186 for (size_t i = 0; i < patch->num_sinks; i++) {
4187 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4188 return INVALID_OPERATION;
4189 }
4190 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004191
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004192 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4193 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4194 if (srcDevice == nullptr || sinkDevice == nullptr) {
4195 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4196 return BAD_VALUE;
4197 }
4198 ALOGV("%s between source %s and sink %s", __func__,
4199 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4200 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4201 // Default attributes, default volume priority, not to infer with non raw audio patches.
4202 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4203 const struct audio_port_config *source = &patch->sources[0];
4204 sp<SourceClientDescriptor> sourceDesc =
4205 new InternalSourceClientDescriptor(
4206 portId, uid, attributes, *source, srcDevice, sinkDevice,
4207 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4208
4209 status_t status =
4210 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4211
4212 if (status != NO_ERROR) {
4213 return INVALID_OPERATION;
4214 }
4215 mAudioSources.add(portId, sourceDesc);
4216 return NO_ERROR;
4217}
4218
4219status_t AudioPolicyManager::connectAudioSourceToSink(
4220 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4221 const struct audio_patch *patch,
4222 audio_patch_handle_t &handle,
4223 uid_t uid, uint32_t delayMs)
4224{
4225 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4226 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4227 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4228 return INVALID_OPERATION;
4229 }
4230 sourceDesc->connect(handle, sinkDevice);
4231 if (isMsdPatch(handle)) {
4232 return NO_ERROR;
4233 }
4234 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4235 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4236 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4237 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4238 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4239 goto FailurePatchAdded;
4240 }
4241 status = swOutput->start();
4242 if (status != NO_ERROR) {
4243 goto FailureSourceAdded;
4244 }
4245 swOutput->addClient(sourceDesc);
4246 status = startSource(swOutput, sourceDesc, &delayMs);
4247 if (status != NO_ERROR) {
4248 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4249 goto FailureSourceActive;
4250 }
4251 if (delayMs != 0) {
4252 usleep(delayMs * 1000);
4253 }
4254 return NO_ERROR;
4255
4256FailureSourceActive:
4257 swOutput->stop();
4258 releaseOutput(sourceDesc->portId());
4259FailureSourceAdded:
4260 sourceDesc->setSwOutput(nullptr);
4261FailurePatchAdded:
4262 releaseAudioPatchInternal(handle);
4263 return INVALID_OPERATION;
4264}
4265
4266status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4267 audio_patch_handle_t *handle,
4268 uid_t uid, uint32_t delayMs,
4269 const sp<SourceClientDescriptor>& sourceDesc)
4270{
4271 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004272 sp<AudioPatch> patchDesc;
4273 ssize_t index = mAudioPatches.indexOfKey(*handle);
4274
François Gaffieafd4cea2019-11-18 15:50:22 +01004275 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4276 patch->sources[0].role,
4277 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004278#if LOG_NDEBUG == 0
4279 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004280 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4281 patch->sinks[i].role,
4282 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004283 }
4284#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004285
4286 if (index >= 0) {
4287 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004288 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4289 __func__, mUidCached, patchDesc->getUid(), uid);
4290 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004291 return INVALID_OPERATION;
4292 }
4293 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004294 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004295 }
4296
4297 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004298 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004299 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004300 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004301 return BAD_VALUE;
4302 }
Eric Laurent84c70242014-06-23 08:46:27 -07004303 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4304 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004305 if (patchDesc != 0) {
4306 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004307 ALOGV("%s source id differs for patch current id %d new id %d",
4308 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004309 return BAD_VALUE;
4310 }
4311 }
Eric Laurent874c42872014-08-08 15:13:39 -07004312 DeviceVector devices;
4313 for (size_t i = 0; i < patch->num_sinks; i++) {
4314 // Only support mix to devices connection
4315 // TODO add support for mix to mix connection
4316 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004317 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004318 return INVALID_OPERATION;
4319 }
4320 sp<DeviceDescriptor> devDesc =
4321 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4322 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004323 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004324 return BAD_VALUE;
4325 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004326
François Gaffie11d30102018-11-02 16:09:09 +01004327 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004328 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004329 NULL, // updatedSamplingRate
4330 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004331 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004332 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004333 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004334 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004335 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004336 return INVALID_OPERATION;
4337 }
4338 devices.add(devDesc);
4339 }
4340 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004341 return INVALID_OPERATION;
4342 }
Eric Laurent874c42872014-08-08 15:13:39 -07004343
Eric Laurent6a94d692014-05-20 11:18:06 -07004344 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004345 ALOGV("%s setting device %s on output %d",
4346 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004347 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004348 index = mAudioPatches.indexOfKey(*handle);
4349 if (index >= 0) {
4350 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004351 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004352 }
4353 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004354 patchDesc->setUid(uid);
4355 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004356 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004357 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004358 return INVALID_OPERATION;
4359 }
4360 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4361 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4362 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004363 // only one sink supported when connecting an input device to a mix
4364 if (patch->num_sinks > 1) {
4365 return INVALID_OPERATION;
4366 }
François Gaffie53615e22015-03-19 09:24:12 +01004367 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004368 if (inputDesc == NULL) {
4369 return BAD_VALUE;
4370 }
4371 if (patchDesc != 0) {
4372 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4373 return BAD_VALUE;
4374 }
4375 }
François Gaffie11d30102018-11-02 16:09:09 +01004376 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004377 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004378 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004379 return BAD_VALUE;
4380 }
4381
François Gaffie11d30102018-11-02 16:09:09 +01004382 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004383 patch->sinks[0].sample_rate,
4384 NULL, /*updatedSampleRate*/
4385 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004386 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004387 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004388 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004389 // FIXME for the parameter type,
4390 // and the NONE
4391 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004392 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004393 return INVALID_OPERATION;
4394 }
4395 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004396 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004397 device->toString().c_str(), inputDesc->mIoHandle);
4398 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004399 index = mAudioPatches.indexOfKey(*handle);
4400 if (index >= 0) {
4401 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004402 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004403 }
4404 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004405 patchDesc->setUid(uid);
4406 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004407 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004408 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004409 return INVALID_OPERATION;
4410 }
4411 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4412 // device to device connection
4413 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004414 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004415 return BAD_VALUE;
4416 }
4417 }
François Gaffie11d30102018-11-02 16:09:09 +01004418 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004419 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004420 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004421 return BAD_VALUE;
4422 }
Eric Laurent874c42872014-08-08 15:13:39 -07004423
Eric Laurent6a94d692014-05-20 11:18:06 -07004424 //update source and sink with our own data as the data passed in the patch may
4425 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004426 PatchBuilder patchBuilder;
4427 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004428
4429 // if first sink is to MSD, establish single MSD patch
4430 if (getMsdAudioOutDevices().contains(
4431 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4432 ALOGV("%s patching to MSD", __FUNCTION__);
4433 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4434 goto installPatch;
4435 }
4436
François Gaffieafd4cea2019-11-18 15:50:22 +01004437 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4438 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004439
Eric Laurent874c42872014-08-08 15:13:39 -07004440 for (size_t i = 0; i < patch->num_sinks; i++) {
4441 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004442 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004443 return INVALID_OPERATION;
4444 }
François Gaffie11d30102018-11-02 16:09:09 +01004445 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004446 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004447 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004448 return BAD_VALUE;
4449 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004450 audio_port_config sinkPortConfig = {};
4451 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4452 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004453
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004454 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4455 // volume management purpose (tracking activity)
4456 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4457 // in config XML to reach the sink so that is can be declared as available.
4458 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4459 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004460 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004461 // take care of dynamic routing for SwOutput selection,
4462 audio_attributes_t attributes = sourceDesc->attributes();
4463 audio_stream_type_t stream = sourceDesc->stream();
4464 audio_attributes_t resultAttr;
4465 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4466 config.sample_rate = sourceDesc->config().sample_rate;
4467 config.channel_mask = sourceDesc->config().channel_mask;
4468 config.format = sourceDesc->config().format;
4469 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4470 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4471 bool isRequestedDeviceForExclusiveUse = false;
4472 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004473 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004474 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4475 &stream, sourceDesc->uid(), &config, &flags,
4476 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004477 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004478 if (output == AUDIO_IO_HANDLE_NONE) {
4479 ALOGV("%s no output for device %s",
4480 __FUNCTION__, sinkDevice->toString().c_str());
4481 return INVALID_OPERATION;
4482 }
4483 outputDesc = mOutputs.valueFor(output);
4484 if (outputDesc->isDuplicated()) {
4485 ALOGE("%s output is duplicated", __func__);
4486 return INVALID_OPERATION;
4487 }
4488 sourceDesc->setSwOutput(outputDesc);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004489 } else {
4490 // Same for "raw patches" aka created from createAudioPatch API
4491 SortedVector<audio_io_handle_t> outputs =
4492 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4493 // if the sink device is reachable via an opened output stream, request to
4494 // go via this output stream by adding a second source to the patch
4495 // description
4496 output = selectOutput(outputs);
4497 if (output == AUDIO_IO_HANDLE_NONE) {
4498 ALOGE("%s no output available for internal patch sink", __func__);
4499 return INVALID_OPERATION;
4500 }
4501 outputDesc = mOutputs.valueFor(output);
4502 if (outputDesc->isDuplicated()) {
4503 ALOGV("%s output for device %s is duplicated",
4504 __func__, sinkDevice->toString().c_str());
4505 return INVALID_OPERATION;
4506 }
4507 sourceDesc->setSwOutput(outputDesc);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004508 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004509 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004510 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004511 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004512 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004513 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4514 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004515 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4516 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004517 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004518 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004519 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004520 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004521 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004522 return INVALID_OPERATION;
4523 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004524 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004525 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004526 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004527 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004528 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004529 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4530 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4531 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004532 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004533 }
Eric Laurent83b88082014-06-20 18:31:16 -07004534 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004535 }
4536 // TODO: check from routing capabilities in config file and other conflicting patches
4537
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004538installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004539 status_t status = installPatch(
4540 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004541 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004542 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004543 return INVALID_OPERATION;
4544 }
4545 } else {
4546 return BAD_VALUE;
4547 }
4548 } else {
4549 return BAD_VALUE;
4550 }
4551 return NO_ERROR;
4552}
4553
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004554status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004555{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004556 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004557 ssize_t index = mAudioPatches.indexOfKey(handle);
4558
4559 if (index < 0) {
4560 return BAD_VALUE;
4561 }
4562 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004563 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4564 __func__, mUidCached, patchDesc->getUid(), uid);
4565 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004566 return INVALID_OPERATION;
4567 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004568 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4569 for (size_t i = 0; i < mAudioSources.size(); i++) {
4570 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4571 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4572 portId = sourceDesc->portId();
4573 break;
4574 }
4575 }
4576 return portId != AUDIO_PORT_HANDLE_NONE ?
4577 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004578}
Eric Laurent6a94d692014-05-20 11:18:06 -07004579
François Gaffieafd4cea2019-11-18 15:50:22 +01004580status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004581 uint32_t delayMs,
4582 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004583{
4584 ALOGV("%s patch %d", __func__, handle);
4585 if (mAudioPatches.indexOfKey(handle) < 0) {
4586 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4587 return BAD_VALUE;
4588 }
4589 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004590 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004591 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004592 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004593 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004594 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004595 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004596 return BAD_VALUE;
4597 }
4598
François Gaffie11d30102018-11-02 16:09:09 +01004599 setOutputDevices(outputDesc,
4600 getNewOutputDevices(outputDesc, true /*fromCache*/),
4601 true,
4602 0,
4603 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004604 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4605 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004606 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004607 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004608 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004609 return BAD_VALUE;
4610 }
4611 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004612 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004613 true,
4614 NULL);
4615 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004616 status_t status =
4617 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4618 ALOGV("%s patch panel returned %d patchHandle %d",
4619 __func__, status, patchDesc->getAfHandle());
4620 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004621 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004622 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004623 // SW or HW Bridge
4624 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4625 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004626 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004627 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4628 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4629 outputDesc = sourceDesc->swOutput().promote();
4630 }
4631 if (outputDesc == nullptr) {
4632 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4633 // releaseOutput has already called closeOutput in case of direct output
4634 return NO_ERROR;
4635 }
4636 if (!outputDesc->isActive() && !sourceDesc->useSwBridge()) {
4637 resetOutputDevice(outputDesc);
4638 } else {
4639 // Reuse patch handle if still valid / do not force rerouting if still routed
4640 patchHandle = outputDesc->getPatchHandle();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004641 setOutputDevices(outputDesc,
4642 getNewOutputDevices(outputDesc, true /*fromCache*/),
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004643 patchHandle == AUDIO_PATCH_HANDLE_NONE, /*force*/
Francois Gaffie7feb8542020-04-06 17:39:47 +02004644 0,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004645 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Francois Gaffie7feb8542020-04-06 17:39:47 +02004646 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004647 } else {
4648 return BAD_VALUE;
4649 }
4650 } else {
4651 return BAD_VALUE;
4652 }
4653 return NO_ERROR;
4654}
4655
4656status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4657 struct audio_patch *patches,
4658 unsigned int *generation)
4659{
François Gaffie53615e22015-03-19 09:24:12 +01004660 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004661 return BAD_VALUE;
4662 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004663 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004664 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004665}
4666
Eric Laurente1715a42014-05-20 11:30:42 -07004667status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004668{
Eric Laurente1715a42014-05-20 11:30:42 -07004669 ALOGV("setAudioPortConfig()");
4670
4671 if (config == NULL) {
4672 return BAD_VALUE;
4673 }
4674 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4675 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004676 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4677 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004678 }
4679
Eric Laurenta121f902014-06-03 13:32:54 -07004680 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004681 if (config->type == AUDIO_PORT_TYPE_MIX) {
4682 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004683 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004684 if (outputDesc == NULL) {
4685 return BAD_VALUE;
4686 }
Eric Laurent84c70242014-06-23 08:46:27 -07004687 ALOG_ASSERT(!outputDesc->isDuplicated(),
4688 "setAudioPortConfig() called on duplicated output %d",
4689 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004690 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004691 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004692 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004693 if (inputDesc == NULL) {
4694 return BAD_VALUE;
4695 }
Eric Laurenta121f902014-06-03 13:32:54 -07004696 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004697 } else {
4698 return BAD_VALUE;
4699 }
4700 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4701 sp<DeviceDescriptor> deviceDesc;
4702 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4703 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4704 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4705 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4706 } else {
4707 return BAD_VALUE;
4708 }
4709 if (deviceDesc == NULL) {
4710 return BAD_VALUE;
4711 }
Eric Laurenta121f902014-06-03 13:32:54 -07004712 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004713 } else {
4714 return BAD_VALUE;
4715 }
4716
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004717 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004718 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4719 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004720 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004721 audioPortConfig->toAudioPortConfig(&newConfig, config);
4722 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004723 }
Eric Laurenta121f902014-06-03 13:32:54 -07004724 if (status != NO_ERROR) {
4725 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004726 }
Eric Laurente1715a42014-05-20 11:30:42 -07004727
4728 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004729}
4730
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004731void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4732{
Eric Laurentd60560a2015-04-10 11:31:20 -07004733 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004734 clearAudioPatches(uid);
4735 clearSessionRoutes(uid);
4736}
4737
Eric Laurent6a94d692014-05-20 11:18:06 -07004738void AudioPolicyManager::clearAudioPatches(uid_t uid)
4739{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004740 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004741 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004742 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004743 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 }
4745 }
4746}
4747
François Gaffiec005e562018-11-06 15:04:49 +01004748void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004749{
François Gaffiec005e562018-11-06 15:04:49 +01004750 // Take the first attributes following the product strategy as it is used to retrieve the routed
4751 // device. All attributes wihin a strategy follows the same "routing strategy"
4752 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4753 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004754 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004755 for (size_t j = 0; j < mOutputs.size(); j++) {
4756 if (mOutputs.keyAt(j) == ouptutToSkip) {
4757 continue;
4758 }
4759 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004760 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004761 continue;
4762 }
4763 // If the default device for this strategy is on another output mix,
4764 // invalidate all tracks in this strategy to force re connection.
4765 // Otherwise select new device on the output mix.
4766 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004767 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4768 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004769 }
4770 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004771 setOutputDevices(
4772 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004773 }
4774 }
4775}
4776
4777void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4778{
4779 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004780 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004781 for (size_t i = 0; i < mOutputs.size(); i++) {
4782 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004783 for (const auto& client : outputDesc->getClientIterable()) {
4784 if (client->hasPreferredDevice() && client->uid() == uid) {
4785 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004786 auto clientStrategy = client->strategy();
4787 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4788 end(affectedStrategies)) {
4789 continue;
4790 }
4791 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004792 }
4793 }
4794 }
4795 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004796 for (const auto& strategy : affectedStrategies) {
4797 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004798 }
4799
4800 // remove input routes associated with this uid
4801 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004802 for (size_t i = 0; i < mInputs.size(); i++) {
4803 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004804 for (const auto& client : inputDesc->getClientIterable()) {
4805 if (client->hasPreferredDevice() && client->uid() == uid) {
4806 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4807 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004808 }
4809 }
4810 }
4811 // reroute inputs if necessary
4812 SortedVector<audio_io_handle_t> inputsToClose;
4813 for (size_t i = 0; i < mInputs.size(); i++) {
4814 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004815 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004816 inputsToClose.add(inputDesc->mIoHandle);
4817 }
4818 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004819 for (const auto& input : inputsToClose) {
4820 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004821 }
4822}
4823
Eric Laurentd60560a2015-04-10 11:31:20 -07004824void AudioPolicyManager::clearAudioSources(uid_t uid)
4825{
4826 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004827 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4828 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004829 stopAudioSource(mAudioSources.keyAt(i));
4830 }
4831 }
4832}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004833
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004834status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4835 audio_io_handle_t *ioHandle,
4836 audio_devices_t *device)
4837{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004838 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4839 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004840 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004841 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004842
François Gaffiedf372692015-03-19 10:43:27 +01004843 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004844}
4845
Eric Laurentd60560a2015-04-10 11:31:20 -07004846status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004847 const audio_attributes_t *attributes,
4848 audio_port_handle_t *portId,
4849 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004850{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004851 ALOGV("%s", __FUNCTION__);
4852 *portId = AUDIO_PORT_HANDLE_NONE;
4853
4854 if (source == NULL || attributes == NULL || portId == NULL) {
4855 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4856 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004857 return BAD_VALUE;
4858 }
4859
Eric Laurentd60560a2015-04-10 11:31:20 -07004860 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4861 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004862 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4863 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004864 return INVALID_OPERATION;
4865 }
4866
François Gaffie11d30102018-11-02 16:09:09 +01004867 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004868 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004869 String8(source->ext.device.address),
4870 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004871 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004872 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004873 return BAD_VALUE;
4874 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004875
jiabin4ef93452019-09-10 14:29:54 -07004876 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004877
François Gaffieaaac0fd2018-11-22 17:56:39 +01004878 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004879 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004880 mEngine->getStreamTypeForAttributes(*attributes),
4881 mEngine->getProductStrategyForAttributes(*attributes),
4882 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004883
4884 status_t status = connectAudioSource(sourceDesc);
4885 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004886 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004887 }
4888 return status;
4889}
4890
Francois Gaffie601801d2021-06-22 13:27:39 +02004891sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4892 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4893{
4894 ALOGV("%s", __FUNCTION__);
4895 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4896
4897 status_t status = startAudioSource(source, attributes, &portId, uid);
4898 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4899 return mAudioSources.valueFor(portId);
4900}
4901
4902
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004903status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004904{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004905 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004906
4907 // make sure we only have one patch per source.
4908 disconnectAudioSource(sourceDesc);
4909
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004910 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004911 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4912 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4913 sourceDesc->srcDevice()->type(),
4914 String8(sourceDesc->srcDevice()->address().c_str()),
4915 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004916 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004917 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004918 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004919 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004920 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4921 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4922 return INVALID_OPERATION;
4923 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004924 PatchBuilder patchBuilder;
4925 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4926 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01004927
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004928 return connectAudioSourceToSink(
4929 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07004930}
4931
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004932status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004933{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004934 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4935 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004936 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004937 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004938 return BAD_VALUE;
4939 }
4940 status_t status = disconnectAudioSource(sourceDesc);
4941
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004942 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004943 return status;
4944}
4945
Andy Hung2ddee192015-12-18 17:34:44 -08004946status_t AudioPolicyManager::setMasterMono(bool mono)
4947{
4948 if (mMasterMono == mono) {
4949 return NO_ERROR;
4950 }
4951 mMasterMono = mono;
4952 // if enabling mono we close all offloaded devices, which will invalidate the
4953 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4954 // for recreating the new AudioTrack as non-offloaded PCM.
4955 //
4956 // If disabling mono, we leave all tracks as is: we don't know which clients
4957 // and tracks are able to be recreated as offloaded. The next "song" should
4958 // play back offloaded.
4959 if (mMasterMono) {
4960 Vector<audio_io_handle_t> offloaded;
4961 for (size_t i = 0; i < mOutputs.size(); ++i) {
4962 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4963 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4964 offloaded.push(desc->mIoHandle);
4965 }
4966 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004967 for (const auto& handle : offloaded) {
4968 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004969 }
4970 }
4971 // update master mono for all remaining outputs
4972 for (size_t i = 0; i < mOutputs.size(); ++i) {
4973 updateMono(mOutputs.keyAt(i));
4974 }
4975 return NO_ERROR;
4976}
4977
4978status_t AudioPolicyManager::getMasterMono(bool *mono)
4979{
4980 *mono = mMasterMono;
4981 return NO_ERROR;
4982}
4983
Eric Laurentac9cef52017-06-09 15:46:26 -07004984float AudioPolicyManager::getStreamVolumeDB(
4985 audio_stream_type_t stream, int index, audio_devices_t device)
4986{
jiabin9a3361e2019-10-01 09:38:30 -07004987 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004988}
4989
jiabin81772902018-04-02 17:52:27 -07004990status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4991 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004992 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004993{
Kriti Dang6537def2021-03-02 13:46:59 +01004994 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4995 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004996 return BAD_VALUE;
4997 }
Kriti Dang6537def2021-03-02 13:46:59 +01004998 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4999 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005000
5001 size_t formatsWritten = 0;
5002 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005003
Kriti Dang6537def2021-03-02 13:46:59 +01005004 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005005 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5006 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005007 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005008 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005009 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005010 bool formatEnabled = true;
5011 switch (forceUse) {
5012 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005013 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005014 break;
5015 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5016 formatEnabled = false;
5017 break;
5018 default: // AUTO or ALWAYS => true
5019 break;
jiabin81772902018-04-02 17:52:27 -07005020 }
5021 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5022 }
jiabin81772902018-04-02 17:52:27 -07005023 }
5024 return NO_ERROR;
5025}
5026
Kriti Dang6537def2021-03-02 13:46:59 +01005027status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5028 audio_format_t *surroundFormats) {
5029 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5030 return BAD_VALUE;
5031 }
5032 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5033 __func__, *numSurroundFormats, surroundFormats);
5034
5035 size_t formatsWritten = 0;
5036 size_t formatsMax = *numSurroundFormats;
5037 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5038
5039 // Return formats from all device profiles that have already been resolved by
5040 // checkOutputsForDevice().
5041 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5042 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5043 audio_devices_t deviceType = device->type();
5044 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5045 // returns formats reported by HDMI devices.
5046 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5047 continue;
5048 }
5049 // Formats reported by sink devices
5050 std::unordered_set<audio_format_t> formatset;
5051 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5052 formatset.insert(it->second.begin(), it->second.end());
5053 }
5054
5055 // Formats hard-coded in the in policy configuration file (if any).
5056 FormatVector encodedFormats = device->encodedFormats();
5057 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5058 // Filter the formats which are supported by the vendor hardware.
5059 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5060 if (mConfig.getSurroundFormats().count(*it) != 0) {
5061 formats.insert(*it);
5062 } else {
5063 for (const auto& pair : mConfig.getSurroundFormats()) {
5064 if (pair.second.count(*it) != 0) {
5065 formats.insert(pair.first);
5066 break;
5067 }
5068 }
5069 }
5070 }
5071 }
5072 *numSurroundFormats = formats.size();
5073 for (const auto& format: formats) {
5074 if (formatsWritten < formatsMax) {
5075 surroundFormats[formatsWritten++] = format;
5076 }
5077 }
5078 return NO_ERROR;
5079}
5080
jiabin81772902018-04-02 17:52:27 -07005081status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5082{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005083 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005084 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5085 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005086 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005087 return BAD_VALUE;
5088 }
5089
Mikhail Naganov100f0122018-11-29 11:22:16 -08005090 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5091 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005092 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005093 return INVALID_OPERATION;
5094 }
5095
Mikhail Naganov100f0122018-11-29 11:22:16 -08005096 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005097 return NO_ERROR;
5098 }
5099
Mikhail Naganov100f0122018-11-29 11:22:16 -08005100 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005101 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005102 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005103 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005104 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005105 }
5106 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005107 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005108 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005109 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005110 }
5111 }
5112
5113 sp<SwAudioOutputDescriptor> outputDesc;
5114 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005115 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5116 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005117 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5118 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005119 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005120 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005121 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5122 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5123 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005124 name.c_str(),
5125 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005126 if (status != NO_ERROR) {
5127 continue;
5128 }
5129 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5130 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5131 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005132 name.c_str(),
5133 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005134 profileUpdated |= (status == NO_ERROR);
5135 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005136 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005137 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005138 AUDIO_DEVICE_IN_HDMI);
5139 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5140 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005141 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005142 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005143 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5144 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5145 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005146 name.c_str(),
5147 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005148 if (status != NO_ERROR) {
5149 continue;
5150 }
5151 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5152 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5153 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005154 name.c_str(),
5155 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005156 profileUpdated |= (status == NO_ERROR);
5157 }
5158
jiabin81772902018-04-02 17:52:27 -07005159 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005160 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005161 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005162 }
5163
5164 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5165}
5166
Eric Laurent5ada82e2019-08-29 17:53:54 -07005167void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005168{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005169 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005170 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005171 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005172 }
5173}
5174
jiabin6012f912018-11-02 17:06:30 -07005175bool AudioPolicyManager::isHapticPlaybackSupported()
5176{
5177 for (const auto& hwModule : mHwModules) {
5178 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5179 for (const auto &outProfile : outputProfiles) {
5180 struct audio_port audioPort;
5181 outProfile->toAudioPort(&audioPort);
5182 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5183 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5184 return true;
5185 }
5186 }
5187 }
5188 }
5189 return false;
5190}
5191
Carter Hsu325a8eb2022-01-19 19:56:51 +08005192bool AudioPolicyManager::isUltrasoundSupported()
5193{
5194 bool hasUltrasoundOutput = false;
5195 bool hasUltrasoundInput = false;
5196 for (const auto& hwModule : mHwModules) {
5197 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5198 if (!hasUltrasoundOutput) {
5199 for (const auto &outProfile : outputProfiles) {
5200 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5201 hasUltrasoundOutput = true;
5202 break;
5203 }
5204 }
5205 }
5206
5207 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5208 if (!hasUltrasoundInput) {
5209 for (const auto &inputProfile : inputProfiles) {
5210 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5211 hasUltrasoundInput = true;
5212 break;
5213 }
5214 }
5215 }
5216
5217 if (hasUltrasoundOutput && hasUltrasoundInput)
5218 return true;
5219 }
5220 return false;
5221}
5222
Eric Laurent8340e672019-11-06 11:01:08 -08005223bool AudioPolicyManager::isCallScreenModeSupported()
5224{
5225 return getConfig().isCallScreenModeSupported();
5226}
5227
5228
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005229status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005230{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005231 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005232 if (!sourceDesc->isConnected()) {
5233 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5234 return NO_ERROR;
5235 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005236 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5237 if (swOutput != 0) {
5238 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005239 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005240 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005241 }
jiabinbce0c1d2020-10-05 11:20:18 -07005242 if (releaseOutput(sourceDesc->portId())) {
5243 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5244 // no need to release audio patch here but just return NO_ERROR.
5245 return NO_ERROR;
5246 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005247 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005248 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005249 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005250 // close Hwoutput and remove from mHwOutputs
5251 } else {
5252 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5253 }
5254 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005255 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005256 sourceDesc->disconnect();
5257 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005258}
5259
François Gaffiec005e562018-11-06 15:04:49 +01005260sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5261 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005262{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005263 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005264 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005265 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005266 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005267 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5268 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005269 source = sourceDesc;
5270 break;
5271 }
5272 }
5273 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005274}
5275
Eric Laurent39095982021-08-24 18:29:27 +02005276/* static */
5277bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
5278 switch (channels) {
5279 case AUDIO_CHANNEL_OUT_5POINT1:
5280 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
5281 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
5282 case AUDIO_CHANNEL_OUT_7POINT1:
5283 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
5284 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
5285 return true;
5286 default:
5287 return false;
5288 }
5289}
5290
Eric Laurentb4f42a92022-01-17 17:37:31 +01005291bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005292 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005293 const AudioDeviceTypeAddrVector &devices,
5294 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005295{
5296 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5297 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005298 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005299 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005300 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5301 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5302 return false;
5303 }
5304 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5305 return false;
5306 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005307 }
5308
5309 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005310 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5311 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005312 // to the specified devices must exist.
5313 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005314 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005315 if (profile == nullptr) {
5316 return false;
5317 }
5318
5319 // The caller can have the audio config criteria ignored by either passing a null ptr or
5320 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005321 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005322 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005323 // If the spatializer output is already opened, only channel masks included in the
5324 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005325
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005326 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005327 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005328 return false;
5329 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005330 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5331 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005332 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005333 != config->channel_mask) {
5334 return false;
5335 }
5336 }
5337 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005338 return true;
5339}
5340
5341void AudioPolicyManager::checkVirtualizerClientRoutes() {
5342 std::set<audio_stream_type_t> streamsToInvalidate;
5343 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005344 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5345 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005346 audio_attributes_t attr = client->attributes();
5347 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5348 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5349 audio_config_base_t clientConfig = client->config();
5350 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005351 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005352 && canBeSpatializedInt(&attr, &config,
5353 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005354 streamsToInvalidate.insert(client->stream());
5355 }
5356 }
5357 }
5358
5359 for (audio_stream_type_t stream : streamsToInvalidate) {
5360 mpClientInterface->invalidateStream(stream);
5361 }
5362}
5363
Eric Laurentfa0f6742021-08-17 18:39:44 +02005364status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005365 const audio_attributes_t *attr,
5366 audio_io_handle_t *output) {
5367 *output = AUDIO_IO_HANDLE_NONE;
5368
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005369 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5370 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5371 audio_config_t *configPtr = nullptr;
5372 audio_config_t config;
5373 if (mixerConfig != nullptr) {
5374 config = audio_config_initializer(mixerConfig);
5375 configPtr = &config;
5376 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005377 if (!canBeSpatializedInt(
5378 attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02005379 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005380 return BAD_VALUE;
5381 }
5382
5383 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005384 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005385 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005386 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005387 return BAD_VALUE;
5388 }
5389
Eric Laurent39095982021-08-24 18:29:27 +02005390 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
5391 && configPtr != nullptr
5392 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
5393 *output = mSpatializerOutput->mIoHandle;
5394 ALOGV("%s returns current spatializer output %d", __func__, *output);
5395 return NO_ERROR;
5396 }
5397 mSpatializerOutput.clear();
5398 for (size_t i = 0; i < mOutputs.size(); i++) {
5399 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5400 if (!desc->isDuplicated() && desc->mProfile == profile) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005401 ALOGV("%s found output %d for spatializer profile", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005402 mSpatializerOutput = desc;
5403 break;
5404 }
5405 }
5406 if (mSpatializerOutput == nullptr) {
5407 ALOGW("%s no opened spatializer output for profile %s",
5408 __func__, profile->getName().c_str());
5409 return BAD_VALUE;
5410 }
5411
5412 if (configPtr != nullptr
5413 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5414 audio_config_base_t savedMixerConfig = {
5415 .sample_rate = mSpatializerOutput->getSamplingRate(),
5416 .format = mSpatializerOutput->getFormat(),
5417 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5418 };
5419 DeviceVector savedDevices = mSpatializerOutput->devices();
5420
Eric Laurentb4f42a92022-01-17 17:37:31 +01005421 ALOGV("%s reopening spatializer output to match channel mask %#x (current mask %#x)",
5422 __func__, configPtr->channel_mask, mSpatializerOutput->mMixerChannelMask);
Eric Laurent39095982021-08-24 18:29:27 +02005423
Eric Laurentb4f42a92022-01-17 17:37:31 +01005424 closeOutput(mSpatializerOutput->mIoHandle);
5425 //from now on mSpatializerOutput is null
5426
5427 sp<SwAudioOutputDescriptor> desc =
5428 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
5429 if (desc == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005430 // re open the spatializer output with previous channel mask
Eric Laurentb4f42a92022-01-17 17:37:31 +01005431 desc = openOutputWithProfileAndDevice(profile, savedDevices, &savedMixerConfig);
5432 if (desc == nullptr) {
5433 ALOGE("%s failed to restore mSpatializerOutput with previous config", __func__);
Eric Laurent39095982021-08-24 18:29:27 +02005434 } else {
5435 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005436 }
5437 mPreviousOutputs = mOutputs;
5438 mpClientInterface->onAudioPortListUpdate();
5439 *output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005440 ALOGW("%s could not open spatializer output with requested config", __func__);
5441 return BAD_VALUE;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005442 }
Eric Laurent39095982021-08-24 18:29:27 +02005443 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005444 mPreviousOutputs = mOutputs;
5445 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005446 }
5447
5448 checkVirtualizerClientRoutes();
5449
Eric Laurent39095982021-08-24 18:29:27 +02005450 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005451 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005452 return NO_ERROR;
5453}
5454
Eric Laurentfa0f6742021-08-17 18:39:44 +02005455status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5456 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005457 return INVALID_OPERATION;
5458 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005459 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005460 return BAD_VALUE;
5461 }
Eric Laurent39095982021-08-24 18:29:27 +02005462
Eric Laurentfa0f6742021-08-17 18:39:44 +02005463 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005464
5465 checkVirtualizerClientRoutes();
5466
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005467 return NO_ERROR;
5468}
5469
Eric Laurente552edb2014-03-10 17:42:56 -07005470// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005471// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005472// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005473uint32_t AudioPolicyManager::nextAudioPortGeneration()
5474{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005475 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005476}
5477
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005478static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005479 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5480 !audioPolicyXmlConfigFile.empty()) {
5481 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5482 if (ret == NO_ERROR) {
5483 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005484 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005485 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005486 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005487 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005488}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005489
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005490AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5491 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005492 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005493 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005494 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005495 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005496 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005497 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005498 mAudioPortGeneration(1),
5499 mBeaconMuteRefCount(0),
5500 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005501 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005502 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005503 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005504 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005505{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005506}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005507
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005508AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5509 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5510{
5511 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005512}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005513
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005514void AudioPolicyManager::loadConfig() {
5515 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005516 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005517 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005518 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005519}
5520
5521status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005522 {
5523 auto engLib = EngineLibrary::load(
5524 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5525 if (!engLib) {
5526 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5527 return NO_INIT;
5528 }
5529 mEngine = engLib->createEngine();
5530 if (mEngine == nullptr) {
5531 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5532 return NO_INIT;
5533 }
François Gaffie2110e042015-03-24 08:41:51 +01005534 }
5535 mEngine->setObserver(this);
5536 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005537 if (status != NO_ERROR) {
5538 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5539 return status;
5540 }
François Gaffie2110e042015-03-24 08:41:51 +01005541
Eric Laurent1d69c872021-01-11 18:53:01 +01005542 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5543 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5544
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005545 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005546 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005547 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005548
Eric Laurent3a4311c2014-03-17 12:00:47 -07005549 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005550 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5551 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5552 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005553 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005554 }
jiabin9ff780e2018-03-19 18:19:52 -07005555 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005556 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005557 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005558 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005559 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005560 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005561 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005562 }
5563 }
5564 }
Eric Laurente552edb2014-03-10 17:42:56 -07005565
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005566 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005567
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005568 // Silence ALOGV statements
5569 property_set("log.tag." LOG_TAG, "D");
5570
Eric Laurente552edb2014-03-10 17:42:56 -07005571 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005572 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005573}
5574
Eric Laurente0720872014-03-11 09:30:41 -07005575AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005576{
Eric Laurente552edb2014-03-10 17:42:56 -07005577 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005578 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005579 }
5580 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005581 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005582 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005583 mAvailableOutputDevices.clear();
5584 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005585 mOutputs.clear();
5586 mInputs.clear();
5587 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005588 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005589 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005590}
5591
Eric Laurente0720872014-03-11 09:30:41 -07005592status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005593{
Eric Laurent87ffa392015-05-22 10:32:38 -07005594 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005595}
5596
Eric Laurente552edb2014-03-10 17:42:56 -07005597// ---
5598
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005599void AudioPolicyManager::onNewAudioModulesAvailable()
5600{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005601 DeviceVector newDevices;
5602 onNewAudioModulesAvailableInt(&newDevices);
5603 if (!newDevices.empty()) {
5604 nextAudioPortGeneration();
5605 mpClientInterface->onAudioPortListUpdate();
5606 }
5607}
5608
5609void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5610{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005611 for (const auto& hwModule : mHwModulesAll) {
5612 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5613 continue;
5614 }
5615 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5616 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5617 ALOGW("could not open HW module %s", hwModule->getName());
5618 continue;
5619 }
5620 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005621 // open all output streams needed to access attached devices.
5622 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005623 // This also validates mAvailableOutputDevices list
5624 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5625 if (!outProfile->canOpenNewIo()) {
5626 ALOGE("Invalid Output profile max open count %u for profile %s",
5627 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5628 continue;
5629 }
5630 if (!outProfile->hasSupportedDevices()) {
5631 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5632 continue;
5633 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005634 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5635 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005636 mTtsOutputAvailable = true;
5637 }
5638
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005639 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5640 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5641 sp<DeviceDescriptor> supportedDevice = 0;
5642 if (supportedDevices.contains(mDefaultOutputDevice)) {
5643 supportedDevice = mDefaultOutputDevice;
5644 } else {
5645 // choose first device present in profile's SupportedDevices also part of
5646 // mAvailableOutputDevices.
5647 if (availProfileDevices.isEmpty()) {
5648 continue;
5649 }
5650 supportedDevice = availProfileDevices.itemAt(0);
5651 }
5652 if (!mOutputDevicesAll.contains(supportedDevice)) {
5653 continue;
5654 }
5655 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5656 mpClientInterface);
5657 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005658 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5659 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005660 AUDIO_STREAM_DEFAULT,
5661 AUDIO_OUTPUT_FLAG_NONE, &output);
5662 if (status != NO_ERROR) {
5663 ALOGW("Cannot open output stream for devices %s on hw module %s",
5664 supportedDevice->toString().c_str(), hwModule->getName());
5665 continue;
5666 }
5667 for (const auto &device : availProfileDevices) {
5668 // give a valid ID to an attached device once confirmed it is reachable
5669 if (!device->isAttached()) {
5670 device->attach(hwModule);
5671 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005672 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005673 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005674 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5675 }
5676 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005677 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005678 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5679 mPrimaryOutput = outputDesc;
5680 }
Eric Laurent39095982021-08-24 18:29:27 +02005681 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005682 outputDesc->close();
5683 } else {
5684 addOutput(output, outputDesc);
5685 setOutputDevices(outputDesc,
5686 DeviceVector(supportedDevice),
5687 true,
5688 0,
5689 NULL);
5690 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005691 }
5692 // open input streams needed to access attached devices to validate
5693 // mAvailableInputDevices list
5694 for (const auto& inProfile : hwModule->getInputProfiles()) {
5695 if (!inProfile->canOpenNewIo()) {
5696 ALOGE("Invalid Input profile max open count %u for profile %s",
5697 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5698 continue;
5699 }
5700 if (!inProfile->hasSupportedDevices()) {
5701 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5702 continue;
5703 }
5704 // chose first device present in profile's SupportedDevices also part of
5705 // available input devices
5706 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5707 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5708 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005709 ALOGV("%s: Input device list is empty! for profile %s",
5710 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005711 continue;
5712 }
5713 sp<AudioInputDescriptor> inputDesc =
5714 new AudioInputDescriptor(inProfile, mpClientInterface);
5715
5716 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5717 status_t status = inputDesc->open(nullptr,
5718 availProfileDevices.itemAt(0),
5719 AUDIO_SOURCE_MIC,
5720 AUDIO_INPUT_FLAG_NONE,
5721 &input);
5722 if (status != NO_ERROR) {
5723 ALOGW("Cannot open input stream for device %s on hw module %s",
5724 availProfileDevices.toString().c_str(),
5725 hwModule->getName());
5726 continue;
5727 }
5728 for (const auto &device : availProfileDevices) {
5729 // give a valid ID to an attached device once confirmed it is reachable
5730 if (!device->isAttached()) {
5731 device->attach(hwModule);
5732 device->importAudioPortAndPickAudioProfile(inProfile, true);
5733 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005734 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005735 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5736 }
5737 }
5738 inputDesc->close();
5739 }
5740 }
5741}
5742
Eric Laurent98e38192018-02-15 18:31:53 -08005743void AudioPolicyManager::addOutput(audio_io_handle_t output,
5744 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005745{
Eric Laurent1c333e22014-05-20 10:48:17 -07005746 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005747 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005748 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005749 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005750 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005751}
5752
François Gaffie53615e22015-03-19 09:24:12 +01005753void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5754{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005755 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5756 ALOGV("%s: removing primary output", __func__);
5757 mPrimaryOutput = nullptr;
5758 }
François Gaffie53615e22015-03-19 09:24:12 +01005759 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005760 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005761}
5762
Eric Laurent98e38192018-02-15 18:31:53 -08005763void AudioPolicyManager::addInput(audio_io_handle_t input,
5764 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005765{
Eric Laurent1c333e22014-05-20 10:48:17 -07005766 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005767 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005768}
Eric Laurente552edb2014-03-10 17:42:56 -07005769
François Gaffie11d30102018-11-02 16:09:09 +01005770status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005771 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005772 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005773{
François Gaffie11d30102018-11-02 16:09:09 +01005774 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005775 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005776 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005777
François Gaffie11d30102018-11-02 16:09:09 +01005778 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005779 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005780 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005781 }
Eric Laurente552edb2014-03-10 17:42:56 -07005782
Eric Laurent3b73df72014-03-11 09:06:29 -07005783 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005784 // first call getAudioPort to get the supported attributes from the HAL
5785 struct audio_port_v7 port = {};
5786 device->toAudioPort(&port);
5787 status_t status = mpClientInterface->getAudioPort(&port);
5788 if (status == NO_ERROR) {
5789 device->importAudioPort(port);
5790 }
5791
5792 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005793 for (size_t i = 0; i < mOutputs.size(); i++) {
5794 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005795 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005796 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005797 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5798 mOutputs.keyAt(i), device->toString().c_str());
5799 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005800 }
5801 }
5802 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005803 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005804 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005805 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5806 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005807 if (profile->supportsDevice(device)) {
5808 profiles.add(profile);
5809 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5810 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005811 }
5812 }
5813 }
5814
Eric Laurent7b279bb2015-12-14 10:18:23 -08005815 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005816
Eric Laurente552edb2014-03-10 17:42:56 -07005817 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005818 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005819 return BAD_VALUE;
5820 }
5821
5822 // open outputs for matching profiles if needed. Direct outputs are also opened to
5823 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5824 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005825 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005826
5827 // nothing to do if one output is already opened for this profile
5828 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005829 for (j = 0; j < outputs.size(); j++) {
5830 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005831 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005832 // matching profile: save the sample rates, format and channel masks supported
5833 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005834 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005835 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005836 }
Eric Laurente552edb2014-03-10 17:42:56 -07005837 break;
5838 }
5839 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005840 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005841 continue;
5842 }
5843
Eric Laurent3974e3b2017-12-07 17:58:43 -08005844 if (!profile->canOpenNewIo()) {
5845 ALOGW("Max Output number %u already opened for this profile %s",
5846 profile->maxOpenCount, profile->getTagName().c_str());
5847 continue;
5848 }
5849
Eric Laurent83efe1c2017-07-09 16:51:08 -07005850 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005851 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005852 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5853 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005854 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005855 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005856 profiles.removeAt(profile_index);
5857 profile_index--;
5858 } else {
5859 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005860 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005861 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005862 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5863 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005864 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005865 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005866
François Gaffie11d30102018-11-02 16:09:09 +01005867 if (device_distinguishes_on_address(deviceType)) {
5868 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5869 device->toString().c_str());
5870 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5871 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005872 }
Eric Laurente552edb2014-03-10 17:42:56 -07005873 ALOGV("checkOutputsForDevice(): adding output %d", output);
5874 }
5875 }
5876
5877 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005878 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005879 return BAD_VALUE;
5880 }
Eric Laurentd4692962014-05-05 18:13:44 -07005881 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005882 // check if one opened output is not needed any more after disconnecting one device
5883 for (size_t i = 0; i < mOutputs.size(); i++) {
5884 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005885 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005886 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005887 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005888 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005889 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005890 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005891 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5892 mOutputs.keyAt(i));
5893 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005894 }
Eric Laurente552edb2014-03-10 17:42:56 -07005895 }
5896 }
Eric Laurentd4692962014-05-05 18:13:44 -07005897 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005898 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005899 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5900 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005901 if (!profile->supportsDevice(device)) {
5902 continue;
5903 }
5904 ALOGV("checkOutputsForDevice(): "
5905 "clearing direct output profile %zu on module %s",
5906 j, hwModule->getName());
5907 profile->clearAudioProfiles();
5908 if (!profile->hasDynamicAudioProfile()) {
5909 continue;
5910 }
5911 // When a device is disconnected, if there is an IOProfile that contains dynamic
5912 // profiles and supports the disconnected device, call getAudioPort to repopulate
5913 // the capabilities of the devices that is supported by the IOProfile.
5914 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5915 if (supportedDevice == device ||
5916 !mAvailableOutputDevices.contains(supportedDevice)) {
5917 continue;
5918 }
5919 struct audio_port_v7 port;
5920 supportedDevice->toAudioPort(&port);
5921 status_t status = mpClientInterface->getAudioPort(&port);
5922 if (status == NO_ERROR) {
5923 supportedDevice->importAudioPort(port);
5924 }
Eric Laurente552edb2014-03-10 17:42:56 -07005925 }
5926 }
5927 }
5928 }
5929 return NO_ERROR;
5930}
5931
François Gaffie11d30102018-11-02 16:09:09 +01005932status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005933 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005934{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005935 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005936
François Gaffie11d30102018-11-02 16:09:09 +01005937 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005938 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005939 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005940 }
5941
Eric Laurentd4692962014-05-05 18:13:44 -07005942 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005943 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005944 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005945 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005946 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005947 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005948 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005949 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005950
François Gaffie11d30102018-11-02 16:09:09 +01005951 if (profile->supportsDevice(device)) {
5952 profiles.add(profile);
5953 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5954 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005955 }
5956 }
5957 }
5958
Eric Laurent0dd51852019-04-19 18:18:58 -07005959 if (profiles.isEmpty()) {
5960 ALOGW("%s: No input profile available for device %s",
5961 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005962 return BAD_VALUE;
5963 }
5964
5965 // open inputs for matching profiles if needed. Direct inputs are also opened to
5966 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5967 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5968
Eric Laurent1c333e22014-05-20 10:48:17 -07005969 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005970
Eric Laurentd4692962014-05-05 18:13:44 -07005971 // nothing to do if one input is already opened for this profile
5972 size_t input_index;
5973 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5974 desc = mInputs.valueAt(input_index);
5975 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005976 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005977 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005978 }
Eric Laurentd4692962014-05-05 18:13:44 -07005979 break;
5980 }
5981 }
5982 if (input_index != mInputs.size()) {
5983 continue;
5984 }
5985
Eric Laurent3974e3b2017-12-07 17:58:43 -08005986 if (!profile->canOpenNewIo()) {
5987 ALOGW("Max Input number %u already opened for this profile %s",
5988 profile->maxOpenCount, profile->getTagName().c_str());
5989 continue;
5990 }
5991
Eric Laurentfe231122017-11-17 17:48:06 -08005992 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005993 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005994 status_t status = desc->open(nullptr,
5995 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005996 AUDIO_SOURCE_MIC,
5997 AUDIO_INPUT_FLAG_NONE,
5998 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005999
Eric Laurentcf2c0212014-07-25 16:20:43 -07006000 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006001 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006002 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006003 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006004 mpClientInterface->setParameters(input, String8(param));
6005 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006006 }
François Gaffie11d30102018-11-02 16:09:09 +01006007 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006008 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006009 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006010 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006011 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006012 }
6013
Eric Laurent0dd51852019-04-19 18:18:58 -07006014 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006015 addInput(input, desc);
6016 }
6017 } // endif input != 0
6018
Eric Laurentcf2c0212014-07-25 16:20:43 -07006019 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006020 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006021 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006022 profiles.removeAt(profile_index);
6023 profile_index--;
6024 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006025 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006026 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006027 }
Eric Laurentd4692962014-05-05 18:13:44 -07006028 ALOGV("checkInputsForDevice(): adding input %d", input);
6029 }
6030 } // end scan profiles
6031
6032 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006033 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006034 return BAD_VALUE;
6035 }
6036 } else {
6037 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006038 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006039 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006040 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006041 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006042 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006043 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006044 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006045 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6046 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006047 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006048 }
6049 }
6050 }
6051 } // end disconnect
6052
6053 return NO_ERROR;
6054}
6055
6056
Eric Laurente0720872014-03-11 09:30:41 -07006057void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006058{
6059 ALOGV("closeOutput(%d)", output);
6060
François Gaffie1c878552018-11-22 16:53:21 +01006061 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6062 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006063 ALOGW("closeOutput() unknown output %d", output);
6064 return;
6065 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006066 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006067 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006068
Eric Laurente552edb2014-03-10 17:42:56 -07006069 // look for duplicated outputs connected to the output being removed.
6070 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006071 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6072 if (dupOutput->isDuplicated() &&
6073 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6074 sp<SwAudioOutputDescriptor> remainingOutput =
6075 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006076 // As all active tracks on duplicated output will be deleted,
6077 // and as they were also referenced on the other output, the reference
6078 // count for their stream type must be adjusted accordingly on
6079 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006080 const bool wasActive = remainingOutput->isActive();
6081 // Note: no-op on the closing output where all clients has already been set inactive
6082 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006083 // stop() will be a no op if the output is still active but is needed in case all
6084 // active streams refcounts where cleared above
6085 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006086 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006087 }
Eric Laurente552edb2014-03-10 17:42:56 -07006088 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6089 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6090
6091 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006092 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006093 }
6094 }
6095
Eric Laurent05b90f82014-08-27 15:32:29 -07006096 nextAudioPortGeneration();
6097
François Gaffie1c878552018-11-22 16:53:21 +01006098 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006099 if (index >= 0) {
6100 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006101 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6102 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006103 mAudioPatches.removeItemsAt(index);
6104 mpClientInterface->onAudioPatchListUpdate();
6105 }
6106
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006107 if (closingOutputWasActive) {
6108 closingOutput->stop();
6109 }
François Gaffie1c878552018-11-22 16:53:21 +01006110 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006111
François Gaffie53615e22015-03-19 09:24:12 +01006112 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006113 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006114 if (closingOutput == mSpatializerOutput) {
6115 mSpatializerOutput.clear();
6116 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006117
6118 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6119 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006120 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006121 bool directOutputOpen = false;
6122 for (size_t i = 0; i < mOutputs.size(); i++) {
6123 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6124 directOutputOpen = true;
6125 break;
6126 }
6127 }
6128 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006129 ALOGV("no direct outputs open, reset MSD patches");
6130 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6131 // how output devices for patching are resolved. Avoid by caching and reusing the
6132 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6133 // devices to patch to. This may be complicated by the fact that devices may become
6134 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006135 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006136 }
6137 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006138}
6139
6140void AudioPolicyManager::closeInput(audio_io_handle_t input)
6141{
6142 ALOGV("closeInput(%d)", input);
6143
6144 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6145 if (inputDesc == NULL) {
6146 ALOGW("closeInput() unknown input %d", input);
6147 return;
6148 }
6149
Eric Laurent6a94d692014-05-20 11:18:06 -07006150 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006151
François Gaffie11d30102018-11-02 16:09:09 +01006152 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006153 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006154 if (index >= 0) {
6155 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006156 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6157 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006158 mAudioPatches.removeItemsAt(index);
6159 mpClientInterface->onAudioPatchListUpdate();
6160 }
6161
Eric Laurentfe231122017-11-17 17:48:06 -08006162 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006163 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006164
François Gaffie11d30102018-11-02 16:09:09 +01006165 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6166 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006167 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006168 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006169 }
Eric Laurente552edb2014-03-10 17:42:56 -07006170}
6171
François Gaffie11d30102018-11-02 16:09:09 +01006172SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6173 const DeviceVector &devices,
6174 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006175{
6176 SortedVector<audio_io_handle_t> outputs;
6177
François Gaffie11d30102018-11-02 16:09:09 +01006178 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006179 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006180 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006181 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006182 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006183 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006184 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006185 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006186 outputs.add(openOutputs.keyAt(i));
6187 }
6188 }
6189 return outputs;
6190}
6191
Mikhail Naganov37977152018-07-11 15:54:44 -07006192void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6193{
6194 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6195 // output is suspended before any tracks are moved to it
6196 checkA2dpSuspend();
6197 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006198 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006199 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006200 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006201 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006202 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6203 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6204 // configuration changes will ultimately be rerouted correctly. We can still avoid
6205 // unnecessary rerouting by caching and reusing the arguments to
6206 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6207 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006208 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006209 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006210 // an event that changed routing likely occurred, inform upper layers
6211 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006212}
6213
François Gaffiec005e562018-11-06 15:04:49 +01006214bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6215 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006216{
François Gaffiec005e562018-11-06 15:04:49 +01006217 return mEngine->getProductStrategyForAttributes(lAttr) ==
6218 mEngine->getProductStrategyForAttributes(rAttr);
6219}
6220
Francois Gaffieff1eb522020-05-06 18:37:04 +02006221void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6222{
6223 for (size_t i = 0; i < mAudioSources.size(); i++) {
6224 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6225 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006226 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006227 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006228 connectAudioSource(sourceDesc);
6229 }
6230 }
6231}
6232
6233void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6234{
6235 for (size_t i = 0; i < mAudioSources.size(); i++) {
6236 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6237 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6238 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6239 disconnectAudioSource(sourceDesc);
6240 }
6241 }
6242}
6243
François Gaffiec005e562018-11-06 15:04:49 +01006244void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6245{
6246 auto psId = mEngine->getProductStrategyForAttributes(attr);
6247
6248 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6249 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006250
François Gaffie11d30102018-11-02 16:09:09 +01006251 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6252 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006253
Eric Laurentc209fe42020-06-05 18:11:23 -07006254 uint32_t maxLatency = 0;
6255 bool invalidate = false;
6256 // take into account dynamic audio policies related changes: if a client is now associated
6257 // to a different policy mix than at creation time, invalidate corresponding stream
6258 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6259 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6260 if (desc->isDuplicated()) {
6261 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006262 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006263 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6264 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6265 continue;
6266 }
6267 sp<AudioPolicyMix> primaryMix;
6268 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
6269 client->flags(), primaryMix, nullptr);
6270 if (status != OK) {
6271 continue;
6272 }
yucliuf4de36d2020-09-14 14:57:56 -07006273 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006274 invalidate = true;
6275 if (desc->isStrategyActive(psId)) {
6276 maxLatency = desc->latency();
6277 }
6278 break;
6279 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006280 }
6281 }
6282
Eric Laurentc209fe42020-06-05 18:11:23 -07006283 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006284 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6285 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006286 for (audio_io_handle_t srcOut : srcOutputs) {
6287 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006288 if (desc == nullptr) continue;
6289
6290 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006291 maxLatency = desc->latency();
6292 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006293
6294 if (invalidate) continue;
6295
6296 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006297 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006298 // a client on a non direct outputs has necessarily a linear PCM format
6299 // so we can call selectOutput() safely
6300 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6301 client->flags(),
6302 client->config().format,
6303 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006304 client->config().sample_rate,
6305 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006306 if (newOutput != srcOut) {
6307 invalidate = true;
6308 break;
6309 }
6310 } else {
6311 sp<IOProfile> profile = getProfileForOutput(newDevices,
6312 client->config().sample_rate,
6313 client->config().format,
6314 client->config().channel_mask,
6315 client->flags(),
6316 true /* directOnly */);
6317 if (profile != desc->mProfile) {
6318 invalidate = true;
6319 break;
6320 }
6321 }
6322 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006323 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006324
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006325 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006326 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006327 std::to_string(srcOutputs[0]).c_str(),
6328 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006329 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006330 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006331 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006332 if (desc == nullptr) continue;
6333
6334 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006335 setStrategyMute(psId, true, desc);
6336 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006337 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006338 }
François Gaffiec005e562018-11-06 15:04:49 +01006339 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006340 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006341 connectAudioSource(source);
6342 }
Eric Laurente552edb2014-03-10 17:42:56 -07006343 }
6344
François Gaffiec005e562018-11-06 15:04:49 +01006345 // Move effects associated to this stream from previous output to new output
6346 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006347 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006348 }
François Gaffiec005e562018-11-06 15:04:49 +01006349 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006350 if (invalidate) {
6351 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6352 mpClientInterface->invalidateStream(stream);
6353 }
jiabin49256852022-03-09 11:21:35 -08006354 for (audio_io_handle_t srcOut : srcOutputs) {
6355 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6356 if (desc == nullptr) continue;
6357
6358 desc->setTracksInvalidatedStatusByStrategy(psId);
6359 }
Eric Laurente552edb2014-03-10 17:42:56 -07006360 }
6361 }
6362}
6363
Eric Laurente0720872014-03-11 09:30:41 -07006364void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006365{
François Gaffiec005e562018-11-06 15:04:49 +01006366 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6367 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6368 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006369 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006370 }
Eric Laurente552edb2014-03-10 17:42:56 -07006371}
6372
Kevin Rocard153f92d2018-12-18 18:33:28 -08006373void AudioPolicyManager::checkSecondaryOutputs() {
6374 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006375 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006376 for (size_t i = 0; i < mOutputs.size(); i++) {
6377 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6378 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006379 sp<AudioPolicyMix> primaryMix;
6380 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006381 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006382 client->flags(), primaryMix, &secondaryMixes);
6383 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6384 for (auto &secondaryMix : secondaryMixes) {
6385 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6386 if (outputDesc != nullptr &&
6387 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6388 secondaryDescs.push_back(outputDesc);
6389 }
6390 }
6391
jiabin10a03f12021-05-07 23:46:28 +00006392 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006393 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006394 } else if (!std::equal(
6395 client->getSecondaryOutputs().begin(),
6396 client->getSecondaryOutputs().end(),
6397 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006398 if (!audio_is_linear_pcm(client->config().format)) {
6399 // If the format is not PCM, the tracks should be invalidated to get correct
6400 // behavior when the secondary output is changed.
6401 streamsToInvalidate.insert(client->stream());
6402 } else {
6403 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6404 std::vector<audio_io_handle_t> secondaryOutputIds;
6405 for (const auto &secondaryDesc: secondaryDescs) {
6406 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6407 weakSecondaryDescs.push_back(secondaryDesc);
6408 }
6409 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6410 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006411 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006412 }
6413 }
6414 }
jiabin10a03f12021-05-07 23:46:28 +00006415 if (!trackSecondaryOutputs.empty()) {
6416 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6417 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006418 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006419 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006420 mpClientInterface->invalidateStream(stream);
6421 }
6422}
6423
Eric Laurent2517af32020-11-25 15:31:27 +01006424bool AudioPolicyManager::isScoRequestedForComm() const {
6425 AudioDeviceTypeAddrVector devices;
6426 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6427 for (const auto &device : devices) {
6428 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6429 return true;
6430 }
6431 }
6432 return false;
6433}
6434
Eric Laurente0720872014-03-11 09:30:41 -07006435void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006436{
François Gaffie53615e22015-03-19 09:24:12 +01006437 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006438 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006439 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006440 return;
6441 }
6442
Eric Laurent3a4311c2014-03-17 12:00:47 -07006443 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006444 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6445 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006446 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006447
6448 // if suspended, restore A2DP output if:
6449 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006450 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006451 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006452 //
Eric Laurentf732e072016-08-03 19:30:28 -07006453 // if not suspended, suspend A2DP output if:
6454 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006455 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006456 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006457 //
6458 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006459 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006460 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006461 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006462 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006463
6464 mpClientInterface->restoreOutput(a2dpOutput);
6465 mA2dpSuspended = false;
6466 }
6467 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006468 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006469 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006470 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006471 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006472
6473 mpClientInterface->suspendOutput(a2dpOutput);
6474 mA2dpSuspended = true;
6475 }
6476 }
6477}
6478
François Gaffie11d30102018-11-02 16:09:09 +01006479DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6480 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006481{
François Gaffie11d30102018-11-02 16:09:09 +01006482 DeviceVector devices;
6483
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006484 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006485 if (index >= 0) {
6486 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006487 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006488 ALOGV("%s device %s forced by patch %d", __func__,
6489 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6490 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006491 }
6492 }
6493
Dean Wheatley514b4312020-06-17 21:45:00 +10006494 // Do not retrieve engine device for outputs through MSD
6495 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6496 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6497 return outputDesc->devices();
6498 }
6499
Eric Laurent97ac8712018-07-27 18:59:02 -07006500 // Honor explicit routing requests only if no client using default routing is active on this
6501 // input: a specific app can not force routing for other apps by setting a preferred device.
6502 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006503 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006504 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006505 if (device != nullptr) {
6506 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006507 }
6508
François Gaffiea807ef92018-11-05 10:44:33 +01006509 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6510 // of setForceUse / Default Bus device here
6511 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6512 if (device != nullptr) {
6513 return DeviceVector(device);
6514 }
6515
François Gaffiec005e562018-11-06 15:04:49 +01006516 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6517 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6518 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306519 auto hasStreamActive = [&](auto stream) {
6520 return hasStream(streams, stream) && isStreamActive(stream, 0);
6521 };
Eric Laurent484e9272018-06-07 17:29:23 -07006522
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306523 auto doGetOutputDevicesForVoice = [&]() {
6524 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006525 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306526 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006527 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6528 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306529 };
6530
6531 // With low-latency playing on speaker, music on WFD, when the first low-latency
6532 // output is stopped, getNewOutputDevices checks for a product strategy
6533 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006534 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306535 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6536 // stream is associated to the output descriptor.
6537 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6538 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6539 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6540 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006541 // Retrieval of devices for voice DL is done on primary output profile, cannot
6542 // check the route (would force modifying configuration file for this profile)
6543 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6544 break;
6545 }
Eric Laurente552edb2014-03-10 17:42:56 -07006546 }
François Gaffiec005e562018-11-06 15:04:49 +01006547 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006548 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006549}
6550
François Gaffie11d30102018-11-02 16:09:09 +01006551sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6552 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006553{
François Gaffie11d30102018-11-02 16:09:09 +01006554 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006555
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006556 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006557 if (index >= 0) {
6558 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006559 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006560 ALOGV("getNewInputDevice() device %s forced by patch %d",
6561 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6562 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006563 }
6564 }
6565
Eric Laurent97ac8712018-07-27 18:59:02 -07006566 // Honor explicit routing requests only if no client using default routing is active on this
6567 // input: a specific app can not force routing for other apps by setting a preferred device.
6568 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006569 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6570 if (device != nullptr) {
6571 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006572 }
6573
Eric Laurentdc95a252018-04-12 12:46:56 -07006574 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006575 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006576 audio_attributes_t attributes;
6577 uid_t uid;
6578 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6579 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006580 attributes = topClient->attributes();
6581 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006582 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006583 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6584 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006585 }
6586
Francois Gaffie716e1432019-01-14 16:58:59 +01006587 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6588 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006589 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006590 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006591 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006592 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006593
Eric Laurente552edb2014-03-10 17:42:56 -07006594 return device;
6595}
6596
Eric Laurent794fde22016-03-11 09:50:45 -08006597bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6598 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006599 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006600}
6601
Dorin Drimusf2196d82022-01-03 12:11:18 +01006602// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006603status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006604 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006605 if (devices == nullptr) {
6606 return BAD_VALUE;
6607 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006608
6609 // Devices are determined in the following precedence:
6610 //
6611 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6612 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6613 //
6614 // If no such dynamic policy then
6615 // 2) Devices containing an active client using setPreferredDevice
6616 // with same strategy as the attributes.
6617 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6618 //
6619 // If no corresponding active client with setPreferredDevice then
6620 // 3) Devices associated with the strategy determined by the attributes
6621 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6622 //
6623 // See related getOutputForAttrInt().
6624
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006625 // check dynamic policies but only for primary descriptors (secondary not used for audible
6626 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006627 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006628 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Andy Hung6d23c0f2022-02-16 09:37:15 -08006629 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr /* secondaryMixes */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006630 if (status != OK) {
6631 return status;
6632 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006633
6634 DeviceVector curDevices;
6635 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6636 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6637 // as they are unaffected by device/stream volume
6638 // (per SwAudioOutputDescriptor::isFixedVolume()).
6639 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6640 ) {
6641 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6642 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6643 curDevices.add(deviceDesc);
6644 } else {
6645 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6646 // which selects setPreferredDevice if active. This means forVolume call
6647 // will take an active setPreferredDevice, if such exists.
6648
6649 curDevices = mEngine->getOutputDevicesForAttributes(
6650 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006651 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006652
6653 if (forVolume) {
6654 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6655 // for single volume control in AudioService (such relationship should exist if
6656 // SPEAKER_SAFE is present).
6657 //
6658 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6659 DeviceVector speakerSafeDevices =
6660 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6661 if (!speakerSafeDevices.isEmpty()) {
6662 curDevices.merge(
6663 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6664 curDevices.remove(speakerSafeDevices);
6665 }
6666 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006667 for (const auto& device : curDevices) {
6668 devices->push_back(device->getDeviceTypeAddr());
6669 }
6670 return NO_ERROR;
6671}
6672
Eric Laurente0720872014-03-11 09:30:41 -07006673void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006674 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006675 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006676 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006677 updateDevicesAndOutputs();
6678 break;
6679 default:
6680 break;
6681 }
6682}
6683
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006684uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006685
6686 // skip beacon mute management if a dedicated TTS output is available
6687 if (mTtsOutputAvailable) {
6688 return 0;
6689 }
6690
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006691 switch(event) {
6692 case STARTING_OUTPUT:
6693 mBeaconMuteRefCount++;
6694 break;
6695 case STOPPING_OUTPUT:
6696 if (mBeaconMuteRefCount > 0) {
6697 mBeaconMuteRefCount--;
6698 }
6699 break;
6700 case STARTING_BEACON:
6701 mBeaconPlayingRefCount++;
6702 break;
6703 case STOPPING_BEACON:
6704 if (mBeaconPlayingRefCount > 0) {
6705 mBeaconPlayingRefCount--;
6706 }
6707 break;
6708 }
6709
6710 if (mBeaconMuteRefCount > 0) {
6711 // any playback causes beacon to be muted
6712 return setBeaconMute(true);
6713 } else {
6714 // no other playback: unmute when beacon starts playing, mute when it stops
6715 return setBeaconMute(mBeaconPlayingRefCount == 0);
6716 }
6717}
6718
6719uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6720 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6721 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6722 // keep track of muted state to avoid repeating mute/unmute operations
6723 if (mBeaconMuted != mute) {
6724 // mute/unmute AUDIO_STREAM_TTS on all outputs
6725 ALOGV("\t muting %d", mute);
6726 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006727 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6728 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6729 ALOGV("\t no tts volume source available");
6730 return 0;
6731 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006732 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006733 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006734 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006735 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006736 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006737 maxLatency = latency;
6738 }
6739 }
6740 mBeaconMuted = mute;
6741 return maxLatency;
6742 }
6743 return 0;
6744}
6745
Eric Laurente0720872014-03-11 09:30:41 -07006746void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006747{
François Gaffiec005e562018-11-06 15:04:49 +01006748 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006749 mPreviousOutputs = mOutputs;
6750}
6751
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006752uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006753 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006754 uint32_t delayMs)
6755{
6756 // mute/unmute strategies using an incompatible device combination
6757 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6758 // if unmuting, unmute only after the specified delay
6759 if (outputDesc->isDuplicated()) {
6760 return 0;
6761 }
6762
6763 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006764 DeviceVector devices = outputDesc->devices();
6765 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006766
François Gaffiec005e562018-11-06 15:04:49 +01006767 auto productStrategies = mEngine->getOrderedProductStrategies();
6768 for (const auto &productStrategy : productStrategies) {
6769 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6770 DeviceVector curDevices =
6771 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6772 curDevices = curDevices.filter(outputDesc->supportedDevices());
6773 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006774 bool doMute = false;
6775
François Gaffiec005e562018-11-06 15:04:49 +01006776 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006777 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006778 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6779 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006780 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006781 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006782 }
Eric Laurent99401132014-05-07 19:48:15 -07006783 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006784 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006785 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006786 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006787 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006788 continue;
6789 }
François Gaffiec005e562018-11-06 15:04:49 +01006790 ALOGVV("%s() %s (curDevice %s)", __func__,
6791 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6792 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6793 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006794 if (mute) {
6795 // FIXME: should not need to double latency if volume could be applied
6796 // immediately by the audioflinger mixer. We must account for the delay
6797 // between now and the next time the audioflinger thread for this output
6798 // will process a buffer (which corresponds to one buffer size,
6799 // usually 1/2 or 1/4 of the latency).
6800 if (muteWaitMs < desc->latency() * 2) {
6801 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006802 }
6803 }
6804 }
6805 }
6806 }
6807 }
6808
Eric Laurent99401132014-05-07 19:48:15 -07006809 // temporary mute output if device selection changes to avoid volume bursts due to
6810 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006811 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006812 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006813
Eric Laurentdc462862016-07-19 12:29:53 -07006814 if (muteWaitMs < tempMuteWaitMs) {
6815 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006816 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006817
6818 // If recommended duration is defined, replace temporary mute duration to avoid
6819 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6820 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6821 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6822 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6823 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6824
François Gaffieaaac0fd2018-11-22 17:56:39 +01006825 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6826 // make sure that we do not start the temporary mute period too early in case of
6827 // delayed device change
6828 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6829 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006830 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006831 }
6832 }
6833
Eric Laurente552edb2014-03-10 17:42:56 -07006834 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6835 if (muteWaitMs > delayMs) {
6836 muteWaitMs -= delayMs;
6837 usleep(muteWaitMs * 1000);
6838 return muteWaitMs;
6839 }
6840 return 0;
6841}
6842
François Gaffie11d30102018-11-02 16:09:09 +01006843uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6844 const DeviceVector &devices,
6845 bool force,
6846 int delayMs,
6847 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006848 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006849{
François Gaffie11d30102018-11-02 16:09:09 +01006850 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006851 uint32_t muteWaitMs;
6852
6853 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006854 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6855 nullptr /* patchHandle */, requiresMuteCheck);
6856 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6857 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006858 return muteWaitMs;
6859 }
Eric Laurente552edb2014-03-10 17:42:56 -07006860
6861 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006862 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006863 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006864 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006865
François Gaffie11d30102018-11-02 16:09:09 +01006866 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6867
6868 if (!filteredDevices.isEmpty()) {
6869 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006870 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006871
6872 // if the outputs are not materially active, there is no need to mute.
6873 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006874 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006875 } else {
6876 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6877 muteWaitMs = 0;
6878 }
Eric Laurente552edb2014-03-10 17:42:56 -07006879
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006880 bool outputRouted = outputDesc->isRouted();
6881
Eric Laurent79ea9582020-06-11 18:49:24 -07006882 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6883 // output profile or if new device is not supported AND previous device(s) is(are) still
6884 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006885 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006886 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6887 // restore previous device after evaluating strategy mute state
6888 outputDesc->setDevices(prevDevices);
6889 return muteWaitMs;
6890 }
6891
Eric Laurente552edb2014-03-10 17:42:56 -07006892 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006893 // the requested device is AUDIO_DEVICE_NONE
6894 // OR the requested device is the same as current device
6895 // AND force is not specified
6896 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006897 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006898 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01006899 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6900 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006901 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6902 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6903 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6904 }
Eric Laurente552edb2014-03-10 17:42:56 -07006905 return muteWaitMs;
6906 }
6907
François Gaffie11d30102018-11-02 16:09:09 +01006908 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006909
Eric Laurente552edb2014-03-10 17:42:56 -07006910 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006911 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006912 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006913 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006914 PatchBuilder patchBuilder;
6915 patchBuilder.addSource(outputDesc);
6916 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6917 for (const auto &filteredDevice : filteredDevices) {
6918 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006919 }
6920
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006921 // Add half reported latency to delayMs when muteWaitMs is null in order
6922 // to avoid disordered sequence of muting volume and changing devices.
6923 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6924 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006925 }
Eric Laurente552edb2014-03-10 17:42:56 -07006926
6927 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006928 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006929
6930 return muteWaitMs;
6931}
6932
Eric Laurentc75307b2015-03-17 15:29:32 -07006933status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006934 int delayMs,
6935 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006936{
Eric Laurent6a94d692014-05-20 11:18:06 -07006937 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006938 if (patchHandle == nullptr && !outputDesc->isRouted()) {
6939 return INVALID_OPERATION;
6940 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006941 if (patchHandle) {
6942 index = mAudioPatches.indexOfKey(*patchHandle);
6943 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006944 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006945 }
6946 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006947 return INVALID_OPERATION;
6948 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006949 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006950 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006951 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006952 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006953 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006954 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006955 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006956 return status;
6957}
6958
6959status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006960 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006961 bool force,
6962 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006963{
6964 status_t status = NO_ERROR;
6965
Eric Laurent1f2f2232014-06-02 12:01:23 -07006966 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006967 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6968 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006969
François Gaffie11d30102018-11-02 16:09:09 +01006970 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006971 PatchBuilder patchBuilder;
6972 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006973 // AUDIO_SOURCE_HOTWORD is for internal use only:
6974 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006975 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6976 auto result = usecase;
6977 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6978 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6979 }
6980 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006981 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006982 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006983 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006984 }
6985 }
6986 return status;
6987}
6988
Eric Laurent6a94d692014-05-20 11:18:06 -07006989status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6990 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006991{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006992 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006993 ssize_t index;
6994 if (patchHandle) {
6995 index = mAudioPatches.indexOfKey(*patchHandle);
6996 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006997 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006998 }
6999 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007000 return INVALID_OPERATION;
7001 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007002 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007003 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007004 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007005 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007006 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007007 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007008 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007009 return status;
7010}
7011
François Gaffie11d30102018-11-02 16:09:09 +01007012sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007013 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007014 audio_format_t& format,
7015 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007016 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007017{
7018 // Choose an input profile based on the requested capture parameters: select the first available
7019 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007020 //
7021 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7022 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007023
Glenn Kasten730b9262018-03-29 15:01:26 -07007024 sp<IOProfile> firstInexact;
7025 uint32_t updatedSamplingRate = 0;
7026 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7027 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007028 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007029 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007030 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007031 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007032 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007033 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007034 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007035 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007036 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007037 &channelMask /*updatedChannelMask*/,
7038 // FIXME ugly cast
7039 (audio_output_flags_t) flags,
7040 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007041 return profile;
7042 }
François Gaffie11d30102018-11-02 16:09:09 +01007043 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007044 samplingRate,
7045 &updatedSamplingRate,
7046 format,
7047 &updatedFormat,
7048 channelMask,
7049 &updatedChannelMask,
7050 // FIXME ugly cast
7051 (audio_output_flags_t) flags,
7052 false /*exactMatchRequiredForInputFlags*/)) {
7053 firstInexact = profile;
7054 }
7055
Eric Laurente552edb2014-03-10 17:42:56 -07007056 }
7057 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007058 if (firstInexact != nullptr) {
7059 samplingRate = updatedSamplingRate;
7060 format = updatedFormat;
7061 channelMask = updatedChannelMask;
7062 return firstInexact;
7063 }
Eric Laurente552edb2014-03-10 17:42:56 -07007064 return NULL;
7065}
7066
François Gaffieaaac0fd2018-11-22 17:56:39 +01007067float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7068 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007069 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007070 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007071{
jiabin9a3361e2019-10-01 09:38:30 -07007072 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007073
7074 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7075 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7076 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7077 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007078 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7079 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7080 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7081 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7082 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007083
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007084 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007085 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7086 mOutputs.isActive(ringVolumeSrc, 0)) {
7087 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007088 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007089 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007090 }
7091
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007092 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007093 if ((volumeSource != callVolumeSrc && (isInCall() ||
7094 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007095 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007096 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7097 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007098 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7099 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7100 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007101 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007102 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007103 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007104 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007105 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007106 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007107 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7108 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7109 // programmatically muted.
7110 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7111 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7112 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007113 bool exemptFromCapping =
7114 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7115 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007116 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7117 volumeSource, volumeDb);
7118 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007119 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7120 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7121 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007122 }
7123 }
Eric Laurente552edb2014-03-10 17:42:56 -07007124 // if a headset is connected, apply the following rules to ring tones and notifications
7125 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007126 // - always attenuate notifications volume by 6dB
7127 // - attenuate ring tones volume by 6dB unless music is not playing and
7128 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007129 // - if music is playing, always limit the volume to current music volume,
7130 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007131 if (!Intersection(deviceTypes,
7132 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7133 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007134 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7135 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007136 ((volumeSource == alarmVolumeSrc ||
7137 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007138 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7139 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7140 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007141 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7142 curves.canBeMuted()) {
7143
Eric Laurente552edb2014-03-10 17:42:56 -07007144 // when the phone is ringing we must consider that music could have been paused just before
7145 // by the music application and behave as if music was active if the last music track was
7146 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007147 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007148 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007149 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007150 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007151 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7152 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007153 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007154 float musicVolDb = computeVolume(musicCurves,
7155 musicVolumeSrc,
7156 musicCurves.getVolumeIndex(musicDevice),
7157 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007158 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7159 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7160 if (volumeDb > minVolDb) {
7161 volumeDb = minVolDb;
7162 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007163 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007164 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7165 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7166 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007167 // on A2DP, also ensure notification volume is not too low compared to media when
7168 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007169 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007170 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007171 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7172 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007173 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7174 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007175 }
7176 }
jiabin9a3361e2019-10-01 09:38:30 -07007177 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007178 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007179 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007180 }
7181 }
7182
François Gaffie43c73442018-11-08 08:21:55 +01007183 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007184}
7185
Eric Laurent3839bc02018-07-10 18:33:34 -07007186int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007187 VolumeSource fromVolumeSource,
7188 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007189{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007190 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007191 return srcIndex;
7192 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007193 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7194 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007195 float minSrc = (float)srcCurves.getVolumeIndexMin();
7196 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7197 float minDst = (float)dstCurves.getVolumeIndexMin();
7198 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007199
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007200 // preserve mute request or correct range
7201 if (srcIndex < minSrc) {
7202 if (srcIndex == 0) {
7203 return 0;
7204 }
7205 srcIndex = minSrc;
7206 } else if (srcIndex > maxSrc) {
7207 srcIndex = maxSrc;
7208 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007209 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7210}
7211
François Gaffieaaac0fd2018-11-22 17:56:39 +01007212status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7213 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007214 int index,
7215 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007216 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007217 int delayMs,
7218 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007219{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007220 // do not change actual attributes volume if the attributes is muted
7221 if (outputDesc->isMuted(volumeSource)) {
7222 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7223 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007224 return NO_ERROR;
7225 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007226 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7227 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7228 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7229 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007230
Eric Laurent2517af32020-11-25 15:31:27 +01007231 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07007232 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007233 // if sco and call follow same curves, bypass forceUseForComm
7234 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007235 ((isVoiceVolSrc && isScoRequested) ||
7236 (isBtScoVolSrc && !isScoRequested))) {
7237 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
7238 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07007239 // Do not return an error here as AudioService will always set both voice call
7240 // and bluetooth SCO volumes due to stream aliasing.
7241 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007242 }
jiabin9a3361e2019-10-01 09:38:30 -07007243 if (deviceTypes.empty()) {
7244 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007245 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007246
jiabin9a3361e2019-10-01 09:38:30 -07007247 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7248 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007249 // Force VoIP volume to max for bluetooth SCO device except if muted
7250 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007251 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007252 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007253 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007254 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007255 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007256 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007257
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007258 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007259 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007260 // 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 +01007261 if (isVoiceVolSrc) {
7262 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007263 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007264 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007265 }
Eric Laurent18fba842016-03-31 14:41:26 -07007266 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007267 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7268 mLastVoiceVolume = voiceVolume;
7269 }
7270 }
Eric Laurente552edb2014-03-10 17:42:56 -07007271 return NO_ERROR;
7272}
7273
Eric Laurentc75307b2015-03-17 15:29:32 -07007274void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007275 const DeviceTypeSet& deviceTypes,
7276 int delayMs,
7277 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007278{
jiabincd510522020-01-22 09:40:55 -08007279 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007280 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7281 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7282 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007283 curves.getVolumeIndex(deviceTypes),
7284 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007285 }
7286}
7287
François Gaffiec005e562018-11-06 15:04:49 +01007288void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7289 bool on,
7290 const sp<AudioOutputDescriptor>& outputDesc,
7291 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007292 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007293{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007294 std::vector<VolumeSource> sourcesToMute;
7295 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7296 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7297 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007298 VolumeSource source = toVolumeSource(attributes, false);
7299 if ((source != VOLUME_SOURCE_NONE) &&
7300 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7301 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007302 sourcesToMute.push_back(source);
7303 }
Eric Laurente552edb2014-03-10 17:42:56 -07007304 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007305 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007306 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007307 }
7308
Eric Laurente552edb2014-03-10 17:42:56 -07007309}
7310
François Gaffieaaac0fd2018-11-22 17:56:39 +01007311void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7312 bool on,
7313 const sp<AudioOutputDescriptor>& outputDesc,
7314 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007315 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007316{
jiabin9a3361e2019-10-01 09:38:30 -07007317 if (deviceTypes.empty()) {
7318 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007319 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007320 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007321 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007322 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007323 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007324 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007325 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7326 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007327 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007328 }
7329 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007330 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7331 // ignored
7332 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007333 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007334 if (!outputDesc->isMuted(volumeSource)) {
7335 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007336 return;
7337 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007338 if (outputDesc->decMuteCount(volumeSource) == 0) {
7339 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007340 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007341 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007342 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007343 delayMs);
7344 }
7345 }
7346}
7347
François Gaffie53615e22015-03-19 09:24:12 +01007348bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7349{
François Gaffiec005e562018-11-06 15:04:49 +01007350 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007351 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7352 return true;
7353 }
7354
7355 // has known usage?
7356 switch (paa->usage) {
7357 case AUDIO_USAGE_UNKNOWN:
7358 case AUDIO_USAGE_MEDIA:
7359 case AUDIO_USAGE_VOICE_COMMUNICATION:
7360 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7361 case AUDIO_USAGE_ALARM:
7362 case AUDIO_USAGE_NOTIFICATION:
7363 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7364 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7365 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7366 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7367 case AUDIO_USAGE_NOTIFICATION_EVENT:
7368 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7369 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7370 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7371 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007372 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007373 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007374 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007375 case AUDIO_USAGE_EMERGENCY:
7376 case AUDIO_USAGE_SAFETY:
7377 case AUDIO_USAGE_VEHICLE_STATUS:
7378 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007379 break;
7380 default:
7381 return false;
7382 }
7383 return true;
7384}
7385
François Gaffie2110e042015-03-24 08:41:51 +01007386audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7387{
7388 return mEngine->getForceUse(usage);
7389}
7390
7391bool AudioPolicyManager::isInCall()
7392{
7393 return isStateInCall(mEngine->getPhoneState());
7394}
7395
7396bool AudioPolicyManager::isStateInCall(int state)
7397{
7398 return is_state_in_call(state);
7399}
7400
Eric Laurent74b71512019-11-06 17:21:57 -08007401bool AudioPolicyManager::isCallAudioAccessible()
7402{
7403 audio_mode_t mode = mEngine->getPhoneState();
7404 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007405 || (mode == AUDIO_MODE_CALL_SCREEN)
7406 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007407}
7408
Eric Laurentd60560a2015-04-10 11:31:20 -07007409void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7410{
7411 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007412 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007413 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007414 sourceDesc->sinkDevice()->equals(deviceDesc))
7415 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007416 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007417 }
7418 }
7419
7420 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7421 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7422 bool release = false;
7423 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7424 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7425 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7426 source->ext.device.type == deviceDesc->type()) {
7427 release = true;
7428 }
7429 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007430 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007431 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7432 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7433 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007434 sink->ext.device.type == deviceDesc->type() &&
7435 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7436 || strncmp(sink->ext.device.address, address,
7437 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007438 release = true;
7439 }
7440 }
7441 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007442 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7443 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007444 }
7445 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007446
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007447 mInputs.clearSessionRoutesForDevice(deviceDesc);
7448
Francois Gaffie716e1432019-01-14 16:58:59 +01007449 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007450}
7451
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007452void AudioPolicyManager::modifySurroundFormats(
7453 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007454 std::unordered_set<audio_format_t> enforcedSurround(
7455 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007456 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7457 for (const auto& pair : mConfig.getSurroundFormats()) {
7458 allSurround.insert(pair.first);
7459 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7460 }
Phil Burk09bc4612016-02-24 15:58:15 -08007461
7462 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7463 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007464 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007465 // This is the resulting set of formats depending on the surround mode:
7466 // 'all surround' = allSurround
7467 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7468 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7469 // 'manual surround' = mManualSurroundFormats
7470 // AUTO: formats v 'enforced surround'
7471 // ALWAYS: formats v 'all surround' v 'enforced surround'
7472 // NEVER: formats ^ 'non-surround'
7473 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007474
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007475 std::unordered_set<audio_format_t> formatSet;
7476 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7477 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007478 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007479 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007480 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007481 formatSet.insert(*formatIter);
7482 }
7483 }
7484 } else {
7485 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7486 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007487 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007488
jiabin81772902018-04-02 17:52:27 -07007489 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007490 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007491 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7492 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7493 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007494 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007495 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7496 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7497 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007498 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007499 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007500 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007501 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007502 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007503 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007504}
7505
jiabin06e4bab2019-07-29 10:13:34 -07007506void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7507 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007508 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7509 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7510
7511 // If NEVER, then remove support for channelMasks > stereo.
7512 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007513 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7514 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007515 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007516 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007517 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007518 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007519 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007520 }
7521 }
jiabin81772902018-04-02 17:52:27 -07007522 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7523 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7524 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007525 bool supports5dot1 = false;
7526 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007527 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007528 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7529 supports5dot1 = true;
7530 break;
7531 }
7532 }
7533 // If not then add 5.1 support.
7534 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007535 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007536 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007537 }
Phil Burk09bc4612016-02-24 15:58:15 -08007538 }
7539}
7540
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007541void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007542 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007543 AudioProfileVector &profiles)
7544{
7545 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007546 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007547
François Gaffie112b0af2015-11-19 16:13:25 +01007548 // Format MUST be checked first to update the list of AudioProfile
7549 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007550 reply = mpClientInterface->getParameters(
7551 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007552 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007553 AudioParameter repliedParameters(reply);
7554 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007555 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007556 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7557 return;
7558 }
Phil Burk09bc4612016-02-24 15:58:15 -08007559 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007560 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007561 if (device == AUDIO_DEVICE_OUT_HDMI
7562 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007563 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007564 }
jiabin3e277cc2019-09-10 14:27:34 -07007565 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007566 }
François Gaffie112b0af2015-11-19 16:13:25 +01007567
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007568 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007569 ChannelMaskSet channelMasks;
7570 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007571 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007572 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007573
7574 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007575 reply = mpClientInterface->getParameters(
7576 ioHandle,
7577 requestedParameters.toString() + ";" +
7578 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007579 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007580 AudioParameter repliedParameters(reply);
7581 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007582 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007583 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007584 }
7585 }
7586 if (profiles.hasDynamicChannelsFor(format)) {
7587 reply = mpClientInterface->getParameters(ioHandle,
7588 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007589 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007590 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007591 AudioParameter repliedParameters(reply);
7592 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007593 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007594 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007595 if (device == AUDIO_DEVICE_OUT_HDMI
7596 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007597 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007598 }
François Gaffie112b0af2015-11-19 16:13:25 +01007599 }
7600 }
jiabin3e277cc2019-09-10 14:27:34 -07007601 addDynamicAudioProfileAndSort(
7602 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007603 }
7604}
Eric Laurentd60560a2015-04-10 11:31:20 -07007605
Mikhail Naganovdc769682018-05-04 15:34:08 -07007606status_t AudioPolicyManager::installPatch(const char *caller,
7607 audio_patch_handle_t *patchHandle,
7608 AudioIODescriptorInterface *ioDescriptor,
7609 const struct audio_patch *patch,
7610 int delayMs)
7611{
7612 ssize_t index = mAudioPatches.indexOfKey(
7613 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7614 *patchHandle : ioDescriptor->getPatchHandle());
7615 sp<AudioPatch> patchDesc;
7616 status_t status = installPatch(
7617 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7618 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007619 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007620 }
7621 return status;
7622}
7623
7624status_t AudioPolicyManager::installPatch(const char *caller,
7625 ssize_t index,
7626 audio_patch_handle_t *patchHandle,
7627 const struct audio_patch *patch,
7628 int delayMs,
7629 uid_t uid,
7630 sp<AudioPatch> *patchDescPtr)
7631{
7632 sp<AudioPatch> patchDesc;
7633 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7634 if (index >= 0) {
7635 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007636 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007637 }
7638
7639 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7640 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7641 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7642 if (status == NO_ERROR) {
7643 if (index < 0) {
7644 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007645 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007646 } else {
7647 patchDesc->mPatch = *patch;
7648 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007649 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007650 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007651 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007652 }
7653 nextAudioPortGeneration();
7654 mpClientInterface->onAudioPatchListUpdate();
7655 }
7656 if (patchDescPtr) *patchDescPtr = patchDesc;
7657 return status;
7658}
7659
jiabinbce0c1d2020-10-05 11:20:18 -07007660bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7661{
7662 const TrackClientVector activeClients = output->getActiveClients();
7663 if (activeClients.empty()) {
7664 return true;
7665 }
7666 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7667 if (index < 0) {
7668 ALOGE("%s, no audio patch found while there are active clients on output %d",
7669 __func__, output->getId());
7670 return false;
7671 }
7672 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7673 DeviceVector routedDevices;
7674 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7675 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7676 patchDesc->mPatch.sinks[i].id);
7677 if (device == nullptr) {
7678 ALOGE("%s, no audio device found with id(%d)",
7679 __func__, patchDesc->mPatch.sinks[i].id);
7680 return false;
7681 }
7682 routedDevices.add(device);
7683 }
7684 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007685 if (client->isInvalid()) {
7686 // No need to take care about invalidated clients.
7687 continue;
7688 }
jiabinbce0c1d2020-10-05 11:20:18 -07007689 sp<DeviceDescriptor> preferredDevice =
7690 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7691 if (mEngine->getOutputDevicesForAttributes(
7692 client->attributes(), preferredDevice, false) == routedDevices) {
7693 return false;
7694 }
7695 }
7696 return true;
7697}
7698
7699sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007700 const sp<IOProfile>& profile, const DeviceVector& devices,
7701 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007702{
7703 for (const auto& device : devices) {
7704 // TODO: This should be checking if the profile supports the device combo.
7705 if (!profile->supportsDevice(device)) {
7706 return nullptr;
7707 }
7708 }
7709 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7710 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007711 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007712 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7713 if (status != NO_ERROR) {
7714 return nullptr;
7715 }
7716
7717 // Here is where the out_set_parameters() for card & device gets called
7718 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7719 const audio_devices_t deviceType = device->type();
7720 const String8 &address = String8(device->address().c_str());
7721 if (!address.isEmpty()) {
7722 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7723 mpClientInterface->setParameters(output, String8(param));
7724 free(param);
7725 }
7726 updateAudioProfiles(device, output, profile->getAudioProfiles());
7727 if (!profile->hasValidAudioProfile()) {
7728 ALOGW("%s() missing param", __func__);
7729 desc->close();
7730 return nullptr;
7731 } else if (profile->hasDynamicAudioProfile()) {
7732 desc->close();
7733 output = AUDIO_IO_HANDLE_NONE;
7734 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7735 profile->pickAudioProfile(
7736 config.sample_rate, config.channel_mask, config.format);
7737 config.offload_info.sample_rate = config.sample_rate;
7738 config.offload_info.channel_mask = config.channel_mask;
7739 config.offload_info.format = config.format;
7740
Eric Laurentb4f42a92022-01-17 17:37:31 +01007741 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007742 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7743 if (status != NO_ERROR) {
7744 return nullptr;
7745 }
7746 }
7747
7748 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007749
jiabinbce0c1d2020-10-05 11:20:18 -07007750 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7751 sp<AudioPolicyMix> policyMix;
7752 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7753 policyMix->setOutput(desc);
7754 desc->mPolicyMix = policyMix;
7755 } else {
7756 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7757 address.string());
7758 }
7759
Eric Laurentb4f42a92022-01-17 17:37:31 +01007760 } else if (hasPrimaryOutput() && profile->getModule()
7761 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7762 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7763 // no duplicated output for:
7764 // - direct outputs
7765 // - outputs used by dynamic policy mixes
7766 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007767 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7768
7769 //TODO: configure audio effect output stage here
7770
7771 // open a duplicating output thread for the new output and the primary output
7772 sp<SwAudioOutputDescriptor> dupOutputDesc =
7773 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7774 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7775 if (status == NO_ERROR) {
7776 // add duplicated output descriptor
7777 addOutput(duplicatedOutput, dupOutputDesc);
7778 } else {
7779 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7780 mPrimaryOutput->mIoHandle, output);
7781 desc->close();
7782 removeOutput(output);
7783 nextAudioPortGeneration();
7784 return nullptr;
7785 }
7786 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007787 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7788 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7789 mPrimaryOutput = desc;
7790 }
jiabinbce0c1d2020-10-05 11:20:18 -07007791 return desc;
7792}
7793
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007794} // namespace android