blob: 2aa3be618c269ae5fa0a7b17fbf8bee48aeb99f5 [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
Michael Chana94fbb22018-04-24 14:31:19 +1000938// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
939// search to profiles for direct outputs.
940sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100941 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000942 uint32_t samplingRate,
943 audio_format_t format,
944 audio_channel_mask_t channelMask,
945 audio_output_flags_t flags,
946 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700947{
Michael Chana94fbb22018-04-24 14:31:19 +1000948 if (directOnly) {
949 // only retain flags that will drive the direct output profile selection
950 // if explicitly requested
951 static const uint32_t kRelevantFlags =
952 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700953 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000954 flags =
955 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
956 }
Eric Laurent861a6282015-05-18 15:40:16 -0700957
958 sp<IOProfile> profile;
959
Mikhail Naganovd4120142017-12-06 15:49:22 -0800960 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800961 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100962 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700963 samplingRate, NULL /*updatedSamplingRate*/,
964 format, NULL /*updatedFormat*/,
965 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700966 flags)) {
967 continue;
968 }
969 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100970 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700971 continue;
972 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800973 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700974 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800975 continue;
976 }
Michael Chana94fbb22018-04-24 14:31:19 +1000977 if (!directOnly) return curProfile;
978 // when searching for direct outputs, if several profiles are compatible, give priority
979 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100980 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700981 continue;
982 }
983 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100984 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700985 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700986 }
Eric Laurente552edb2014-03-10 17:42:56 -0700987 }
988 }
Eric Laurent861a6282015-05-18 15:40:16 -0700989 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700990}
991
Eric Laurentfa0f6742021-08-17 18:39:44 +0200992sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +0200993 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200994{
995 for (const auto& hwModule : mHwModules) {
996 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200997 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200998 continue;
999 }
1000 // reject profiles not corresponding to a device currently available
1001 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1002 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1003 continue;
1004 }
1005 if (!devices.empty()) {
1006 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1007 != devices.size()) {
1008 continue;
1009 }
1010 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001011 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1012 return curProfile;
1013 }
1014 }
1015 return nullptr;
1016}
1017
Eric Laurentf4e63452017-11-06 19:31:46 +00001018audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001019{
François Gaffiec005e562018-11-06 15:04:49 +01001020 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001021
1022 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1023 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1024 // format, flags, etc. This may result in some discrepancy for functions that utilize
1025 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1026 // and AudioSystem::getOutputSamplingRate().
1027
François Gaffie11d30102018-11-02 16:09:09 +01001028 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001029 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001030
François Gaffie11d30102018-11-02 16:09:09 +01001031 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1032 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001033 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001034}
1035
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001036status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1037 const audio_attributes_t *srcAttr,
1038 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001039{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001040 if (srcAttr != NULL) {
1041 if (!isValidAttributes(srcAttr)) {
1042 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1043 __func__,
1044 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1045 srcAttr->tags);
1046 return BAD_VALUE;
1047 }
1048 *dstAttr = *srcAttr;
1049 } else {
1050 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1051 ALOGE("%s: invalid stream type", __func__);
1052 return BAD_VALUE;
1053 }
François Gaffiec005e562018-11-06 15:04:49 +01001054 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001055 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001056
1057 // Only honor audibility enforced when required. The client will be
1058 // forced to reconnect if the forced usage changes.
1059 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001060 dstAttr->flags = static_cast<audio_flags_mask_t>(
1061 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001062 }
1063
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001064 return NO_ERROR;
1065}
1066
Kevin Rocard153f92d2018-12-18 18:33:28 -08001067status_t AudioPolicyManager::getOutputForAttrInt(
1068 audio_attributes_t *resultAttr,
1069 audio_io_handle_t *output,
1070 audio_session_t session,
1071 const audio_attributes_t *attr,
1072 audio_stream_type_t *stream,
1073 uid_t uid,
1074 const audio_config_t *config,
1075 audio_output_flags_t *flags,
1076 audio_port_handle_t *selectedDeviceId,
1077 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001078 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001079 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001080{
François Gaffiec005e562018-11-06 15:04:49 +01001081 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001082 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001083 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001084 const sp<DeviceDescriptor> requestedDevice =
1085 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1086
Eric Laurent8a1095a2019-11-08 14:44:16 -08001087 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001088 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1089 if (status != NO_ERROR) {
1090 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001091 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001092 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001093 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001094 }
François Gaffiec005e562018-11-06 15:04:49 +01001095 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001096
François Gaffiec005e562018-11-06 15:04:49 +01001097 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1098 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001099
Kevin Rocard153f92d2018-12-18 18:33:28 -08001100 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1101 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1102 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001103 sp<AudioPolicyMix> primaryMix;
1104 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001105 if (status != OK) {
1106 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001107 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001108
Kevin Rocard153f92d2018-12-18 18:33:28 -08001109 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001110 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001111
1112 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001113 if ((usePrimaryOutputFromPolicyMixes
1114 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001115 && !audio_is_linear_pcm(config->format)) {
1116 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001117 return BAD_VALUE;
1118 }
1119 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001120 sp<DeviceDescriptor> deviceDesc =
1121 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1122 primaryMix->mDeviceAddress,
1123 AUDIO_FORMAT_DEFAULT);
1124 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001125 if (deviceDesc != nullptr
1126 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001127 audio_io_handle_t newOutput;
1128 status = openDirectOutput(
1129 *stream, session, config,
1130 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1131 DeviceVector(deviceDesc), &newOutput);
1132 if (status != NO_ERROR) {
1133 policyDesc = nullptr;
1134 } else {
1135 policyDesc = mOutputs.valueFor(newOutput);
1136 primaryMix->setOutput(policyDesc);
1137 }
1138 }
1139 if (policyDesc != nullptr) {
1140 policyDesc->mPolicyMix = primaryMix;
1141 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001142 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001143
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001144 ALOGV("getOutputForAttr() returns output %d", *output);
1145 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1146 *outputType = API_OUT_MIX_PLAYBACK;
1147 } else {
1148 *outputType = API_OUTPUT_LEGACY;
1149 }
1150 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001151 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001152 }
François Gaffiec005e562018-11-06 15:04:49 +01001153 // Virtual sources must always be dynamicaly or explicitly routed
1154 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1155 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1156 return BAD_VALUE;
1157 }
1158 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1159 // in order to let the choice of the order to future vendor engine
1160 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001161
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001162 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001163 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001164 }
1165
Nadav Barb2f18162018-07-18 13:01:53 +03001166 // Set incall music only if device was explicitly set, and fallback to the device which is
1167 // chosen by the engine if not.
1168 // FIXME: provide a more generic approach which is not device specific and move this back
1169 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001170 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001171 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001172 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001173 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001174 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001175 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001176 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001177 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001178 }
1179 }
1180
François Gaffiec005e562018-11-06 15:04:49 +01001181 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1182 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1183 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001184
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001185 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001186 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001187 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001188 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001189 ALOGV("%s() Using MSD devices %s instead of devices %s",
1190 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001191 } else {
1192 *output = AUDIO_IO_HANDLE_NONE;
1193 }
1194 }
1195 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001196 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001197 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001198 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001199 if (*output == AUDIO_IO_HANDLE_NONE) {
1200 return INVALID_OPERATION;
1201 }
Paul McLeanaa981192015-03-21 09:55:15 -07001202
François Gaffiec005e562018-11-06 15:04:49 +01001203 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001204 for (auto &outputDevice : outputDevices) {
1205 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1206 *selectedDeviceId = outputDevice->getId();
1207 break;
1208 }
1209 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001210
Eric Laurent8a1095a2019-11-08 14:44:16 -08001211 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1212 *outputType = API_OUTPUT_TELEPHONY_TX;
1213 } else {
1214 *outputType = API_OUTPUT_LEGACY;
1215 }
1216
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001217 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1218
1219 return NO_ERROR;
1220}
1221
1222status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1223 audio_io_handle_t *output,
1224 audio_session_t session,
1225 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001226 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001227 const audio_config_t *config,
1228 audio_output_flags_t *flags,
1229 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001230 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001231 std::vector<audio_io_handle_t> *secondaryOutputs,
1232 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001233{
1234 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1235 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1236 return INVALID_OPERATION;
1237 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001238 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001239 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001240 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001241 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001242 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001243 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001244 const sp<DeviceDescriptor> requestedDevice =
1245 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1246
1247 // Prevent from storing invalid requested device id in clients
1248 const audio_port_handle_t sanitizedRequestedPortId =
1249 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1250 *selectedDeviceId = sanitizedRequestedPortId;
1251
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001252 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001253 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001254 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001255 if (status != NO_ERROR) {
1256 return status;
1257 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001258 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001259 if (secondaryOutputs != nullptr) {
1260 for (auto &secondaryMix : secondaryMixes) {
1261 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1262 if (outputDesc != nullptr &&
1263 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1264 secondaryOutputs->push_back(outputDesc->mIoHandle);
1265 weakSecondaryOutputDescs.push_back(outputDesc);
1266 }
1267 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001268 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001269
Eric Laurent8fc147b2018-07-22 19:13:55 -07001270 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001271 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001272 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001273 };
jiabin4ef93452019-09-10 14:29:54 -07001274 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001275
Eric Laurentc209fe42020-06-05 18:11:23 -07001276 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001277 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001278 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001279 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001280 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001281 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001282 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001283 std::move(weakSecondaryOutputDescs),
1284 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001285 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001286
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001287 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1288 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001289
Eric Laurente83b55d2014-11-14 10:06:21 -08001290 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001291}
1292
Eric Laurentc529cf62020-04-17 18:19:10 -07001293status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1294 audio_session_t session,
1295 const audio_config_t *config,
1296 audio_output_flags_t flags,
1297 const DeviceVector &devices,
1298 audio_io_handle_t *output) {
1299
1300 *output = AUDIO_IO_HANDLE_NONE;
1301
1302 // skip direct output selection if the request can obviously be attached to a mixed output
1303 // and not explicitly requested
1304 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1305 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1306 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1307 return NAME_NOT_FOUND;
1308 }
1309
1310 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1311 // This prevents creating an offloaded track and tearing it down immediately after start
1312 // when audioflinger detects there is an active non offloadable effect.
1313 // FIXME: We should check the audio session here but we do not have it in this context.
1314 // This may prevent offloading in rare situations where effects are left active by apps
1315 // in the background.
1316 sp<IOProfile> profile;
1317 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1318 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1319 profile = getProfileForOutput(
1320 devices, config->sample_rate, config->format, config->channel_mask,
1321 flags, true /* directOnly */);
1322 }
1323
1324 if (profile == nullptr) {
1325 return NAME_NOT_FOUND;
1326 }
1327
1328 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1329 for (size_t i = 0; i < mOutputs.size(); i++) {
1330 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1331 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1332 // reuse direct output if currently open by the same client
1333 // and configured with same parameters
1334 if ((config->sample_rate == desc->getSamplingRate()) &&
1335 (config->format == desc->getFormat()) &&
1336 (config->channel_mask == desc->getChannelMask()) &&
1337 (session == desc->mDirectClientSession)) {
1338 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001339 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001340 mOutputs.keyAt(i), session);
1341 *output = mOutputs.keyAt(i);
1342 return NO_ERROR;
1343 }
1344 }
1345 }
1346
1347 if (!profile->canOpenNewIo()) {
1348 return NAME_NOT_FOUND;
1349 }
1350
1351 sp<SwAudioOutputDescriptor> outputDesc =
1352 new SwAudioOutputDescriptor(profile, mpClientInterface);
1353
Michael Chan6fb34492020-12-08 15:44:49 +11001354 // An MSD patch may be using the only output stream that can service this request. Release
1355 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001356 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001357
Eric Laurentf1f22e72021-07-13 14:04:14 +02001358 status_t status =
1359 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001360
1361 // only accept an output with the requested parameters
1362 if (status != NO_ERROR ||
1363 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1364 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1365 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1366 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1367 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1368 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1369 config->channel_mask, outputDesc->getChannelMask());
1370 if (*output != AUDIO_IO_HANDLE_NONE) {
1371 outputDesc->close();
1372 }
1373 // fall back to mixer output if possible when the direct output could not be open
1374 if (audio_is_linear_pcm(config->format) &&
1375 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1376 return NAME_NOT_FOUND;
1377 }
1378 *output = AUDIO_IO_HANDLE_NONE;
1379 return BAD_VALUE;
1380 }
1381 outputDesc->mDirectOpenCount = 1;
1382 outputDesc->mDirectClientSession = session;
1383
1384 addOutput(*output, outputDesc);
1385 mPreviousOutputs = mOutputs;
1386 ALOGV("%s returns new direct output %d", __func__, *output);
1387 mpClientInterface->onAudioPortListUpdate();
1388 return NO_ERROR;
1389}
1390
François Gaffie11d30102018-11-02 16:09:09 +01001391audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1392 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001393 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001394 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001395 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001396 audio_output_flags_t *flags,
1397 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001398{
Andy Hungc88b0642018-04-27 15:42:35 -07001399 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001400
jiabine375d412019-02-26 12:54:53 -08001401 // Discard haptic channel mask when forcing muting haptic channels.
1402 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001403 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1404 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001405
Eric Laurente552edb2014-03-10 17:42:56 -07001406 // open a direct output if required by specified parameters
1407 //force direct flag if offload flag is set: offloading implies a direct output stream
1408 // and all common behaviors are driven by checking only the direct flag
1409 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001410 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1411 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001412 }
Nadav Bar766fb022018-01-07 12:18:03 +02001413 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1414 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001415 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001416
1417 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1418
Eric Laurente83b55d2014-11-14 10:06:21 -08001419 // only allow deep buffering for music stream type
1420 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001421 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001422 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001423 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001424 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1425 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001426 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001427 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001428 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001429 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001430 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001431 audio_is_linear_pcm(config->format) &&
1432 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001433 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001434 AUDIO_OUTPUT_FLAG_DIRECT);
1435 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001436 }
Eric Laurente552edb2014-03-10 17:42:56 -07001437
Carter Hsua3abb402021-10-26 11:11:20 +08001438 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1439 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1440 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1441 }
1442
Eric Laurentfa0f6742021-08-17 18:39:44 +02001443 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001444 && canBeSpatializedInt(attr, config,
1445 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02001446 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001447 }
1448
Eric Laurentc529cf62020-04-17 18:19:10 -07001449 audio_config_t directConfig = *config;
1450 directConfig.channel_mask = channelMask;
1451 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1452 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001453 return output;
1454 }
1455
Eric Laurent14cbfca2016-03-17 09:42:16 -07001456 // A request for HW A/V sync cannot fallback to a mixed output because time
1457 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001458 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001459 return AUDIO_IO_HANDLE_NONE;
1460 }
1461
Eric Laurente552edb2014-03-10 17:42:56 -07001462 // ignoring channel mask due to downmix capability in mixer
1463
1464 // open a non direct output
1465
1466 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001467 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001468 // get which output is suitable for the specified stream. The actual
1469 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001470 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001471
Eric Laurent8838a382014-09-08 16:44:28 -07001472 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001473 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001474 output = selectOutput(
1475 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001476 }
François Gaffie11d30102018-11-02 16:09:09 +01001477 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001478 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001479 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001480
Eric Laurente552edb2014-03-10 17:42:56 -07001481 return output;
1482}
1483
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001484sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001485 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1486 mAvailableInputDevices);
1487 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1488}
1489
1490DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1491 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1492 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001493}
1494
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001495const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001496 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001497 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1498 if (msdModule != 0) {
1499 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1500 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1501 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1502 const struct audio_port_config *source = &patch->mPatch.sources[j];
1503 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1504 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001505 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001506 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001507 }
1508 }
1509 }
1510 return msdPatches;
1511}
1512
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001513bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1514 ssize_t index = mAudioPatches.indexOfKey(handle);
1515 if (index < 0) {
1516 return false;
1517 }
1518 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1519 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1520 if (msdModule == nullptr) {
1521 return false;
1522 }
1523 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1524 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1525 return true;
1526 }
1527 index = getMsdOutputPatches().indexOfKey(handle);
1528 if (index < 0) {
1529 return false;
1530 }
1531 return true;
1532}
1533
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001534status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1535 const InputProfileCollection &inputProfiles,
1536 const OutputProfileCollection &outputProfiles,
1537 const sp<DeviceDescriptor> &sourceDevice,
1538 const sp<DeviceDescriptor> &sinkDevice,
1539 AudioProfileVector& sourceProfiles,
1540 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001541 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001542 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001543 return NO_INIT;
1544 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001545 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001546 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001547 return NO_INIT;
1548 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001549 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001550 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1551 inProfile->supportsDevice(sourceDevice)) {
1552 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001553 }
1554 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001555 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001556 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001557 outProfile->supportsDevice(sinkDevice)) {
1558 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001559 }
1560 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001561 return NO_ERROR;
1562}
1563
1564status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1565 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1566 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1567{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001568 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001569 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1570 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1571 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001572 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001573 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1574 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001575 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001576 }
1577 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1578 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1579 sinkConfig->format = bestSinkConfig.format;
1580 // For encoded streams force direct flag to prevent downstream mixing.
1581 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1582 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001583 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1584 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001585 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001586 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1587 // raw and IEC61937 framed streams.
1588 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1589 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1590 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001591 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1592 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1593 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1594 sourceConfig->format = bestSinkConfig.format;
1595 // Copy input stream directly without any processing (e.g. resampling).
1596 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1597 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1598 if (hwAvSync) {
1599 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1600 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1601 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1602 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1603 }
1604 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1605 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1606 sinkConfig->config_mask |= config_mask;
1607 sourceConfig->config_mask |= config_mask;
1608 return NO_ERROR;
1609}
1610
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001611PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1612 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001613{
1614 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001615 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1616 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1617 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1618 if (deviceModule == nullptr) {
1619 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1620 return patchBuilder;
1621 }
1622 const InputProfileCollection inputProfiles = msdIsSource ?
1623 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1624 const OutputProfileCollection outputProfiles = msdIsSource ?
1625 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1626
1627 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1628 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1629 device : getMsdAudioOutDevices().itemAt(0);
1630 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1631
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001632 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1633 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001634 AudioProfileVector sourceProfiles;
1635 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001636 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1637 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001638 for (auto hwAvSync : { true, false }) {
1639 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1640 sourceProfiles, sinkProfiles) != NO_ERROR) {
1641 continue;
1642 }
1643 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1644 &sinkConfig) == NO_ERROR) {
1645 // Found a matching config. Re-create PatchBuilder with this config.
1646 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1647 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001648 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001649 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001650 " supporting PCM format conversion.", __func__);
1651 return patchBuilder;
1652}
1653
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001654status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001655 DeviceVector devices;
1656 if (outputDevices != nullptr && outputDevices->size() > 0) {
1657 devices.add(*outputDevices);
1658 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001659 // Use media strategy for unspecified output device. This should only
1660 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1661 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001662 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001663 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001664 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001665 }
Michael Chan6fb34492020-12-08 15:44:49 +11001666 std::vector<PatchBuilder> patchesToCreate;
1667 for (auto i = 0u; i < devices.size(); ++i) {
1668 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001669 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001670 }
1671 // Retain only the MSD patches associated with outputDevices request.
1672 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001673 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001674 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1675 auto retainedPatch = false;
1676 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1677 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1678 patchesToRemove.removeItemsAt(i);
1679 retainedPatch = true;
1680 break;
1681 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001682 }
Michael Chan6fb34492020-12-08 15:44:49 +11001683 if (retainedPatch) {
1684 it = patchesToCreate.erase(it);
1685 continue;
1686 }
1687 ++it;
1688 }
1689 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1690 return NO_ERROR;
1691 }
1692 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1693 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001694 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001695 }
Michael Chan6fb34492020-12-08 15:44:49 +11001696 status_t status = NO_ERROR;
1697 for (const auto &p : patchesToCreate) {
1698 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1699 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1700 char message[256];
1701 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1702 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1703 currStatus == NO_ERROR ? "Success" : "Error",
1704 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1705 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1706 if (currStatus == NO_ERROR) {
1707 ALOGD("%s", message);
1708 } else {
1709 ALOGE("%s", message);
1710 if (status == NO_ERROR) {
1711 status = currStatus;
1712 }
1713 }
1714 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001715 return status;
1716}
1717
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001718void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1719 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001720 for (size_t i = 0; i < msdPatches.size(); i++) {
1721 const auto& patch = msdPatches[i];
1722 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1723 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1724 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1725 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1726 releaseAudioPatch(patch->getHandle(), mUidCached);
1727 break;
1728 }
1729 }
1730 }
1731}
1732
Dorin Drimus94d94412022-02-02 09:05:02 +01001733bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1734 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1735 AudioPatchCollection msdPatches = getMsdOutputPatches();
1736 for (size_t i = 0; i < msdPatches.size(); i++) {
1737 const auto& patch = msdPatches[i];
1738 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1739 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1740 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1741 const auto& foundDevice = devicesToCheck.getDevice(
1742 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1743 if (foundDevice != nullptr) {
1744 devicesToCheck.remove(foundDevice);
1745 if (devicesToCheck.isEmpty()) {
1746 return true;
1747 }
1748 }
1749 }
1750 }
1751 }
1752 return false;
1753}
1754
Eric Laurente0720872014-03-11 09:30:41 -07001755audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001756 audio_output_flags_t flags,
1757 audio_format_t format,
1758 audio_channel_mask_t channelMask,
1759 uint32_t samplingRate,
1760 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001761{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001762 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1763 "%s called with format %#x", __func__, format);
1764
jiabinebb6af42020-06-09 17:31:17 -07001765 // Return the output that haptic-generating attached to when 1) session id is specified,
1766 // 2) haptic-generating effect exists for given session id and 3) the output that
1767 // haptic-generating effect attached to is in given outputs.
1768 if (sessionId != AUDIO_SESSION_NONE) {
1769 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1770 sessionId, FX_IID_HAPTICGENERATOR);
1771 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1772 return hapticGeneratingOutput;
1773 }
1774 }
1775
Eric Laurent16c66dd2019-05-01 17:54:10 -07001776 // Flags disqualifying an output: the match must happen before calling selectOutput()
1777 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1778 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1779
1780 // Flags expressing a functional request: must be honored in priority over
1781 // other criteria
1782 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1783 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001784 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1785 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001786 // Flags expressing a performance request: have lower priority than serving
1787 // requested sampling rate or channel mask
1788 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1789 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1790 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1791
1792 const audio_output_flags_t functionalFlags =
1793 (audio_output_flags_t)(flags & kFunctionalFlags);
1794 const audio_output_flags_t performanceFlags =
1795 (audio_output_flags_t)(flags & kPerformanceFlags);
1796
1797 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1798
Eric Laurente552edb2014-03-10 17:42:56 -07001799 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001800 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001801 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001802 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001803 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001804 // with tiebreak preferring the minimum number of extra functional flags
1805 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001806 // 3: the output supporting the exact channel mask
1807 // 4: the output with a higher channel count than requested
1808 // 5: the output with a higher sampling rate than requested
1809 // 6: the output with the highest number of requested performance flags
1810 // 7: the output with the bit depth the closest to the requested one
1811 // 8: the primary output
1812 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001813
Eric Laurent16c66dd2019-05-01 17:54:10 -07001814 // matching criteria values in priority order for best matching output so far
1815 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001816
Eric Laurent16c66dd2019-05-01 17:54:10 -07001817 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1818 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1819 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001820
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001821 for (audio_io_handle_t output : outputs) {
1822 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001823 // matching criteria values in priority order for current output
1824 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001825
Eric Laurent16c66dd2019-05-01 17:54:10 -07001826 if (outputDesc->isDuplicated()) {
1827 continue;
1828 }
1829 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1830 continue;
1831 }
Eric Laurent8838a382014-09-08 16:44:28 -07001832
Eric Laurent16c66dd2019-05-01 17:54:10 -07001833 // If haptic channel is specified, use the haptic output if present.
1834 // When using haptic output, same audio format and sample rate are required.
1835 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001836 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001837 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1838 continue;
1839 }
1840 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001841 && format == outputDesc->getFormat()
1842 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001843 currentMatchCriteria[0] = outputHapticChannelCount;
1844 }
1845
1846 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001847 const int matchingFunctionalFlags =
1848 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1849 const int totalFunctionalFlags =
1850 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1851 // Prefer matching functional flags, but subtract unnecessary functional flags.
1852 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001853
1854 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001855 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1856 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001857 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1858 channelCount <= outputChannelCount) {
1859 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001860 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1861 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001862 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001863 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001864 currentMatchCriteria[3] = outputChannelCount;
1865 }
1866
1867 // sampling rate match
1868 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001869 samplingRate <= outputDesc->getSamplingRate()) {
1870 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001871 }
1872
1873 // performance flags match
1874 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1875
1876 // format match
1877 if (format != AUDIO_FORMAT_INVALID) {
1878 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001879 PolicyAudioPort::kFormatDistanceMax -
1880 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001881 }
1882
1883 // primary output match
1884 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1885
1886 // compare match criteria by priority then value
1887 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1888 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1889 bestMatchCriteria = currentMatchCriteria;
1890 bestOutput = output;
1891
1892 std::stringstream result;
1893 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1894 std::ostream_iterator<int>(result, " "));
1895 ALOGV("%s new bestOutput %d criteria %s",
1896 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001897 }
1898 }
1899
Eric Laurent16c66dd2019-05-01 17:54:10 -07001900 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001901}
1902
Eric Laurent8fc147b2018-07-22 19:13:55 -07001903status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001904{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001905 ALOGV("%s portId %d", __FUNCTION__, portId);
1906
1907 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1908 if (outputDesc == 0) {
1909 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001910 return BAD_VALUE;
1911 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001912 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001913
Eric Laurent8fc147b2018-07-22 19:13:55 -07001914 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001915 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001916
Eric Laurent733ce942017-12-07 12:18:25 -08001917 status_t status = outputDesc->start();
1918 if (status != NO_ERROR) {
1919 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001920 }
1921
Eric Laurent97ac8712018-07-27 18:59:02 -07001922 uint32_t delayMs;
1923 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001924
1925 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001926 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001927 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001928 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001929 if (delayMs != 0) {
1930 usleep(delayMs * 1000);
1931 }
1932
1933 return status;
1934}
1935
Eric Laurent97ac8712018-07-27 18:59:02 -07001936status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1937 const sp<TrackClientDescriptor>& client,
1938 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001939{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001940 // cannot start playback of STREAM_TTS if any other output is being used
1941 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001942
1943 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001944 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001945 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001946 auto clientStrategy = client->strategy();
1947 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001948 if (stream == AUDIO_STREAM_TTS) {
1949 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001950 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01001951 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001952 return INVALID_OPERATION;
1953 } else {
1954 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1955 }
1956 } else {
1957 // some playback other than beacon starts
1958 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1959 }
1960
Eric Laurent77305a62016-07-25 16:39:22 -07001961 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001962 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001963 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001964
François Gaffie11d30102018-11-02 16:09:09 +01001965 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001966 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001967 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001968 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001969 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001970 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001971 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001972 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001973 } else {
1974 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001975 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001976 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1977 AUDIO_FORMAT_DEFAULT);
1978 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1979 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001980 }
1981
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001982 // requiresMuteCheck is false when we can bypass mute strategy.
1983 // It covers a common case when there is no materially active audio
1984 // and muting would result in unnecessary delay and dropped audio.
1985 const uint32_t outputLatencyMs = outputDesc->latency();
1986 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1987
Eric Laurente552edb2014-03-10 17:42:56 -07001988 // increment usage count for this stream on the requested output:
1989 // NOTE that the usage count is the same for duplicated output and hardware output which is
1990 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001991 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001992
1993 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001994 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1995 client->isPreferredDeviceForExclusiveUse()) {
1996 // Preferred device may be exclusive, use only if no other active clients on this output
1997 devices = DeviceVector(
1998 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1999 } else {
2000 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2001 }
François Gaffie11d30102018-11-02 16:09:09 +01002002 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002003 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002004 }
2005 }
Eric Laurente552edb2014-03-10 17:42:56 -07002006
François Gaffiec005e562018-11-06 15:04:49 +01002007 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002008 selectOutputForMusicEffects();
2009 }
2010
François Gaffie1c878552018-11-22 16:53:21 +01002011 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002012 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002013 if (devices.isEmpty()) {
2014 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002015 }
François Gaffiec005e562018-11-06 15:04:49 +01002016 bool shouldWait =
2017 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2018 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2019 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002020 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002021 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002022 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002023 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002024 // An output has a shared device if
2025 // - managed by the same hw module
2026 // - supports the currently selected device
2027 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002028 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002029
Eric Laurent77305a62016-07-25 16:39:22 -07002030 // force a device change if any other output is:
2031 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002032 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002033 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002034 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002035 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002036 // change the device currently selected by the other output.
2037 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002038 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002039 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002040 force = true;
2041 }
2042 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002043 // a notification so that audio focus effect can propagate, or that a mute/unmute
2044 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002045 const uint32_t latencyMs = desc->latency();
2046 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2047
2048 if (shouldWait && isActive && (waitMs < latencyMs)) {
2049 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002050 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002051
2052 // Require mute check if another output is on a shared device
2053 // and currently active to have proper drain and avoid pops.
2054 // Note restoring AudioTracks onto this output needs to invoke
2055 // a volume ramp if there is no mute.
2056 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002057 }
2058 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002059
2060 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002061 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002062
Eric Laurente552edb2014-03-10 17:42:56 -07002063 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002064 auto &curves = getVolumeCurves(client->attributes());
2065 checkAndSetVolume(curves, client->volumeSource(),
2066 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002067 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002068 outputDesc->devices().types(), 0 /*delay*/,
2069 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002070
2071 // update the outputs if starting an output with a stream that can affect notification
2072 // routing
2073 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002074
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002075 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002076 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002077 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2078 }
Eric Laurentdc462862016-07-19 12:29:53 -07002079
2080 if (waitMs > muteWaitMs) {
2081 *delayMs = waitMs - muteWaitMs;
2082 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002083
2084 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2085 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2086 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2087 // change occurs after the MixerThread starts and causes a stream volume
2088 // glitch.
2089 //
2090 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002091 }
Eric Laurentdc462862016-07-19 12:29:53 -07002092
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002093 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002094 mEngine->getForceUse(
2095 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002096 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002097 }
2098
Eric Laurent97ac8712018-07-27 18:59:02 -07002099 // Automatically enable the remote submix input when output is started on a re routing mix
2100 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002101 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2102 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002103 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2104 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2105 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002106 "remote-submix",
2107 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002108 }
2109
Eric Laurente552edb2014-03-10 17:42:56 -07002110 return NO_ERROR;
2111}
2112
Eric Laurent8fc147b2018-07-22 19:13:55 -07002113status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002114{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002115 ALOGV("%s portId %d", __FUNCTION__, portId);
2116
2117 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2118 if (outputDesc == 0) {
2119 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002120 return BAD_VALUE;
2121 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002122 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002123
Eric Laurent97ac8712018-07-27 18:59:02 -07002124 ALOGV("stopOutput() output %d, stream %d, session %d",
2125 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002126
Eric Laurent97ac8712018-07-27 18:59:02 -07002127 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002128
Eric Laurent733ce942017-12-07 12:18:25 -08002129 if (status == NO_ERROR ) {
2130 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002131 }
2132 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002133}
2134
Eric Laurent97ac8712018-07-27 18:59:02 -07002135status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2136 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002137{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002138 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002139 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002140 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002141
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002142 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2143
François Gaffie1c878552018-11-22 16:53:21 +01002144 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2145 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002146 // Automatically disable the remote submix input when output is stopped on a
2147 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002148 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002149 if (isSingleDeviceType(
2150 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002151 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002152 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002153 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2154 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002155 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002156 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002157 }
2158 }
2159 bool forceDeviceUpdate = false;
2160 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002161 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002162 forceDeviceUpdate = true;
2163 }
2164
Eric Laurente552edb2014-03-10 17:42:56 -07002165 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002166 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002167
Eric Laurente552edb2014-03-10 17:42:56 -07002168 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002169 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002170 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002171 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002172
2173 // If the routing does not change, if an output is routed on a device using HwGain
2174 // (aka setAudioPortConfig) and there are still active clients following different
2175 // volume group(s), force reapply volume
2176 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2177 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2178
Eric Laurente552edb2014-03-10 17:42:56 -07002179 // delay the device switch by twice the latency because stopOutput() is executed when
2180 // the track stop() command is received and at that time the audio track buffer can
2181 // still contain data that needs to be drained. The latency only covers the audio HAL
2182 // and kernel buffers. Also the latency does not always include additional delay in the
2183 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002184 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2185 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002186
2187 // force restoring the device selection on other active outputs if it differs from the
2188 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002189 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002190 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002191 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002192 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002193 desc->isActive() &&
2194 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002195 (newDevices != desc->devices())) {
2196 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2197 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002198
François Gaffie11d30102018-11-02 16:09:09 +01002199 setOutputDevices(desc, newDevices2, force, delayMs);
2200
Eric Laurent57de36c2016-09-28 16:59:11 -07002201 // re-apply device specific volume if not done by setOutputDevice()
2202 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002203 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002204 }
Eric Laurente552edb2014-03-10 17:42:56 -07002205 }
2206 }
2207 // update the outputs if stopping one with a stream that can affect notification routing
2208 handleNotificationRoutingForStream(stream);
2209 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002210
2211 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2212 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002213 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002214 }
2215
François Gaffiec005e562018-11-06 15:04:49 +01002216 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002217 selectOutputForMusicEffects();
2218 }
Eric Laurente552edb2014-03-10 17:42:56 -07002219 return NO_ERROR;
2220 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002221 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002222 return INVALID_OPERATION;
2223 }
2224}
2225
jiabinbce0c1d2020-10-05 11:20:18 -07002226bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002227{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002228 ALOGV("%s portId %d", __FUNCTION__, portId);
2229
2230 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2231 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002232 // If an output descriptor is closed due to a device routing change,
2233 // then there are race conditions with releaseOutput from tracks
2234 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2235 // destroyed shortly thereafter.
2236 //
2237 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002238 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002239 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002240 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002241
2242 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002243
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302244 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2245 if (outputDesc->isClientActive(client)) {
2246 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2247 stopOutput(portId);
2248 }
2249
Eric Laurent8fc147b2018-07-22 19:13:55 -07002250 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2251 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002252 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002253 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002254 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002255 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002256 if (--outputDesc->mDirectOpenCount == 0) {
2257 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002258 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002259 }
2260 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302261
Andy Hung39efb7a2018-09-26 15:39:28 -07002262 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002263 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2264 // The output is pending reopened to query dynamic profiles and
2265 // there is no active clients
2266 closeOutput(outputDesc->mIoHandle);
2267 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2268 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2269 if (newOutputDesc == nullptr) {
2270 ALOGE("%s failed to open output", __func__);
2271 }
2272 return true;
2273 }
2274 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002275}
2276
Eric Laurentcaf7f482014-11-25 17:50:47 -08002277status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2278 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002279 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002280 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002281 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002282 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002283 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002284 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002285 input_type_t *inputType,
2286 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002287{
François Gaffiec005e562018-11-06 15:04:49 +01002288 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002289 "flags %#x attributes=%s requested device ID %d",
2290 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2291 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002292
Eric Laurentad2e7b92017-09-14 20:06:42 -07002293 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002294 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002295 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002296 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002297 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002298 sp<AudioInputDescriptor> inputDesc;
2299 sp<RecordClientDescriptor> clientDesc;
2300 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002301 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002302 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002303
2304 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2305 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2306 return INVALID_OPERATION;
2307 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002308
Francois Gaffie716e1432019-01-14 16:58:59 +01002309 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2310 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002311 }
2312
Paul McLean466dc8e2015-04-17 13:15:36 -06002313 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002314 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002315 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002316
Eric Laurentad2e7b92017-09-14 20:06:42 -07002317 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2318 // possible
2319 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2320 *input != AUDIO_IO_HANDLE_NONE) {
2321 ssize_t index = mInputs.indexOfKey(*input);
2322 if (index < 0) {
2323 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2324 status = BAD_VALUE;
2325 goto error;
2326 }
2327 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002328 RecordClientVector clients = inputDesc->getClientsForSession(session);
2329 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002330 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2331 status = BAD_VALUE;
2332 goto error;
2333 }
2334 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2335 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002336 // corresponds to a new client and is only permitted from the same UID.
2337 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002338 if (clients.size() > 1) {
2339 for (const auto& client : clients) {
2340 // The client map is ordered by key values (portId) and portIds are allocated
2341 // incrementaly. So the first client in this list is the one opened by audio flinger
2342 // when the mmap stream is created and should be ignored as it does not correspond
2343 // to an actual client
2344 if (client == *clients.cbegin()) {
2345 continue;
2346 }
2347 if (uid != client->uid() && !client->isSilenced()) {
2348 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2349 uid, client->portId(), client->uid());
2350 status = INVALID_OPERATION;
2351 goto error;
2352 }
Eric Laurent331679c2018-04-16 17:03:16 -07002353 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002354 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002355 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002356 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002357
Eric Laurentfecbceb2021-02-09 14:46:43 +01002358 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002359 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002360 }
2361
2362 *input = AUDIO_IO_HANDLE_NONE;
2363 *inputType = API_INPUT_INVALID;
2364
Francois Gaffie716e1432019-01-14 16:58:59 +01002365 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002366
Francois Gaffie716e1432019-01-14 16:58:59 +01002367 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2368 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2369 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002370 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002371 ALOGW("%s could not find input mix for attr %s",
2372 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002373 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002374 }
jiabinc1de2df2019-05-07 14:26:40 -07002375 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2376 String8(attr->tags + strlen("addr=")),
2377 AUDIO_FORMAT_DEFAULT);
2378 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002379 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002380 __func__, attributes.source, attributes.tags);
2381 status = BAD_VALUE;
2382 goto error;
2383 }
2384
Kevin Rocard25f9b052019-02-27 15:08:54 -08002385 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2386 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2387 } else {
2388 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2389 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002390 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002391 if (explicitRoutingDevice != nullptr) {
2392 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002393 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002394 // Prevent from storing invalid requested device id in clients
2395 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002396 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002397 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2398 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002399 }
François Gaffie11d30102018-11-02 16:09:09 +01002400 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002401 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002402 status = BAD_VALUE;
2403 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002404 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002405 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2406 *inputType = API_INPUT_MIX_CAPTURE;
2407 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002408 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2409 // there is an external policy, but this input is attached to a mix of recorders,
2410 // meaning it receives audio injected into the framework, so the recorder doesn't
2411 // know about it and is therefore considered "legacy"
2412 *inputType = API_INPUT_LEGACY;
2413 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002414 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002415 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002416 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002417 } else {
2418 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002419 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002420
Eric Laurent599c7582015-12-07 18:05:55 -08002421 }
2422
François Gaffiec005e562018-11-06 15:04:49 +01002423 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002424 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002425 status = INVALID_OPERATION;
2426 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002427 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002428
Eric Laurent8f42ea12018-08-08 09:08:25 -07002429exit:
2430
François Gaffiec005e562018-11-06 15:04:49 +01002431 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2432 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002433
Francois Gaffie716e1432019-01-14 16:58:59 +01002434 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002435 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002436 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002437
Mikhail Naganov2996f672019-04-18 12:29:59 -07002438 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002439 requestedDeviceId, attributes.source, flags,
2440 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002441 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002442 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002443
2444 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2445 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002446
Eric Laurent599c7582015-12-07 18:05:55 -08002447 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002448
2449error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002450 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002451}
2452
2453
François Gaffie11d30102018-11-02 16:09:09 +01002454audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002455 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002456 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002457 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002458 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002459 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002460{
2461 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002462 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002463 bool isSoundTrigger = false;
2464
François Gaffiec005e562018-11-06 15:04:49 +01002465 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002466 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2467 if (index >= 0) {
2468 input = mSoundTriggerSessions.valueFor(session);
2469 isSoundTrigger = true;
2470 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2471 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2472 } else {
2473 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002474 }
François Gaffiec005e562018-11-06 15:04:49 +01002475 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002476 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002477 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002478 }
2479
Carter Hsua3abb402021-10-26 11:11:20 +08002480 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2481 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2482 }
2483
Andy Hungf129b032015-04-07 13:45:50 -07002484 // find a compatible input profile (not necessarily identical in parameters)
2485 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002486 // sampling rate and flags may be updated by getInputProfile
2487 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2488 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002489 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002490 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002491 audio_input_flags_t profileFlags = flags;
2492 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002493 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002494 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002495 profileFlags);
2496 if (profile != 0) {
2497 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002498 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2499 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002500 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002501 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2502 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002503 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002504 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002505 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002506 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002507 }
Eric Laurente552edb2014-03-10 17:42:56 -07002508 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002509 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002510 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002511 if (samplingRate == 0) {
2512 samplingRate = profileSamplingRate;
2513 }
Eric Laurente552edb2014-03-10 17:42:56 -07002514
Eric Laurent322b4d22015-04-03 15:57:54 -07002515 if (profile->getModuleHandle() == 0) {
2516 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002517 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002518 }
2519
Eric Laurentec376dc2021-04-08 20:41:22 +02002520 // Reuse an already opened input if a client with the same session ID already exists
2521 // on that input
2522 for (size_t i = 0; i < mInputs.size(); i++) {
2523 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2524 if (desc->mProfile != profile) {
2525 continue;
2526 }
2527 RecordClientVector clients = desc->clientsList();
2528 for (const auto &client : clients) {
2529 if (session == client->session()) {
2530 return desc->mIoHandle;
2531 }
2532 }
2533 }
2534
Eric Laurent3974e3b2017-12-07 17:58:43 -08002535 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002536 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002537 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002538 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002539 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002540 continue;
2541 }
2542 // if sound trigger, reuse input if used by other sound trigger on same session
2543 // else
2544 // reuse input if active client app is not in IDLE state
2545 //
2546 RecordClientVector clients = desc->clientsList();
2547 bool doClose = false;
2548 for (const auto& client : clients) {
2549 if (isSoundTrigger != client->isSoundTrigger()) {
2550 continue;
2551 }
2552 if (client->isSoundTrigger()) {
2553 if (session == client->session()) {
2554 return desc->mIoHandle;
2555 }
2556 continue;
2557 }
2558 if (client->active() && client->appState() != APP_STATE_IDLE) {
2559 return desc->mIoHandle;
2560 }
2561 doClose = true;
2562 }
2563 if (doClose) {
2564 closeInput(desc->mIoHandle);
2565 } else {
2566 i++;
2567 }
2568 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002569 }
2570
Eric Laurentfe231122017-11-17 17:48:06 -08002571 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002572
Eric Laurentfe231122017-11-17 17:48:06 -08002573 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2574 lConfig.sample_rate = profileSamplingRate;
2575 lConfig.channel_mask = profileChannelMask;
2576 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002577
François Gaffie11d30102018-11-02 16:09:09 +01002578 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002579
2580 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002581 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002582 (profileSamplingRate != lConfig.sample_rate) ||
2583 !audio_formats_match(profileFormat, lConfig.format) ||
2584 (profileChannelMask != lConfig.channel_mask)) {
2585 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002586 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002587 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002588 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002589 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002590 }
Eric Laurent599c7582015-12-07 18:05:55 -08002591 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002592 }
2593
Eric Laurentc722f302014-12-10 11:21:49 -08002594 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002595
Eric Laurent599c7582015-12-07 18:05:55 -08002596 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002597 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002598
Eric Laurent599c7582015-12-07 18:05:55 -08002599 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002600}
2601
Eric Laurent4eb58f12018-12-07 16:41:02 -08002602status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002603{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002604 ALOGV("%s portId %d", __FUNCTION__, portId);
2605
2606 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2607 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002608 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002609 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002610 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002611 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002612 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002613 if (client->active()) {
2614 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2615 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002616 }
2617
Eric Laurent8f42ea12018-08-08 09:08:25 -07002618 audio_session_t session = client->session();
2619
Eric Laurent4eb58f12018-12-07 16:41:02 -08002620 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002621
Eric Laurent4eb58f12018-12-07 16:41:02 -08002622 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002623
Eric Laurent4eb58f12018-12-07 16:41:02 -08002624 status_t status = inputDesc->start();
2625 if (status != NO_ERROR) {
2626 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002627 }
Eric Laurente552edb2014-03-10 17:42:56 -07002628
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002629 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002630 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002631 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002632
Eric Laurent8f42ea12018-08-08 09:08:25 -07002633 // indicate active capture to sound trigger service if starting capture from a mic on
2634 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002635 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002636 if (device != nullptr) {
2637 status = setInputDevice(input, device, true /* force */);
2638 } else {
2639 ALOGW("%s no new input device can be found for descriptor %d",
2640 __FUNCTION__, inputDesc->getId());
2641 status = BAD_VALUE;
2642 }
Eric Laurente552edb2014-03-10 17:42:56 -07002643
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002644 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002645 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002646 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002647 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002648 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2649 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002650 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002651 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002652
François Gaffie11d30102018-11-02 16:09:09 +01002653 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2654 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002655 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002656 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002657 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002658
Eric Laurent8f42ea12018-08-08 09:08:25 -07002659 // automatically enable the remote submix output when input is started if not
2660 // used by a policy mix of type MIX_TYPE_RECORDERS
2661 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002662 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002663 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002664 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002665 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002666 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2667 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002668 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002669 if (address != "") {
2670 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2671 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002672 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002673 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002674 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002675 } else if (status != NO_ERROR) {
2676 // Restore client activity state.
2677 inputDesc->setClientActive(client, false);
2678 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002679 }
2680
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002681 ALOGV("%s input %d source = %d status = %d exit",
2682 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002683
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002684 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002685}
2686
Eric Laurent8fc147b2018-07-22 19:13:55 -07002687status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002688{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002689 ALOGV("%s portId %d", __FUNCTION__, portId);
2690
2691 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2692 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002693 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002694 return BAD_VALUE;
2695 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002696 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002697 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002698 if (!client->active()) {
2699 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002700 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002701 }
Carter Hsue6139d52021-07-08 10:30:20 +08002702 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002703 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002704
Eric Laurent8f42ea12018-08-08 09:08:25 -07002705 inputDesc->stop();
2706 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002707 auto current_source = inputDesc->source();
2708 setInputDevice(input, getNewInputDevice(inputDesc),
2709 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002710 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002711 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002712 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002713 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002714 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2715 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002716 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002717 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002718
2719 // automatically disable the remote submix output when input is stopped if not
2720 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002721 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002722 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002723 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002724 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002725 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2726 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002727 }
2728 if (address != "") {
2729 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2730 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002731 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002732 }
2733 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002734 resetInputDevice(input);
2735
2736 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2737 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002738 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2739 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002740 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002741 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002742 }
2743 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002744 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002745 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002746}
2747
Eric Laurent8fc147b2018-07-22 19:13:55 -07002748void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002749{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002750 ALOGV("%s portId %d", __FUNCTION__, portId);
2751
2752 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2753 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002754 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002755 return;
2756 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002757 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002758 audio_io_handle_t input = inputDesc->mIoHandle;
2759
Eric Laurent8f42ea12018-08-08 09:08:25 -07002760 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002761
Andy Hung39efb7a2018-09-26 15:39:28 -07002762 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002763
Andy Hung39efb7a2018-09-26 15:39:28 -07002764 if (inputDesc->getClientCount() > 0) {
2765 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002766 return;
2767 }
2768
Eric Laurent05b90f82014-08-27 15:32:29 -07002769 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002770 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002771 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002772}
2773
Eric Laurent8f42ea12018-08-08 09:08:25 -07002774void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002775{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002776 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002777
2778 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002779 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002780 }
2781}
2782
Eric Laurent8f42ea12018-08-08 09:08:25 -07002783void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2784{
2785 stopInput(portId);
2786 releaseInput(portId);
2787}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002788
Eric Laurent0dd51852019-04-19 18:18:58 -07002789void AudioPolicyManager::checkCloseInputs() {
2790 // After connecting or disconnecting an input device, close input if:
2791 // - it has no client (was just opened to check profile) OR
2792 // - none of its supported devices are connected anymore OR
2793 // - one of its clients cannot be routed to one of its supported
2794 // devices anymore. Otherwise update device selection
2795 std::vector<audio_io_handle_t> inputsToClose;
2796 for (size_t i = 0; i < mInputs.size(); i++) {
2797 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2798 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002799 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002800 inputsToClose.push_back(mInputs.keyAt(i));
2801 } else {
2802 bool close = false;
2803 for (const auto& client : input->clientsList()) {
2804 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002805 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002806 if (!input->supportedDevices().contains(device)) {
2807 close = true;
2808 break;
2809 }
2810 }
2811 if (close) {
2812 inputsToClose.push_back(mInputs.keyAt(i));
2813 } else {
2814 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2815 }
2816 }
2817 }
2818
2819 for (const audio_io_handle_t handle : inputsToClose) {
2820 ALOGV("%s closing input %d", __func__, handle);
2821 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002822 }
Eric Laurentd4692962014-05-05 18:13:44 -07002823}
2824
François Gaffie251c7f02018-11-07 10:41:08 +01002825void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002826{
2827 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002828 if (indexMin < 0 || indexMax < 0) {
2829 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2830 return;
2831 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002832 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002833
2834 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002835 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2836 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002837 continue;
2838 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002839 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002840 }
Eric Laurente552edb2014-03-10 17:42:56 -07002841}
2842
Eric Laurente0720872014-03-11 09:30:41 -07002843status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002844 int index,
2845 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002846{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002847 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002848 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2849 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2850 return NO_ERROR;
2851 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002852 ALOGV("%s: stream %s attributes=%s", __func__,
2853 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002854 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002855}
2856
Eric Laurente0720872014-03-11 09:30:41 -07002857status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002858 int *index,
2859 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002860{
François Gaffiec005e562018-11-06 15:04:49 +01002861 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2862 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002863 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002864 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002865 deviceTypes = mEngine->getOutputDevicesForStream(
2866 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002867 }
jiabin9a3361e2019-10-01 09:38:30 -07002868 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002869}
2870
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002871status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002872 int index,
2873 audio_devices_t device)
2874{
2875 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002876 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2877 if (group == VOLUME_GROUP_NONE) {
2878 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002879 return BAD_VALUE;
2880 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002881 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002882 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002883 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002884 VolumeSource vs = toVolumeSource(group);
2885 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2886
2887 status = setVolumeCurveIndex(index, device, curves);
2888 if (status != NO_ERROR) {
2889 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2890 return status;
2891 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002892
jiabin9a3361e2019-10-01 09:38:30 -07002893 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002894 auto curCurvAttrs = curves.getAttributes();
2895 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2896 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002897 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002898 } else if (!curves.getStreamTypes().empty()) {
2899 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002900 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002901 } else {
2902 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2903 return BAD_VALUE;
2904 }
jiabin9a3361e2019-10-01 09:38:30 -07002905 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2906 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002907
François Gaffiecfe17322018-11-07 13:41:29 +01002908 // update volume on all outputs and streams matching the following:
2909 // - The requested stream (or a stream matching for volume control) is active on the output
2910 // - The device (or devices) selected by the engine for this stream includes
2911 // the requested device
2912 // - For non default requested device, currently selected device on the output is either the
2913 // requested device or one of the devices selected by the engine for this stream
2914 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2915 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002916 for (size_t i = 0; i < mOutputs.size(); i++) {
2917 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002918 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002919
jiabin9a3361e2019-10-01 09:38:30 -07002920 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2921 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002922 }
François Gaffieed91f582020-01-31 10:35:37 +01002923 if (!(desc->isActive(vs) || isInCall())) {
2924 continue;
2925 }
2926 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2927 curDevices.find(device) == curDevices.end()) {
2928 continue;
2929 }
2930 bool applyVolume = false;
2931 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2932 curSrcDevices.insert(device);
2933 applyVolume = (curSrcDevices.find(
2934 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2935 } else {
2936 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2937 }
2938 if (!applyVolume) {
2939 continue; // next output
2940 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002941 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2942 // If a higher priority strategy is active, and the output is routed to a device with a
2943 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002944 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002945 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02002946 // If the volume source is active with higher priority source, ensure at least Sw Muted
2947 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002948 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2949 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2950 false /*preferredDevice*/);
2951 if (activeClients.empty()) {
2952 continue;
2953 }
2954 bool isPreempted = false;
2955 bool isHigherPriority = productStrategy < strategy;
2956 for (const auto &client : activeClients) {
2957 if (isHigherPriority && (client->volumeSource() != vs)) {
2958 ALOGV("%s: Strategy=%d (\nrequester:\n"
2959 " group %d, volumeGroup=%d attributes=%s)\n"
2960 " higher priority source active:\n"
2961 " volumeGroup=%d attributes=%s) \n"
2962 " on output %zu, bailing out", __func__, productStrategy,
2963 group, group, toString(attributes).c_str(),
2964 client->volumeSource(), toString(client->attributes()).c_str(), i);
2965 applyVolume = false;
2966 isPreempted = true;
2967 break;
2968 }
2969 // However, continue for loop to ensure no higher prio clients running on output
2970 if (client->volumeSource() == vs) {
2971 applyVolume = true;
2972 }
2973 }
2974 if (isPreempted || applyVolume) {
2975 break;
2976 }
2977 }
2978 if (!applyVolume) {
2979 continue; // next output
2980 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002981 }
François Gaffieed91f582020-01-31 10:35:37 +01002982 //FIXME: workaround for truncated touch sounds
2983 // delayed volume change for system stream to be removed when the problem is
2984 // handled by system UI
2985 status_t volStatus = checkAndSetVolume(
2986 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002987 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01002988 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2989 if (volStatus != NO_ERROR) {
2990 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002991 }
2992 }
François Gaffiecfe17322018-11-07 13:41:29 +01002993 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2994 return status;
2995}
2996
François Gaffieaaac0fd2018-11-22 17:56:39 +01002997status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002998 audio_devices_t device,
2999 IVolumeCurves &volumeCurves)
3000{
3001 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3002 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003003 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3004 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003005 (index > volumeCurves.getVolumeIndexMax())) {
3006 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3007 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3008 return BAD_VALUE;
3009 }
3010 if (!audio_is_output_device(device)) {
3011 return BAD_VALUE;
3012 }
3013
3014 // Force max volume if stream cannot be muted
3015 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3016
François Gaffieaaac0fd2018-11-22 17:56:39 +01003017 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003018 volumeCurves.addCurrentVolumeIndex(device, index);
3019 return NO_ERROR;
3020}
3021
3022status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3023 int &index,
3024 audio_devices_t device)
3025{
3026 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3027 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003028 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003029 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003030 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3031 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003032 }
jiabin9a3361e2019-10-01 09:38:30 -07003033 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003034}
3035
3036status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3037 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003038 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003039{
jiabin9a3361e2019-10-01 09:38:30 -07003040 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003041 return BAD_VALUE;
3042 }
jiabin9a3361e2019-10-01 09:38:30 -07003043 index = curves.getVolumeIndex(deviceTypes);
3044 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003045 return NO_ERROR;
3046}
3047
3048status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3049 int &index)
3050{
3051 index = getVolumeCurves(attr).getVolumeIndexMin();
3052 return NO_ERROR;
3053}
3054
3055status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3056 int &index)
3057{
3058 index = getVolumeCurves(attr).getVolumeIndexMax();
3059 return NO_ERROR;
3060}
3061
Eric Laurent36829f92017-04-07 19:04:42 -07003062audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003063{
3064 // select one output among several suitable for global effects.
3065 // The priority is as follows:
3066 // 1: An offloaded output. If the effect ends up not being offloadable,
3067 // AudioFlinger will invalidate the track and the offloaded output
3068 // will be closed causing the effect to be moved to a PCM output.
3069 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003070 // 3: The primary output
3071 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003072
François Gaffiec005e562018-11-06 15:04:49 +01003073 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3074 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003075 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003076
Eric Laurent36829f92017-04-07 19:04:42 -07003077 if (outputs.size() == 0) {
3078 return AUDIO_IO_HANDLE_NONE;
3079 }
Eric Laurente552edb2014-03-10 17:42:56 -07003080
Eric Laurent36829f92017-04-07 19:04:42 -07003081 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3082 bool activeOnly = true;
3083
3084 while (output == AUDIO_IO_HANDLE_NONE) {
3085 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3086 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3087 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3088
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003089 for (audio_io_handle_t output : outputs) {
3090 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003091 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003092 continue;
3093 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003094 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3095 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003096 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003097 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003098 }
3099 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003100 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003101 }
3102 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003103 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003104 }
3105 }
3106 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3107 output = outputOffloaded;
3108 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3109 output = outputDeepBuffer;
3110 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3111 output = outputPrimary;
3112 } else {
3113 output = outputs[0];
3114 }
3115 activeOnly = false;
3116 }
3117
3118 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003119 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003120 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3121 mMusicEffectOutput = output;
3122 }
3123
3124 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003125 return output;
3126}
3127
Eric Laurent36829f92017-04-07 19:04:42 -07003128audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3129{
3130 return selectOutputForMusicEffects();
3131}
3132
Eric Laurente0720872014-03-11 09:30:41 -07003133status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003134 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003135 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003136 int session,
3137 int id)
3138{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003139 if (session != AUDIO_SESSION_DEVICE) {
3140 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003141 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003142 index = mInputs.indexOfKey(io);
3143 if (index < 0) {
3144 ALOGW("registerEffect() unknown io %d", io);
3145 return INVALID_OPERATION;
3146 }
Eric Laurente552edb2014-03-10 17:42:56 -07003147 }
3148 }
François Gaffiec005e562018-11-06 15:04:49 +01003149 return mEffects.registerEffect(desc, io, session, id,
3150 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3151 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003152}
3153
Eric Laurentc241b0d2018-11-28 09:08:49 -08003154status_t AudioPolicyManager::unregisterEffect(int id)
3155{
3156 if (mEffects.getEffect(id) == nullptr) {
3157 return INVALID_OPERATION;
3158 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003159 if (mEffects.isEffectEnabled(id)) {
3160 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3161 setEffectEnabled(id, false);
3162 }
3163 return mEffects.unregisterEffect(id);
3164}
3165
3166status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3167{
3168 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3169 if (effect == nullptr) {
3170 return INVALID_OPERATION;
3171 }
3172
3173 status_t status = mEffects.setEffectEnabled(id, enabled);
3174 if (status == NO_ERROR) {
3175 mInputs.trackEffectEnabled(effect, enabled);
3176 }
3177 return status;
3178}
3179
Eric Laurent6c796322019-04-09 14:13:17 -07003180
3181status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3182{
3183 mEffects.moveEffects(ids, io);
3184 return NO_ERROR;
3185}
3186
Eric Laurentc75307b2015-03-17 15:29:32 -07003187bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3188{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003189 auto vs = toVolumeSource(stream, false);
3190 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003191}
3192
3193bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3194{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003195 auto vs = toVolumeSource(stream, false);
3196 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003197}
3198
Eric Laurente0720872014-03-11 09:30:41 -07003199bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003200{
3201 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003202 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003203 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003204 return true;
3205 }
3206 }
3207 return false;
3208}
3209
Eric Laurent275e8e92014-11-30 15:14:47 -08003210// Register a list of custom mixes with their attributes and format.
3211// When a mix is registered, corresponding input and output profiles are
3212// added to the remote submix hw module. The profile contains only the
3213// parameters (sampling rate, format...) specified by the mix.
3214// The corresponding input remote submix device is also connected.
3215//
3216// When a remote submix device is connected, the address is checked to select the
3217// appropriate profile and the corresponding input or output stream is opened.
3218//
3219// When capture starts, getInputForAttr() will:
3220// - 1 look for a mix matching the address passed in attribtutes tags if any
3221// - 2 if none found, getDeviceForInputSource() will:
3222// - 2.1 look for a mix matching the attributes source
3223// - 2.2 if none found, default to device selection by policy rules
3224// At this time, the corresponding output remote submix device is also connected
3225// and active playback use cases can be transferred to this mix if needed when reconnecting
3226// after AudioTracks are invalidated
3227//
3228// When playback starts, getOutputForAttr() will:
3229// - 1 look for a mix matching the address passed in attribtutes tags if any
3230// - 2 if none found, look for a mix matching the attributes usage
3231// - 3 if none found, default to device and output selection by policy rules.
3232
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003233status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003234{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003235 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3236 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003237 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003238 sp<HwModule> rSubmixModule;
3239 // examine each mix's route type
3240 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003241 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003242 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3243 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3244 ALOGE("Unsupported Policy Mix %zu of %zu: "
3245 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3246 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003247 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003248 break;
3249 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003250 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3251 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003252 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003253 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3254 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003255 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003256 rSubmixModule = mHwModules.getModuleFromName(
3257 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3258 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003259 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003260 i);
3261 res = INVALID_OPERATION;
3262 break;
3263 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003264 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003265
Eric Laurent97ac8712018-07-27 18:59:02 -07003266 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003267 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003268 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003269 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003270 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3271 } else {
3272 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3273 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003274 }
François Gaffie036e1e92015-03-19 10:16:24 +01003275
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003276 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003277 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003278 res = INVALID_OPERATION;
3279 break;
3280 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003281 audio_config_t outputConfig = mix.mFormat;
3282 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003283 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3284 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003285 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3286 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003287 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003288 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003289 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003290 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003291
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003292 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003293 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3294 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3295 ALOGE("Failed to set remote submix device available, type %u, address %s",
3296 mix.mDeviceType, address.string());
3297 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003298 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003299 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3300 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003301 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003302 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003303 i, mixes.size(), type, address.string());
3304
3305 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3306 mix.mDeviceType, mix.mDeviceAddress,
3307 String8(), AUDIO_FORMAT_DEFAULT);
3308 if (device == nullptr) {
3309 res = INVALID_OPERATION;
3310 break;
3311 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003312
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003313 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003314 // First try to find an already opened output supporting the device
3315 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003316 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003317
Eric Laurentc529cf62020-04-17 18:19:10 -07003318 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003319 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003320 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3321 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003322 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003323 } else {
3324 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003325 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003326 }
3327 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003328 // If no output found, try to find a direct output profile supporting the device
3329 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3330 sp<HwModule> module = mHwModules[i];
3331 for (size_t j = 0;
3332 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3333 j++) {
3334 sp<IOProfile> profile = module->getOutputProfiles()[j];
3335 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3336 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3337 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3338 address.string());
3339 res = INVALID_OPERATION;
3340 } else {
3341 foundOutput = true;
3342 }
3343 }
3344 }
3345 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003346 if (res != NO_ERROR) {
3347 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003348 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003349 res = INVALID_OPERATION;
3350 break;
3351 } else if (!foundOutput) {
3352 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003353 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003354 res = INVALID_OPERATION;
3355 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003356 } else {
3357 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003358 }
Eric Laurentc722f302014-12-10 11:21:49 -08003359 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003360 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003361 if (res != NO_ERROR) {
3362 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003363 } else if (checkOutputs) {
3364 checkForDeviceAndOutputChanges();
3365 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003366 }
3367 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003368}
3369
3370status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3371{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003372 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003373 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003374 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003375 sp<HwModule> rSubmixModule;
3376 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003377 for (const auto& mix : mixes) {
3378 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003379
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003380 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003381 rSubmixModule = mHwModules.getModuleFromName(
3382 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3383 if (rSubmixModule == 0) {
3384 res = INVALID_OPERATION;
3385 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003386 }
3387 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003388
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003389 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003390
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003391 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003392 res = INVALID_OPERATION;
3393 continue;
3394 }
3395
Kevin Rocard04ed0462019-05-02 17:53:24 -07003396 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3397 if (getDeviceConnectionState(device, address.string()) ==
3398 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3399 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3400 address.string(), "remote-submix",
3401 AUDIO_FORMAT_DEFAULT);
3402 if (res != OK) {
3403 ALOGE("Error making RemoteSubmix device unavailable for mix "
3404 "with type %d, address %s", device, address.string());
3405 }
3406 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003407 }
jiabin5740f082019-08-19 15:08:30 -07003408 rSubmixModule->removeOutputProfile(address.c_str());
3409 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003410
Kevin Rocard153f92d2018-12-18 18:33:28 -08003411 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003412 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003413 res = INVALID_OPERATION;
3414 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003415 } else {
3416 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003417 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003418 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003419 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003420 if (res == NO_ERROR && checkOutputs) {
3421 checkForDeviceAndOutputChanges();
3422 updateCallAndOutputRouting();
3423 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003424 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003425}
3426
Mikhail Naganov100f0122018-11-29 11:22:16 -08003427void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3428{
3429 size_t i = 0;
3430 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3431 for (const auto& fmt : mManualSurroundFormats) {
3432 if (i++ != 0) dst->append(", ");
3433 std::string sfmt;
3434 FormatConverter::toString(fmt, sfmt);
3435 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3436 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3437 }
3438}
3439
Eric Laurentc529cf62020-04-17 18:19:10 -07003440// Returns true if all devices types match the predicate and are supported by one HW module
3441bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003442 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003443 std::function<bool(audio_devices_t)> predicate,
3444 const char *context) {
3445 for (size_t i = 0; i < devices.size(); i++) {
3446 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003447 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003448 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003449 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003450 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003451 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003452 return false;
3453 }
3454 }
3455 return true;
3456}
3457
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003458status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003459 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003460 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003461 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3462 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003463 }
3464 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003465 if (res != NO_ERROR) {
3466 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3467 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003468 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003469
3470 checkForDeviceAndOutputChanges();
3471 updateCallAndOutputRouting();
3472
3473 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003474}
3475
3476status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3477 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003478 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3479 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003480 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003481 __FUNCTION__, uid);
3482 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003483 }
3484
Eric Laurentc529cf62020-04-17 18:19:10 -07003485 checkForDeviceAndOutputChanges();
3486 updateCallAndOutputRouting();
3487
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003488 return res;
3489}
3490
Eric Laurent2517af32020-11-25 15:31:27 +01003491
jiabin0a488932020-08-07 17:32:40 -07003492status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3493 device_role_t role,
3494 const AudioDeviceTypeAddrVector &devices) {
3495 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3496 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003497
Eric Laurentc529cf62020-04-17 18:19:10 -07003498 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003499 return BAD_VALUE;
3500 }
jiabin0a488932020-08-07 17:32:40 -07003501 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003502 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003503 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3504 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003505 return status;
3506 }
3507
3508 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003509
3510 bool forceVolumeReeval = false;
3511 // FIXME: workaround for truncated touch sounds
3512 // to be removed when the problem is handled by system UI
3513 uint32_t delayMs = 0;
3514 if (strategy == mCommunnicationStrategy) {
3515 forceVolumeReeval = true;
3516 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3517 updateInputRouting();
3518 }
3519 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003520
3521 return NO_ERROR;
3522}
3523
3524void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3525{
3526 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003527 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003528 // Only apply special touch sound delay once
3529 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003530 }
3531 for (size_t i = 0; i < mOutputs.size(); i++) {
3532 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3533 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003534 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3535 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003536 // As done in setDeviceConnectionState, we could also fix default device issue by
3537 // preventing the force re-routing in case of default dev that distinguishes on address.
3538 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003539 bool forceRouting = !newDevices.isEmpty();
3540 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3541 true /*requiresMuteCheck*/,
3542 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003543 // Only apply special touch sound delay once
3544 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003545 }
3546 if (forceVolumeReeval && !newDevices.isEmpty()) {
3547 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3548 }
3549 }
3550}
3551
Eric Laurent2517af32020-11-25 15:31:27 +01003552void AudioPolicyManager::updateInputRouting() {
3553 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303554 // Skip for hotword recording as the input device switch
3555 // is handled within sound trigger HAL
3556 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3557 continue;
3558 }
Eric Laurent2517af32020-11-25 15:31:27 +01003559 auto newDevice = getNewInputDevice(activeDesc);
3560 // Force new input selection if the new device can not be reached via current input
3561 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3562 setInputDevice(activeDesc->mIoHandle, newDevice);
3563 } else {
3564 closeInput(activeDesc->mIoHandle);
3565 }
3566 }
3567}
3568
jiabin0a488932020-08-07 17:32:40 -07003569status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3570 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003571{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003572 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003573
jiabin0a488932020-08-07 17:32:40 -07003574 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003575 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003576 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3577 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003578 return status;
3579 }
3580
3581 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003582
3583 bool forceVolumeReeval = false;
3584 // FIXME: workaround for truncated touch sounds
3585 // to be removed when the problem is handled by system UI
3586 uint32_t delayMs = 0;
3587 if (strategy == mCommunnicationStrategy) {
3588 forceVolumeReeval = true;
3589 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3590 updateInputRouting();
3591 }
3592 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003593
3594 return NO_ERROR;
3595}
3596
jiabin0a488932020-08-07 17:32:40 -07003597status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3598 device_role_t role,
3599 AudioDeviceTypeAddrVector &devices) {
3600 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003601}
3602
Jiabin Huang3b98d322020-09-03 17:54:16 +00003603status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3604 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3605 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3606 dumpAudioDeviceTypeAddrVector(devices).c_str());
3607
Mikhail Naganov55773032020-10-01 15:08:13 -07003608 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003609 return BAD_VALUE;
3610 }
3611 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3612 ALOGW_IF(status != NO_ERROR,
3613 "Engine could not set preferred devices %s for audio source %d role %d",
3614 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3615
3616 return status;
3617}
3618
3619status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3620 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3621 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3622 dumpAudioDeviceTypeAddrVector(devices).c_str());
3623
Mikhail Naganov55773032020-10-01 15:08:13 -07003624 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003625 return BAD_VALUE;
3626 }
3627 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3628 ALOGW_IF(status != NO_ERROR,
3629 "Engine could not add preferred devices %s for audio source %d role %d",
3630 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3631
Eric Laurent2517af32020-11-25 15:31:27 +01003632 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003633 return status;
3634}
3635
3636status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3637 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3638{
3639 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3640 dumpAudioDeviceTypeAddrVector(devices).c_str());
3641
Mikhail Naganov55773032020-10-01 15:08:13 -07003642 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003643 return BAD_VALUE;
3644 }
3645
3646 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3647 audioSource, role, devices);
3648 ALOGW_IF(status != NO_ERROR,
3649 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3650
Eric Laurent2517af32020-11-25 15:31:27 +01003651 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003652 return status;
3653}
3654
3655status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3656 device_role_t role) {
3657 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3658
3659 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3660 ALOGW_IF(status != NO_ERROR,
3661 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3662
Eric Laurent2517af32020-11-25 15:31:27 +01003663 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003664 return status;
3665}
3666
3667status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3668 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3669 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3670}
3671
Oscar Azucena90e77632019-11-27 17:12:28 -08003672status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003673 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003674 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003675 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3676 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003677 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003678 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3679 if (status != NO_ERROR) {
3680 ALOGE("%s() could not set device affinity for userId %d",
3681 __FUNCTION__, userId);
3682 return status;
3683 }
3684
3685 // reevaluate outputs for all devices
3686 checkForDeviceAndOutputChanges();
3687 updateCallAndOutputRouting();
3688
3689 return NO_ERROR;
3690}
3691
3692status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003693 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003694 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3695 if (status != NO_ERROR) {
3696 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3697 __FUNCTION__, userId);
3698 return status;
3699 }
3700
3701 // reevaluate outputs for all devices
3702 checkForDeviceAndOutputChanges();
3703 updateCallAndOutputRouting();
3704
3705 return NO_ERROR;
3706}
3707
Andy Hungc29d82b2018-10-05 12:23:17 -07003708void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003709{
Andy Hungc29d82b2018-10-05 12:23:17 -07003710 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003711 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003712 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003713 std::string stateLiteral;
3714 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003715 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003716 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3717 "communications", "media", "record", "dock", "system",
3718 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3719 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3720 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003721 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3722 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3723 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3724 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3725 dst->append(" (MANUAL: ");
3726 dumpManualSurroundFormats(dst);
3727 dst->append(")");
3728 }
3729 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003730 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003731 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3732 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003733 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003734 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003735
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003736 dst->append("\n");
3737 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3738 dst->append("\n");
3739 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003740 mHwModulesAll.dump(dst);
3741 mOutputs.dump(dst);
3742 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003743 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003744 mAudioPatches.dump(dst);
3745 mPolicyMixes.dump(dst);
3746 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003747
Kevin Rocardb99cc752019-03-21 20:52:24 -07003748 dst->appendFormat(" AllowedCapturePolicies:\n");
3749 for (auto& policy : mAllowedCapturePolicies) {
3750 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3751 }
3752
François Gaffiec005e562018-11-06 15:04:49 +01003753 dst->appendFormat("\nPolicy Engine dump:\n");
3754 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003755}
3756
3757status_t AudioPolicyManager::dump(int fd)
3758{
3759 String8 result;
3760 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003761 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003762 return NO_ERROR;
3763}
3764
Kevin Rocardb99cc752019-03-21 20:52:24 -07003765status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3766{
3767 mAllowedCapturePolicies[uid] = capturePolicy;
3768 return NO_ERROR;
3769}
3770
Eric Laurente552edb2014-03-10 17:42:56 -07003771// This function checks for the parameters which can be offloaded.
3772// This can be enhanced depending on the capability of the DSP and policy
3773// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003774audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003775{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003776 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003777 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003778 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003779 offloadInfo.format,
3780 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3781 offloadInfo.has_video);
3782
jiabin2b9d5a12021-12-10 01:06:29 +00003783 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003784 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003785 }
3786
3787 // See if there is a profile to support this.
3788 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003789 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003790 offloadInfo.sample_rate,
3791 offloadInfo.format,
3792 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003793 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3794 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003795 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3796 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3797 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003798 if (profile == nullptr) {
3799 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3800 }
3801 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3802 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3803 }
3804 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003805}
3806
Michael Chana94fbb22018-04-24 14:31:19 +10003807bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3808 const audio_attributes_t& attributes) {
3809 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003810 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003811 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3812 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003813 config.sample_rate,
3814 config.format,
3815 config.channel_mask,
3816 output_flags,
3817 true /* directOnly */);
3818 ALOGV("%s() profile %sfound with name: %s, "
3819 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3820 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003821 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003822 config.sample_rate, config.format, config.channel_mask, output_flags);
3823 return (profile != 0);
3824}
3825
jiabin2b9d5a12021-12-10 01:06:29 +00003826bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3827 bool durationIgnored) {
3828 if (mMasterMono) {
3829 return false; // no offloading if mono is set.
3830 }
3831
3832 // Check if offload has been disabled
3833 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3834 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3835 return false;
3836 }
3837
3838 // Check if stream type is music, then only allow offload as of now.
3839 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3840 {
3841 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3842 return false;
3843 }
3844
3845 //TODO: enable audio offloading with video when ready
3846 const bool allowOffloadWithVideo =
3847 property_get_bool("audio.offload.video", false /* default_value */);
3848 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3849 ALOGV("%s: has_video == true, returning false", __func__);
3850 return false;
3851 }
3852
3853 //If duration is less than minimum value defined in property, return false
3854 const int min_duration_secs = property_get_int32(
3855 "audio.offload.min.duration.secs", -1 /* default_value */);
3856 if (!durationIgnored) {
3857 if (min_duration_secs >= 0) {
3858 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3859 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3860 __func__, min_duration_secs);
3861 return false;
3862 }
3863 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3864 ALOGV("%s: Offload denied by duration < default min(=%u)",
3865 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3866 return false;
3867 }
3868 }
3869
3870 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3871 // creating an offloaded track and tearing it down immediately after start when audioflinger
3872 // detects there is an active non offloadable effect.
3873 // FIXME: We should check the audio session here but we do not have it in this context.
3874 // This may prevent offloading in rare situations where effects are left active by apps
3875 // in the background.
3876 if (mEffects.isNonOffloadableEffectEnabled()) {
3877 return false;
3878 }
3879
3880 return true;
3881}
3882
3883audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
3884 const audio_config_t *config) {
3885 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
3886 offloadInfo.format = config->format;
3887 offloadInfo.sample_rate = config->sample_rate;
3888 offloadInfo.channel_mask = config->channel_mask;
3889 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
3890 offloadInfo.has_video = false;
3891 offloadInfo.is_streaming = false;
3892 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
3893
3894 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
3895 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3896 audio_flags_to_audio_output_flags(attr->flags, &flags);
3897 // only retain flags that will drive compressed offload or passthrough
3898 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
3899 if (offloadPossible) {
3900 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
3901 }
3902 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
3903
jiabinc8f7dfc2022-01-06 18:42:08 +00003904 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00003905 for (const auto& hwModule : mHwModules) {
3906 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00003907 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00003908 config->sample_rate, nullptr /*updatedSamplingRate*/,
3909 config->format, nullptr /*updatedFormat*/,
3910 config->channel_mask, nullptr /*updatedChannelMask*/,
3911 flags)) {
3912 continue;
3913 }
3914 // reject profiles not corresponding to a device currently available
3915 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
3916 continue;
3917 }
3918 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
3919 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00003920 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00003921 != AUDIO_DIRECT_NOT_SUPPORTED) {
3922 // Already reports offload gapless supported. No need to report offload support.
3923 continue;
3924 }
3925 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
3926 != AUDIO_OUTPUT_FLAG_NONE) {
3927 // If offload gapless is reported, no need to report offload support.
3928 directMode = (audio_direct_mode_t) ((directMode &
3929 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
3930 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
3931 } else {
3932 directMode = (audio_direct_mode_t)(directMode |AUDIO_DIRECT_OFFLOAD_SUPPORTED);
3933 }
3934 } else {
3935 directMode = (audio_direct_mode_t) (directMode |
3936 AUDIO_DIRECT_BITSTREAM_SUPPORTED);
3937 }
3938 }
3939 }
3940 return directMode;
3941}
3942
Dorin Drimusf2196d82022-01-03 12:11:18 +01003943status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
3944 AudioProfileVector& audioProfilesVector) {
3945 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08003946 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01003947 if (status != OK) {
3948 return status;
3949 }
3950 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
3951 if (devices.empty()) {
3952 return OK; // no output devices for the attributes
3953 }
3954
3955 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01003956 // the MSD module checks for different conditions
3957 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
3958 continue;
3959 }
3960 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
3961 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01003962 continue;
3963 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003964 // allow only profiles that support all the available and routed devices
3965 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01003966 != devices.size()) {
3967 continue;
3968 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003969 audioProfilesVector.addAllValidProfiles(
3970 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01003971 }
3972 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003973
3974 // add the direct profiles from MSD if present and has audio patches to all the output(s)
3975 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
3976 if (msdModule != nullptr) {
3977 if (msdHasPatchesToAllDevices(devices)) {
3978 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
3979 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
3980 if (!outputProfile->asAudioPort()->isDirectOutput()) {
3981 continue;
3982 }
3983 audioProfilesVector.addAllValidProfiles(
3984 outputProfile->asAudioPort()->getAudioProfiles());
3985 }
3986 } else {
3987 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
3988 }
3989 }
3990
Dorin Drimusf2196d82022-01-03 12:11:18 +01003991 return NO_ERROR;
3992}
3993
Eric Laurent6a94d692014-05-20 11:18:06 -07003994status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3995 audio_port_type_t type,
3996 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003997 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003998 unsigned int *generation)
3999{
jiabin19cdba52020-11-24 11:28:58 -08004000 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4001 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004002 return BAD_VALUE;
4003 }
4004 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004005 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004006 *num_ports = 0;
4007 }
4008
4009 size_t portsWritten = 0;
4010 size_t portsMax = *num_ports;
4011 *num_ports = 0;
4012 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004013 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4014 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004015 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004016 for (const auto& dev : mAvailableOutputDevices) {
4017 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004018 continue;
4019 }
4020 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004021 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004022 }
4023 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004024 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004025 }
4026 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004027 for (const auto& dev : mAvailableInputDevices) {
4028 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004029 continue;
4030 }
4031 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004032 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004033 }
4034 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004035 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004036 }
4037 }
4038 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4039 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4040 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4041 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4042 }
4043 *num_ports += mInputs.size();
4044 }
4045 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004046 size_t numOutputs = 0;
4047 for (size_t i = 0; i < mOutputs.size(); i++) {
4048 if (!mOutputs[i]->isDuplicated()) {
4049 numOutputs++;
4050 if (portsWritten < portsMax) {
4051 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4052 }
4053 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004054 }
Eric Laurent84c70242014-06-23 08:46:27 -07004055 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004056 }
4057 }
4058 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004059 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004060 return NO_ERROR;
4061}
4062
jiabin19cdba52020-11-24 11:28:58 -08004063status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004064{
Eric Laurent99fcae42018-05-17 16:59:18 -07004065 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4066 return BAD_VALUE;
4067 }
4068 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4069 if (dev != 0) {
4070 dev->toAudioPort(port);
4071 return NO_ERROR;
4072 }
4073 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4074 if (dev != 0) {
4075 dev->toAudioPort(port);
4076 return NO_ERROR;
4077 }
4078 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4079 if (out != 0) {
4080 out->toAudioPort(port);
4081 return NO_ERROR;
4082 }
4083 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4084 if (in != 0) {
4085 in->toAudioPort(port);
4086 return NO_ERROR;
4087 }
4088 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004089}
4090
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004091status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4092 audio_patch_handle_t *handle,
4093 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004094{
François Gaffieafd4cea2019-11-18 15:50:22 +01004095 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004096 if (handle == NULL || patch == NULL) {
4097 return BAD_VALUE;
4098 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004099 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004100 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004101 return BAD_VALUE;
4102 }
4103 // only one source per audio patch supported for now
4104 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004105 return INVALID_OPERATION;
4106 }
Eric Laurent874c42872014-08-08 15:13:39 -07004107 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004108 return INVALID_OPERATION;
4109 }
Eric Laurent874c42872014-08-08 15:13:39 -07004110 for (size_t i = 0; i < patch->num_sinks; i++) {
4111 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4112 return INVALID_OPERATION;
4113 }
4114 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004115
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004116 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4117 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4118 if (srcDevice == nullptr || sinkDevice == nullptr) {
4119 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4120 return BAD_VALUE;
4121 }
4122 ALOGV("%s between source %s and sink %s", __func__,
4123 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4124 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4125 // Default attributes, default volume priority, not to infer with non raw audio patches.
4126 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4127 const struct audio_port_config *source = &patch->sources[0];
4128 sp<SourceClientDescriptor> sourceDesc =
4129 new InternalSourceClientDescriptor(
4130 portId, uid, attributes, *source, srcDevice, sinkDevice,
4131 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4132
4133 status_t status =
4134 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4135
4136 if (status != NO_ERROR) {
4137 return INVALID_OPERATION;
4138 }
4139 mAudioSources.add(portId, sourceDesc);
4140 return NO_ERROR;
4141}
4142
4143status_t AudioPolicyManager::connectAudioSourceToSink(
4144 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4145 const struct audio_patch *patch,
4146 audio_patch_handle_t &handle,
4147 uid_t uid, uint32_t delayMs)
4148{
4149 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4150 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4151 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4152 return INVALID_OPERATION;
4153 }
4154 sourceDesc->connect(handle, sinkDevice);
4155 if (isMsdPatch(handle)) {
4156 return NO_ERROR;
4157 }
4158 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4159 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4160 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4161 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4162 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4163 goto FailurePatchAdded;
4164 }
4165 status = swOutput->start();
4166 if (status != NO_ERROR) {
4167 goto FailureSourceAdded;
4168 }
4169 swOutput->addClient(sourceDesc);
4170 status = startSource(swOutput, sourceDesc, &delayMs);
4171 if (status != NO_ERROR) {
4172 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4173 goto FailureSourceActive;
4174 }
4175 if (delayMs != 0) {
4176 usleep(delayMs * 1000);
4177 }
4178 return NO_ERROR;
4179
4180FailureSourceActive:
4181 swOutput->stop();
4182 releaseOutput(sourceDesc->portId());
4183FailureSourceAdded:
4184 sourceDesc->setSwOutput(nullptr);
4185FailurePatchAdded:
4186 releaseAudioPatchInternal(handle);
4187 return INVALID_OPERATION;
4188}
4189
4190status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4191 audio_patch_handle_t *handle,
4192 uid_t uid, uint32_t delayMs,
4193 const sp<SourceClientDescriptor>& sourceDesc)
4194{
4195 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004196 sp<AudioPatch> patchDesc;
4197 ssize_t index = mAudioPatches.indexOfKey(*handle);
4198
François Gaffieafd4cea2019-11-18 15:50:22 +01004199 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4200 patch->sources[0].role,
4201 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004202#if LOG_NDEBUG == 0
4203 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004204 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4205 patch->sinks[i].role,
4206 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004207 }
4208#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004209
4210 if (index >= 0) {
4211 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004212 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4213 __func__, mUidCached, patchDesc->getUid(), uid);
4214 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004215 return INVALID_OPERATION;
4216 }
4217 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004218 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004219 }
4220
4221 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004222 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004223 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004224 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004225 return BAD_VALUE;
4226 }
Eric Laurent84c70242014-06-23 08:46:27 -07004227 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4228 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004229 if (patchDesc != 0) {
4230 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004231 ALOGV("%s source id differs for patch current id %d new id %d",
4232 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004233 return BAD_VALUE;
4234 }
4235 }
Eric Laurent874c42872014-08-08 15:13:39 -07004236 DeviceVector devices;
4237 for (size_t i = 0; i < patch->num_sinks; i++) {
4238 // Only support mix to devices connection
4239 // TODO add support for mix to mix connection
4240 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004241 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004242 return INVALID_OPERATION;
4243 }
4244 sp<DeviceDescriptor> devDesc =
4245 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4246 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004247 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004248 return BAD_VALUE;
4249 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004250
François Gaffie11d30102018-11-02 16:09:09 +01004251 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004252 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004253 NULL, // updatedSamplingRate
4254 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004255 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004256 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004257 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004258 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004259 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004260 return INVALID_OPERATION;
4261 }
4262 devices.add(devDesc);
4263 }
4264 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004265 return INVALID_OPERATION;
4266 }
Eric Laurent874c42872014-08-08 15:13:39 -07004267
Eric Laurent6a94d692014-05-20 11:18:06 -07004268 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004269 ALOGV("%s setting device %s on output %d",
4270 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004271 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004272 index = mAudioPatches.indexOfKey(*handle);
4273 if (index >= 0) {
4274 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004275 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004276 }
4277 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004278 patchDesc->setUid(uid);
4279 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004280 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004281 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004282 return INVALID_OPERATION;
4283 }
4284 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4285 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4286 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004287 // only one sink supported when connecting an input device to a mix
4288 if (patch->num_sinks > 1) {
4289 return INVALID_OPERATION;
4290 }
François Gaffie53615e22015-03-19 09:24:12 +01004291 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004292 if (inputDesc == NULL) {
4293 return BAD_VALUE;
4294 }
4295 if (patchDesc != 0) {
4296 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4297 return BAD_VALUE;
4298 }
4299 }
François Gaffie11d30102018-11-02 16:09:09 +01004300 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004301 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004302 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004303 return BAD_VALUE;
4304 }
4305
François Gaffie11d30102018-11-02 16:09:09 +01004306 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004307 patch->sinks[0].sample_rate,
4308 NULL, /*updatedSampleRate*/
4309 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004310 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004311 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004312 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004313 // FIXME for the parameter type,
4314 // and the NONE
4315 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004316 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004317 return INVALID_OPERATION;
4318 }
4319 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004320 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004321 device->toString().c_str(), inputDesc->mIoHandle);
4322 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004323 index = mAudioPatches.indexOfKey(*handle);
4324 if (index >= 0) {
4325 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004326 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004327 }
4328 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004329 patchDesc->setUid(uid);
4330 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004331 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004332 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004333 return INVALID_OPERATION;
4334 }
4335 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4336 // device to device connection
4337 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004338 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004339 return BAD_VALUE;
4340 }
4341 }
François Gaffie11d30102018-11-02 16:09:09 +01004342 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004343 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004344 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004345 return BAD_VALUE;
4346 }
Eric Laurent874c42872014-08-08 15:13:39 -07004347
Eric Laurent6a94d692014-05-20 11:18:06 -07004348 //update source and sink with our own data as the data passed in the patch may
4349 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004350 PatchBuilder patchBuilder;
4351 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004352
4353 // if first sink is to MSD, establish single MSD patch
4354 if (getMsdAudioOutDevices().contains(
4355 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4356 ALOGV("%s patching to MSD", __FUNCTION__);
4357 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4358 goto installPatch;
4359 }
4360
François Gaffieafd4cea2019-11-18 15:50:22 +01004361 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4362 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004363
Eric Laurent874c42872014-08-08 15:13:39 -07004364 for (size_t i = 0; i < patch->num_sinks; i++) {
4365 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004366 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004367 return INVALID_OPERATION;
4368 }
François Gaffie11d30102018-11-02 16:09:09 +01004369 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004370 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004371 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004372 return BAD_VALUE;
4373 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004374 audio_port_config sinkPortConfig = {};
4375 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4376 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004377
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004378 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4379 // volume management purpose (tracking activity)
4380 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4381 // in config XML to reach the sink so that is can be declared as available.
4382 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4383 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004384 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004385 // take care of dynamic routing for SwOutput selection,
4386 audio_attributes_t attributes = sourceDesc->attributes();
4387 audio_stream_type_t stream = sourceDesc->stream();
4388 audio_attributes_t resultAttr;
4389 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4390 config.sample_rate = sourceDesc->config().sample_rate;
4391 config.channel_mask = sourceDesc->config().channel_mask;
4392 config.format = sourceDesc->config().format;
4393 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4394 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4395 bool isRequestedDeviceForExclusiveUse = false;
4396 output_type_t outputType;
4397 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4398 &stream, sourceDesc->uid(), &config, &flags,
4399 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4400 nullptr, &outputType);
4401 if (output == AUDIO_IO_HANDLE_NONE) {
4402 ALOGV("%s no output for device %s",
4403 __FUNCTION__, sinkDevice->toString().c_str());
4404 return INVALID_OPERATION;
4405 }
4406 outputDesc = mOutputs.valueFor(output);
4407 if (outputDesc->isDuplicated()) {
4408 ALOGE("%s output is duplicated", __func__);
4409 return INVALID_OPERATION;
4410 }
4411 sourceDesc->setSwOutput(outputDesc);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004412 } else {
4413 // Same for "raw patches" aka created from createAudioPatch API
4414 SortedVector<audio_io_handle_t> outputs =
4415 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4416 // if the sink device is reachable via an opened output stream, request to
4417 // go via this output stream by adding a second source to the patch
4418 // description
4419 output = selectOutput(outputs);
4420 if (output == AUDIO_IO_HANDLE_NONE) {
4421 ALOGE("%s no output available for internal patch sink", __func__);
4422 return INVALID_OPERATION;
4423 }
4424 outputDesc = mOutputs.valueFor(output);
4425 if (outputDesc->isDuplicated()) {
4426 ALOGV("%s output for device %s is duplicated",
4427 __func__, sinkDevice->toString().c_str());
4428 return INVALID_OPERATION;
4429 }
4430 sourceDesc->setSwOutput(outputDesc);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004431 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004432 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004433 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004434 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004435 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004436 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4437 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004438 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4439 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004440 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004441 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004442 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004443 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004444 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004445 return INVALID_OPERATION;
4446 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004447 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004448 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004449 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004450 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004451 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004452 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4453 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4454 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004455 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004456 }
Eric Laurent83b88082014-06-20 18:31:16 -07004457 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004458 }
4459 // TODO: check from routing capabilities in config file and other conflicting patches
4460
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004461installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004462 status_t status = installPatch(
4463 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004464 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004465 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004466 return INVALID_OPERATION;
4467 }
4468 } else {
4469 return BAD_VALUE;
4470 }
4471 } else {
4472 return BAD_VALUE;
4473 }
4474 return NO_ERROR;
4475}
4476
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004477status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004478{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004479 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004480 ssize_t index = mAudioPatches.indexOfKey(handle);
4481
4482 if (index < 0) {
4483 return BAD_VALUE;
4484 }
4485 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004486 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4487 __func__, mUidCached, patchDesc->getUid(), uid);
4488 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004489 return INVALID_OPERATION;
4490 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004491 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4492 for (size_t i = 0; i < mAudioSources.size(); i++) {
4493 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4494 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4495 portId = sourceDesc->portId();
4496 break;
4497 }
4498 }
4499 return portId != AUDIO_PORT_HANDLE_NONE ?
4500 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004501}
Eric Laurent6a94d692014-05-20 11:18:06 -07004502
François Gaffieafd4cea2019-11-18 15:50:22 +01004503status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004504 uint32_t delayMs,
4505 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004506{
4507 ALOGV("%s patch %d", __func__, handle);
4508 if (mAudioPatches.indexOfKey(handle) < 0) {
4509 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4510 return BAD_VALUE;
4511 }
4512 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004513 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004514 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004515 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004516 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004517 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004518 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004519 return BAD_VALUE;
4520 }
4521
François Gaffie11d30102018-11-02 16:09:09 +01004522 setOutputDevices(outputDesc,
4523 getNewOutputDevices(outputDesc, true /*fromCache*/),
4524 true,
4525 0,
4526 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004527 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4528 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004529 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004530 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004531 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004532 return BAD_VALUE;
4533 }
4534 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004535 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004536 true,
4537 NULL);
4538 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004539 status_t status =
4540 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4541 ALOGV("%s patch panel returned %d patchHandle %d",
4542 __func__, status, patchDesc->getAfHandle());
4543 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004544 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004545 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004546 // SW or HW Bridge
4547 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4548 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004549 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004550 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4551 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4552 outputDesc = sourceDesc->swOutput().promote();
4553 }
4554 if (outputDesc == nullptr) {
4555 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4556 // releaseOutput has already called closeOutput in case of direct output
4557 return NO_ERROR;
4558 }
4559 if (!outputDesc->isActive() && !sourceDesc->useSwBridge()) {
4560 resetOutputDevice(outputDesc);
4561 } else {
4562 // Reuse patch handle if still valid / do not force rerouting if still routed
4563 patchHandle = outputDesc->getPatchHandle();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004564 setOutputDevices(outputDesc,
4565 getNewOutputDevices(outputDesc, true /*fromCache*/),
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004566 patchHandle == AUDIO_PATCH_HANDLE_NONE, /*force*/
Francois Gaffie7feb8542020-04-06 17:39:47 +02004567 0,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004568 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Francois Gaffie7feb8542020-04-06 17:39:47 +02004569 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004570 } else {
4571 return BAD_VALUE;
4572 }
4573 } else {
4574 return BAD_VALUE;
4575 }
4576 return NO_ERROR;
4577}
4578
4579status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4580 struct audio_patch *patches,
4581 unsigned int *generation)
4582{
François Gaffie53615e22015-03-19 09:24:12 +01004583 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004584 return BAD_VALUE;
4585 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004586 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004587 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004588}
4589
Eric Laurente1715a42014-05-20 11:30:42 -07004590status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004591{
Eric Laurente1715a42014-05-20 11:30:42 -07004592 ALOGV("setAudioPortConfig()");
4593
4594 if (config == NULL) {
4595 return BAD_VALUE;
4596 }
4597 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4598 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004599 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4600 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004601 }
4602
Eric Laurenta121f902014-06-03 13:32:54 -07004603 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004604 if (config->type == AUDIO_PORT_TYPE_MIX) {
4605 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004606 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004607 if (outputDesc == NULL) {
4608 return BAD_VALUE;
4609 }
Eric Laurent84c70242014-06-23 08:46:27 -07004610 ALOG_ASSERT(!outputDesc->isDuplicated(),
4611 "setAudioPortConfig() called on duplicated output %d",
4612 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004613 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004614 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004615 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004616 if (inputDesc == NULL) {
4617 return BAD_VALUE;
4618 }
Eric Laurenta121f902014-06-03 13:32:54 -07004619 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004620 } else {
4621 return BAD_VALUE;
4622 }
4623 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4624 sp<DeviceDescriptor> deviceDesc;
4625 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4626 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4627 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4628 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4629 } else {
4630 return BAD_VALUE;
4631 }
4632 if (deviceDesc == NULL) {
4633 return BAD_VALUE;
4634 }
Eric Laurenta121f902014-06-03 13:32:54 -07004635 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004636 } else {
4637 return BAD_VALUE;
4638 }
4639
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004640 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004641 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4642 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004643 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004644 audioPortConfig->toAudioPortConfig(&newConfig, config);
4645 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004646 }
Eric Laurenta121f902014-06-03 13:32:54 -07004647 if (status != NO_ERROR) {
4648 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004649 }
Eric Laurente1715a42014-05-20 11:30:42 -07004650
4651 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004652}
4653
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004654void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4655{
Eric Laurentd60560a2015-04-10 11:31:20 -07004656 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004657 clearAudioPatches(uid);
4658 clearSessionRoutes(uid);
4659}
4660
Eric Laurent6a94d692014-05-20 11:18:06 -07004661void AudioPolicyManager::clearAudioPatches(uid_t uid)
4662{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004663 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004664 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004665 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004666 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004667 }
4668 }
4669}
4670
François Gaffiec005e562018-11-06 15:04:49 +01004671void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004672{
François Gaffiec005e562018-11-06 15:04:49 +01004673 // Take the first attributes following the product strategy as it is used to retrieve the routed
4674 // device. All attributes wihin a strategy follows the same "routing strategy"
4675 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4676 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004677 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004678 for (size_t j = 0; j < mOutputs.size(); j++) {
4679 if (mOutputs.keyAt(j) == ouptutToSkip) {
4680 continue;
4681 }
4682 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004683 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004684 continue;
4685 }
4686 // If the default device for this strategy is on another output mix,
4687 // invalidate all tracks in this strategy to force re connection.
4688 // Otherwise select new device on the output mix.
4689 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004690 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4691 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004692 }
4693 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004694 setOutputDevices(
4695 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004696 }
4697 }
4698}
4699
4700void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4701{
4702 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004703 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004704 for (size_t i = 0; i < mOutputs.size(); i++) {
4705 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004706 for (const auto& client : outputDesc->getClientIterable()) {
4707 if (client->hasPreferredDevice() && client->uid() == uid) {
4708 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004709 auto clientStrategy = client->strategy();
4710 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4711 end(affectedStrategies)) {
4712 continue;
4713 }
4714 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004715 }
4716 }
4717 }
4718 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004719 for (const auto& strategy : affectedStrategies) {
4720 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004721 }
4722
4723 // remove input routes associated with this uid
4724 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004725 for (size_t i = 0; i < mInputs.size(); i++) {
4726 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004727 for (const auto& client : inputDesc->getClientIterable()) {
4728 if (client->hasPreferredDevice() && client->uid() == uid) {
4729 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4730 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004731 }
4732 }
4733 }
4734 // reroute inputs if necessary
4735 SortedVector<audio_io_handle_t> inputsToClose;
4736 for (size_t i = 0; i < mInputs.size(); i++) {
4737 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004738 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004739 inputsToClose.add(inputDesc->mIoHandle);
4740 }
4741 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004742 for (const auto& input : inputsToClose) {
4743 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004744 }
4745}
4746
Eric Laurentd60560a2015-04-10 11:31:20 -07004747void AudioPolicyManager::clearAudioSources(uid_t uid)
4748{
4749 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004750 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4751 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004752 stopAudioSource(mAudioSources.keyAt(i));
4753 }
4754 }
4755}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004756
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004757status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4758 audio_io_handle_t *ioHandle,
4759 audio_devices_t *device)
4760{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004761 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4762 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004763 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004764 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004765
François Gaffiedf372692015-03-19 10:43:27 +01004766 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004767}
4768
Eric Laurentd60560a2015-04-10 11:31:20 -07004769status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004770 const audio_attributes_t *attributes,
4771 audio_port_handle_t *portId,
4772 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004773{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004774 ALOGV("%s", __FUNCTION__);
4775 *portId = AUDIO_PORT_HANDLE_NONE;
4776
4777 if (source == NULL || attributes == NULL || portId == NULL) {
4778 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4779 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004780 return BAD_VALUE;
4781 }
4782
Eric Laurentd60560a2015-04-10 11:31:20 -07004783 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4784 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004785 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4786 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004787 return INVALID_OPERATION;
4788 }
4789
François Gaffie11d30102018-11-02 16:09:09 +01004790 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004791 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004792 String8(source->ext.device.address),
4793 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004794 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004795 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004796 return BAD_VALUE;
4797 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004798
jiabin4ef93452019-09-10 14:29:54 -07004799 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004800
François Gaffieaaac0fd2018-11-22 17:56:39 +01004801 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004802 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004803 mEngine->getStreamTypeForAttributes(*attributes),
4804 mEngine->getProductStrategyForAttributes(*attributes),
4805 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004806
4807 status_t status = connectAudioSource(sourceDesc);
4808 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004809 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004810 }
4811 return status;
4812}
4813
Francois Gaffie601801d2021-06-22 13:27:39 +02004814sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4815 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4816{
4817 ALOGV("%s", __FUNCTION__);
4818 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4819
4820 status_t status = startAudioSource(source, attributes, &portId, uid);
4821 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4822 return mAudioSources.valueFor(portId);
4823}
4824
4825
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004826status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004827{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004828 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004829
4830 // make sure we only have one patch per source.
4831 disconnectAudioSource(sourceDesc);
4832
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004833 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004834 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4835 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4836 sourceDesc->srcDevice()->type(),
4837 String8(sourceDesc->srcDevice()->address().c_str()),
4838 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004839 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004840 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004841 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004842 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004843 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4844 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4845 return INVALID_OPERATION;
4846 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004847 PatchBuilder patchBuilder;
4848 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4849 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01004850
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004851 return connectAudioSourceToSink(
4852 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07004853}
4854
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004855status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004856{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004857 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4858 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004859 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004860 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004861 return BAD_VALUE;
4862 }
4863 status_t status = disconnectAudioSource(sourceDesc);
4864
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004865 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004866 return status;
4867}
4868
Andy Hung2ddee192015-12-18 17:34:44 -08004869status_t AudioPolicyManager::setMasterMono(bool mono)
4870{
4871 if (mMasterMono == mono) {
4872 return NO_ERROR;
4873 }
4874 mMasterMono = mono;
4875 // if enabling mono we close all offloaded devices, which will invalidate the
4876 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4877 // for recreating the new AudioTrack as non-offloaded PCM.
4878 //
4879 // If disabling mono, we leave all tracks as is: we don't know which clients
4880 // and tracks are able to be recreated as offloaded. The next "song" should
4881 // play back offloaded.
4882 if (mMasterMono) {
4883 Vector<audio_io_handle_t> offloaded;
4884 for (size_t i = 0; i < mOutputs.size(); ++i) {
4885 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4886 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4887 offloaded.push(desc->mIoHandle);
4888 }
4889 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004890 for (const auto& handle : offloaded) {
4891 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004892 }
4893 }
4894 // update master mono for all remaining outputs
4895 for (size_t i = 0; i < mOutputs.size(); ++i) {
4896 updateMono(mOutputs.keyAt(i));
4897 }
4898 return NO_ERROR;
4899}
4900
4901status_t AudioPolicyManager::getMasterMono(bool *mono)
4902{
4903 *mono = mMasterMono;
4904 return NO_ERROR;
4905}
4906
Eric Laurentac9cef52017-06-09 15:46:26 -07004907float AudioPolicyManager::getStreamVolumeDB(
4908 audio_stream_type_t stream, int index, audio_devices_t device)
4909{
jiabin9a3361e2019-10-01 09:38:30 -07004910 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004911}
4912
jiabin81772902018-04-02 17:52:27 -07004913status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4914 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004915 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004916{
Kriti Dang6537def2021-03-02 13:46:59 +01004917 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4918 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004919 return BAD_VALUE;
4920 }
Kriti Dang6537def2021-03-02 13:46:59 +01004921 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4922 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004923
4924 size_t formatsWritten = 0;
4925 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004926
Kriti Dang6537def2021-03-02 13:46:59 +01004927 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004928 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4929 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004930 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004931 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004932 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004933 bool formatEnabled = true;
4934 switch (forceUse) {
4935 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004936 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004937 break;
4938 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4939 formatEnabled = false;
4940 break;
4941 default: // AUTO or ALWAYS => true
4942 break;
jiabin81772902018-04-02 17:52:27 -07004943 }
4944 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4945 }
jiabin81772902018-04-02 17:52:27 -07004946 }
4947 return NO_ERROR;
4948}
4949
Kriti Dang6537def2021-03-02 13:46:59 +01004950status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4951 audio_format_t *surroundFormats) {
4952 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4953 return BAD_VALUE;
4954 }
4955 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4956 __func__, *numSurroundFormats, surroundFormats);
4957
4958 size_t formatsWritten = 0;
4959 size_t formatsMax = *numSurroundFormats;
4960 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4961
4962 // Return formats from all device profiles that have already been resolved by
4963 // checkOutputsForDevice().
4964 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4965 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4966 audio_devices_t deviceType = device->type();
4967 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4968 // returns formats reported by HDMI devices.
4969 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4970 continue;
4971 }
4972 // Formats reported by sink devices
4973 std::unordered_set<audio_format_t> formatset;
4974 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4975 formatset.insert(it->second.begin(), it->second.end());
4976 }
4977
4978 // Formats hard-coded in the in policy configuration file (if any).
4979 FormatVector encodedFormats = device->encodedFormats();
4980 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4981 // Filter the formats which are supported by the vendor hardware.
4982 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4983 if (mConfig.getSurroundFormats().count(*it) != 0) {
4984 formats.insert(*it);
4985 } else {
4986 for (const auto& pair : mConfig.getSurroundFormats()) {
4987 if (pair.second.count(*it) != 0) {
4988 formats.insert(pair.first);
4989 break;
4990 }
4991 }
4992 }
4993 }
4994 }
4995 *numSurroundFormats = formats.size();
4996 for (const auto& format: formats) {
4997 if (formatsWritten < formatsMax) {
4998 surroundFormats[formatsWritten++] = format;
4999 }
5000 }
5001 return NO_ERROR;
5002}
5003
jiabin81772902018-04-02 17:52:27 -07005004status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5005{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005006 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005007 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5008 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005009 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005010 return BAD_VALUE;
5011 }
5012
Mikhail Naganov100f0122018-11-29 11:22:16 -08005013 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5014 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005015 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005016 return INVALID_OPERATION;
5017 }
5018
Mikhail Naganov100f0122018-11-29 11:22:16 -08005019 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005020 return NO_ERROR;
5021 }
5022
Mikhail Naganov100f0122018-11-29 11:22:16 -08005023 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005024 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005025 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005026 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005027 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005028 }
5029 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005030 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005031 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005032 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005033 }
5034 }
5035
5036 sp<SwAudioOutputDescriptor> outputDesc;
5037 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005038 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5039 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005040 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5041 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005042 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005043 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005044 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5045 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5046 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005047 name.c_str(),
5048 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005049 if (status != NO_ERROR) {
5050 continue;
5051 }
5052 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5053 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5054 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005055 name.c_str(),
5056 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005057 profileUpdated |= (status == NO_ERROR);
5058 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005059 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005060 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005061 AUDIO_DEVICE_IN_HDMI);
5062 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5063 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005064 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005065 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005066 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5067 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5068 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005069 name.c_str(),
5070 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005071 if (status != NO_ERROR) {
5072 continue;
5073 }
5074 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5075 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5076 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005077 name.c_str(),
5078 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005079 profileUpdated |= (status == NO_ERROR);
5080 }
5081
jiabin81772902018-04-02 17:52:27 -07005082 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005083 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005084 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005085 }
5086
5087 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5088}
5089
Eric Laurent5ada82e2019-08-29 17:53:54 -07005090void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005091{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005092 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005093 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005094 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005095 }
5096}
5097
jiabin6012f912018-11-02 17:06:30 -07005098bool AudioPolicyManager::isHapticPlaybackSupported()
5099{
5100 for (const auto& hwModule : mHwModules) {
5101 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5102 for (const auto &outProfile : outputProfiles) {
5103 struct audio_port audioPort;
5104 outProfile->toAudioPort(&audioPort);
5105 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5106 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5107 return true;
5108 }
5109 }
5110 }
5111 }
5112 return false;
5113}
5114
Carter Hsu325a8eb2022-01-19 19:56:51 +08005115bool AudioPolicyManager::isUltrasoundSupported()
5116{
5117 bool hasUltrasoundOutput = false;
5118 bool hasUltrasoundInput = false;
5119 for (const auto& hwModule : mHwModules) {
5120 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5121 if (!hasUltrasoundOutput) {
5122 for (const auto &outProfile : outputProfiles) {
5123 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5124 hasUltrasoundOutput = true;
5125 break;
5126 }
5127 }
5128 }
5129
5130 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5131 if (!hasUltrasoundInput) {
5132 for (const auto &inputProfile : inputProfiles) {
5133 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5134 hasUltrasoundInput = true;
5135 break;
5136 }
5137 }
5138 }
5139
5140 if (hasUltrasoundOutput && hasUltrasoundInput)
5141 return true;
5142 }
5143 return false;
5144}
5145
Eric Laurent8340e672019-11-06 11:01:08 -08005146bool AudioPolicyManager::isCallScreenModeSupported()
5147{
5148 return getConfig().isCallScreenModeSupported();
5149}
5150
5151
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005152status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005153{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005154 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005155 if (!sourceDesc->isConnected()) {
5156 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5157 return NO_ERROR;
5158 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005159 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5160 if (swOutput != 0) {
5161 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005162 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005163 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005164 }
jiabinbce0c1d2020-10-05 11:20:18 -07005165 if (releaseOutput(sourceDesc->portId())) {
5166 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5167 // no need to release audio patch here but just return NO_ERROR.
5168 return NO_ERROR;
5169 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005170 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005171 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005172 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005173 // close Hwoutput and remove from mHwOutputs
5174 } else {
5175 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5176 }
5177 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005178 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005179 sourceDesc->disconnect();
5180 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005181}
5182
François Gaffiec005e562018-11-06 15:04:49 +01005183sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5184 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005185{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005186 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005187 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005188 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005189 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005190 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5191 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005192 source = sourceDesc;
5193 break;
5194 }
5195 }
5196 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005197}
5198
Eric Laurent39095982021-08-24 18:29:27 +02005199/* static */
5200bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
5201 switch (channels) {
5202 case AUDIO_CHANNEL_OUT_5POINT1:
5203 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
5204 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
5205 case AUDIO_CHANNEL_OUT_7POINT1:
5206 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
5207 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
5208 return true;
5209 default:
5210 return false;
5211 }
5212}
5213
Eric Laurentb4f42a92022-01-17 17:37:31 +01005214bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005215 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005216 const AudioDeviceTypeAddrVector &devices,
5217 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005218{
5219 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5220 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005221 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005222 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005223 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5224 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5225 return false;
5226 }
5227 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5228 return false;
5229 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005230 }
5231
5232 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005233 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5234 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005235 // to the specified devices must exist.
5236 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005237 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005238 if (profile == nullptr) {
5239 return false;
5240 }
5241
5242 // The caller can have the audio config criteria ignored by either passing a null ptr or
5243 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005244 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005245 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005246 // If the spatializer output is already opened, only channel masks included in the
5247 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005248
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005249 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005250 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005251 return false;
5252 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005253 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5254 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005255 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005256 != config->channel_mask) {
5257 return false;
5258 }
5259 }
5260 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005261 return true;
5262}
5263
5264void AudioPolicyManager::checkVirtualizerClientRoutes() {
5265 std::set<audio_stream_type_t> streamsToInvalidate;
5266 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005267 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5268 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005269 audio_attributes_t attr = client->attributes();
5270 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5271 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5272 audio_config_base_t clientConfig = client->config();
5273 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005274 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005275 && canBeSpatializedInt(&attr, &config,
5276 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005277 streamsToInvalidate.insert(client->stream());
5278 }
5279 }
5280 }
5281
5282 for (audio_stream_type_t stream : streamsToInvalidate) {
5283 mpClientInterface->invalidateStream(stream);
5284 }
5285}
5286
Eric Laurentfa0f6742021-08-17 18:39:44 +02005287status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005288 const audio_attributes_t *attr,
5289 audio_io_handle_t *output) {
5290 *output = AUDIO_IO_HANDLE_NONE;
5291
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005292 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5293 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5294 audio_config_t *configPtr = nullptr;
5295 audio_config_t config;
5296 if (mixerConfig != nullptr) {
5297 config = audio_config_initializer(mixerConfig);
5298 configPtr = &config;
5299 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005300 if (!canBeSpatializedInt(
5301 attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02005302 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005303 return BAD_VALUE;
5304 }
5305
5306 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005307 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005308 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005309 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005310 return BAD_VALUE;
5311 }
5312
Eric Laurent39095982021-08-24 18:29:27 +02005313 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
5314 && configPtr != nullptr
5315 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
5316 *output = mSpatializerOutput->mIoHandle;
5317 ALOGV("%s returns current spatializer output %d", __func__, *output);
5318 return NO_ERROR;
5319 }
5320 mSpatializerOutput.clear();
5321 for (size_t i = 0; i < mOutputs.size(); i++) {
5322 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5323 if (!desc->isDuplicated() && desc->mProfile == profile) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005324 ALOGV("%s found output %d for spatializer profile", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005325 mSpatializerOutput = desc;
5326 break;
5327 }
5328 }
5329 if (mSpatializerOutput == nullptr) {
5330 ALOGW("%s no opened spatializer output for profile %s",
5331 __func__, profile->getName().c_str());
5332 return BAD_VALUE;
5333 }
5334
5335 if (configPtr != nullptr
5336 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5337 audio_config_base_t savedMixerConfig = {
5338 .sample_rate = mSpatializerOutput->getSamplingRate(),
5339 .format = mSpatializerOutput->getFormat(),
5340 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5341 };
5342 DeviceVector savedDevices = mSpatializerOutput->devices();
5343
Eric Laurentb4f42a92022-01-17 17:37:31 +01005344 ALOGV("%s reopening spatializer output to match channel mask %#x (current mask %#x)",
5345 __func__, configPtr->channel_mask, mSpatializerOutput->mMixerChannelMask);
Eric Laurent39095982021-08-24 18:29:27 +02005346
Eric Laurentb4f42a92022-01-17 17:37:31 +01005347 closeOutput(mSpatializerOutput->mIoHandle);
5348 //from now on mSpatializerOutput is null
5349
5350 sp<SwAudioOutputDescriptor> desc =
5351 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
5352 if (desc == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005353 // re open the spatializer output with previous channel mask
Eric Laurentb4f42a92022-01-17 17:37:31 +01005354 desc = openOutputWithProfileAndDevice(profile, savedDevices, &savedMixerConfig);
5355 if (desc == nullptr) {
5356 ALOGE("%s failed to restore mSpatializerOutput with previous config", __func__);
Eric Laurent39095982021-08-24 18:29:27 +02005357 } else {
5358 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005359 }
5360 mPreviousOutputs = mOutputs;
5361 mpClientInterface->onAudioPortListUpdate();
5362 *output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005363 ALOGW("%s could not open spatializer output with requested config", __func__);
5364 return BAD_VALUE;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005365 }
Eric Laurent39095982021-08-24 18:29:27 +02005366 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005367 mPreviousOutputs = mOutputs;
5368 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005369 }
5370
5371 checkVirtualizerClientRoutes();
5372
Eric Laurent39095982021-08-24 18:29:27 +02005373 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005374 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005375 return NO_ERROR;
5376}
5377
Eric Laurentfa0f6742021-08-17 18:39:44 +02005378status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5379 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005380 return INVALID_OPERATION;
5381 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005382 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005383 return BAD_VALUE;
5384 }
Eric Laurent39095982021-08-24 18:29:27 +02005385
Eric Laurentfa0f6742021-08-17 18:39:44 +02005386 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005387
5388 checkVirtualizerClientRoutes();
5389
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005390 return NO_ERROR;
5391}
5392
Eric Laurente552edb2014-03-10 17:42:56 -07005393// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005394// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005395// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005396uint32_t AudioPolicyManager::nextAudioPortGeneration()
5397{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005398 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005399}
5400
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005401static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005402 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5403 !audioPolicyXmlConfigFile.empty()) {
5404 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5405 if (ret == NO_ERROR) {
5406 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005407 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005408 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005409 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005410 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005411}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005412
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005413AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5414 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005415 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005416 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005417 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005418 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005419 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005420 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005421 mAudioPortGeneration(1),
5422 mBeaconMuteRefCount(0),
5423 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005424 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005425 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005426 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005427 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005428{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005429}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005430
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005431AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5432 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5433{
5434 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005435}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005436
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005437void AudioPolicyManager::loadConfig() {
5438 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005439 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005440 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005441 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005442}
5443
5444status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005445 {
5446 auto engLib = EngineLibrary::load(
5447 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5448 if (!engLib) {
5449 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5450 return NO_INIT;
5451 }
5452 mEngine = engLib->createEngine();
5453 if (mEngine == nullptr) {
5454 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5455 return NO_INIT;
5456 }
François Gaffie2110e042015-03-24 08:41:51 +01005457 }
5458 mEngine->setObserver(this);
5459 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005460 if (status != NO_ERROR) {
5461 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5462 return status;
5463 }
François Gaffie2110e042015-03-24 08:41:51 +01005464
Eric Laurent1d69c872021-01-11 18:53:01 +01005465 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5466 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5467
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005468 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005469 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005470 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005471
Eric Laurent3a4311c2014-03-17 12:00:47 -07005472 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005473 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5474 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5475 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005476 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005477 }
jiabin9ff780e2018-03-19 18:19:52 -07005478 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005479 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005480 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005481 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005482 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005483 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005484 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005485 }
5486 }
5487 }
Eric Laurente552edb2014-03-10 17:42:56 -07005488
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005489 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005490
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005491 // Silence ALOGV statements
5492 property_set("log.tag." LOG_TAG, "D");
5493
Eric Laurente552edb2014-03-10 17:42:56 -07005494 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005495 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005496}
5497
Eric Laurente0720872014-03-11 09:30:41 -07005498AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005499{
Eric Laurente552edb2014-03-10 17:42:56 -07005500 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005501 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005502 }
5503 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005504 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005505 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005506 mAvailableOutputDevices.clear();
5507 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005508 mOutputs.clear();
5509 mInputs.clear();
5510 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005511 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005512 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005513}
5514
Eric Laurente0720872014-03-11 09:30:41 -07005515status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005516{
Eric Laurent87ffa392015-05-22 10:32:38 -07005517 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005518}
5519
Eric Laurente552edb2014-03-10 17:42:56 -07005520// ---
5521
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005522void AudioPolicyManager::onNewAudioModulesAvailable()
5523{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005524 DeviceVector newDevices;
5525 onNewAudioModulesAvailableInt(&newDevices);
5526 if (!newDevices.empty()) {
5527 nextAudioPortGeneration();
5528 mpClientInterface->onAudioPortListUpdate();
5529 }
5530}
5531
5532void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5533{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005534 for (const auto& hwModule : mHwModulesAll) {
5535 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5536 continue;
5537 }
5538 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5539 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5540 ALOGW("could not open HW module %s", hwModule->getName());
5541 continue;
5542 }
5543 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005544 // open all output streams needed to access attached devices.
5545 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005546 // This also validates mAvailableOutputDevices list
5547 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5548 if (!outProfile->canOpenNewIo()) {
5549 ALOGE("Invalid Output profile max open count %u for profile %s",
5550 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5551 continue;
5552 }
5553 if (!outProfile->hasSupportedDevices()) {
5554 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5555 continue;
5556 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005557 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5558 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005559 mTtsOutputAvailable = true;
5560 }
5561
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005562 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5563 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5564 sp<DeviceDescriptor> supportedDevice = 0;
5565 if (supportedDevices.contains(mDefaultOutputDevice)) {
5566 supportedDevice = mDefaultOutputDevice;
5567 } else {
5568 // choose first device present in profile's SupportedDevices also part of
5569 // mAvailableOutputDevices.
5570 if (availProfileDevices.isEmpty()) {
5571 continue;
5572 }
5573 supportedDevice = availProfileDevices.itemAt(0);
5574 }
5575 if (!mOutputDevicesAll.contains(supportedDevice)) {
5576 continue;
5577 }
5578 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5579 mpClientInterface);
5580 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005581 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5582 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005583 AUDIO_STREAM_DEFAULT,
5584 AUDIO_OUTPUT_FLAG_NONE, &output);
5585 if (status != NO_ERROR) {
5586 ALOGW("Cannot open output stream for devices %s on hw module %s",
5587 supportedDevice->toString().c_str(), hwModule->getName());
5588 continue;
5589 }
5590 for (const auto &device : availProfileDevices) {
5591 // give a valid ID to an attached device once confirmed it is reachable
5592 if (!device->isAttached()) {
5593 device->attach(hwModule);
5594 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005595 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005596 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005597 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5598 }
5599 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005600 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005601 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5602 mPrimaryOutput = outputDesc;
5603 }
Eric Laurent39095982021-08-24 18:29:27 +02005604 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005605 outputDesc->close();
5606 } else {
5607 addOutput(output, outputDesc);
5608 setOutputDevices(outputDesc,
5609 DeviceVector(supportedDevice),
5610 true,
5611 0,
5612 NULL);
5613 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005614 }
5615 // open input streams needed to access attached devices to validate
5616 // mAvailableInputDevices list
5617 for (const auto& inProfile : hwModule->getInputProfiles()) {
5618 if (!inProfile->canOpenNewIo()) {
5619 ALOGE("Invalid Input profile max open count %u for profile %s",
5620 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5621 continue;
5622 }
5623 if (!inProfile->hasSupportedDevices()) {
5624 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5625 continue;
5626 }
5627 // chose first device present in profile's SupportedDevices also part of
5628 // available input devices
5629 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5630 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5631 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005632 ALOGV("%s: Input device list is empty! for profile %s",
5633 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005634 continue;
5635 }
5636 sp<AudioInputDescriptor> inputDesc =
5637 new AudioInputDescriptor(inProfile, mpClientInterface);
5638
5639 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5640 status_t status = inputDesc->open(nullptr,
5641 availProfileDevices.itemAt(0),
5642 AUDIO_SOURCE_MIC,
5643 AUDIO_INPUT_FLAG_NONE,
5644 &input);
5645 if (status != NO_ERROR) {
5646 ALOGW("Cannot open input stream for device %s on hw module %s",
5647 availProfileDevices.toString().c_str(),
5648 hwModule->getName());
5649 continue;
5650 }
5651 for (const auto &device : availProfileDevices) {
5652 // give a valid ID to an attached device once confirmed it is reachable
5653 if (!device->isAttached()) {
5654 device->attach(hwModule);
5655 device->importAudioPortAndPickAudioProfile(inProfile, true);
5656 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005657 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005658 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5659 }
5660 }
5661 inputDesc->close();
5662 }
5663 }
5664}
5665
Eric Laurent98e38192018-02-15 18:31:53 -08005666void AudioPolicyManager::addOutput(audio_io_handle_t output,
5667 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005668{
Eric Laurent1c333e22014-05-20 10:48:17 -07005669 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005670 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005671 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005672 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005673 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005674}
5675
François Gaffie53615e22015-03-19 09:24:12 +01005676void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5677{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005678 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5679 ALOGV("%s: removing primary output", __func__);
5680 mPrimaryOutput = nullptr;
5681 }
François Gaffie53615e22015-03-19 09:24:12 +01005682 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005683 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005684}
5685
Eric Laurent98e38192018-02-15 18:31:53 -08005686void AudioPolicyManager::addInput(audio_io_handle_t input,
5687 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005688{
Eric Laurent1c333e22014-05-20 10:48:17 -07005689 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005690 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005691}
Eric Laurente552edb2014-03-10 17:42:56 -07005692
François Gaffie11d30102018-11-02 16:09:09 +01005693status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005694 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005695 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005696{
François Gaffie11d30102018-11-02 16:09:09 +01005697 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005698 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005699 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005700
François Gaffie11d30102018-11-02 16:09:09 +01005701 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005702 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005703 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005704 }
Eric Laurente552edb2014-03-10 17:42:56 -07005705
Eric Laurent3b73df72014-03-11 09:06:29 -07005706 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005707 // first call getAudioPort to get the supported attributes from the HAL
5708 struct audio_port_v7 port = {};
5709 device->toAudioPort(&port);
5710 status_t status = mpClientInterface->getAudioPort(&port);
5711 if (status == NO_ERROR) {
5712 device->importAudioPort(port);
5713 }
5714
5715 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005716 for (size_t i = 0; i < mOutputs.size(); i++) {
5717 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005718 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005719 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005720 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5721 mOutputs.keyAt(i), device->toString().c_str());
5722 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005723 }
5724 }
5725 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005726 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005727 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005728 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5729 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005730 if (profile->supportsDevice(device)) {
5731 profiles.add(profile);
5732 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5733 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005734 }
5735 }
5736 }
5737
Eric Laurent7b279bb2015-12-14 10:18:23 -08005738 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005739
Eric Laurente552edb2014-03-10 17:42:56 -07005740 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005741 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005742 return BAD_VALUE;
5743 }
5744
5745 // open outputs for matching profiles if needed. Direct outputs are also opened to
5746 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5747 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005748 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005749
5750 // nothing to do if one output is already opened for this profile
5751 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005752 for (j = 0; j < outputs.size(); j++) {
5753 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005754 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005755 // matching profile: save the sample rates, format and channel masks supported
5756 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005757 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005758 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005759 }
Eric Laurente552edb2014-03-10 17:42:56 -07005760 break;
5761 }
5762 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005763 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005764 continue;
5765 }
5766
Eric Laurent3974e3b2017-12-07 17:58:43 -08005767 if (!profile->canOpenNewIo()) {
5768 ALOGW("Max Output number %u already opened for this profile %s",
5769 profile->maxOpenCount, profile->getTagName().c_str());
5770 continue;
5771 }
5772
Eric Laurent83efe1c2017-07-09 16:51:08 -07005773 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005774 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005775 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5776 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005777 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005778 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005779 profiles.removeAt(profile_index);
5780 profile_index--;
5781 } else {
5782 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005783 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005784 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005785 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5786 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005787 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005788 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005789
François Gaffie11d30102018-11-02 16:09:09 +01005790 if (device_distinguishes_on_address(deviceType)) {
5791 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5792 device->toString().c_str());
5793 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5794 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005795 }
Eric Laurente552edb2014-03-10 17:42:56 -07005796 ALOGV("checkOutputsForDevice(): adding output %d", output);
5797 }
5798 }
5799
5800 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005801 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005802 return BAD_VALUE;
5803 }
Eric Laurentd4692962014-05-05 18:13:44 -07005804 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005805 // check if one opened output is not needed any more after disconnecting one device
5806 for (size_t i = 0; i < mOutputs.size(); i++) {
5807 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005808 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005809 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005810 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005811 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005812 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005813 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005814 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5815 mOutputs.keyAt(i));
5816 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005817 }
Eric Laurente552edb2014-03-10 17:42:56 -07005818 }
5819 }
Eric Laurentd4692962014-05-05 18:13:44 -07005820 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005821 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005822 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5823 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005824 if (!profile->supportsDevice(device)) {
5825 continue;
5826 }
5827 ALOGV("checkOutputsForDevice(): "
5828 "clearing direct output profile %zu on module %s",
5829 j, hwModule->getName());
5830 profile->clearAudioProfiles();
5831 if (!profile->hasDynamicAudioProfile()) {
5832 continue;
5833 }
5834 // When a device is disconnected, if there is an IOProfile that contains dynamic
5835 // profiles and supports the disconnected device, call getAudioPort to repopulate
5836 // the capabilities of the devices that is supported by the IOProfile.
5837 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5838 if (supportedDevice == device ||
5839 !mAvailableOutputDevices.contains(supportedDevice)) {
5840 continue;
5841 }
5842 struct audio_port_v7 port;
5843 supportedDevice->toAudioPort(&port);
5844 status_t status = mpClientInterface->getAudioPort(&port);
5845 if (status == NO_ERROR) {
5846 supportedDevice->importAudioPort(port);
5847 }
Eric Laurente552edb2014-03-10 17:42:56 -07005848 }
5849 }
5850 }
5851 }
5852 return NO_ERROR;
5853}
5854
François Gaffie11d30102018-11-02 16:09:09 +01005855status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005856 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005857{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005858 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005859
François Gaffie11d30102018-11-02 16:09:09 +01005860 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005861 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005862 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005863 }
5864
Eric Laurentd4692962014-05-05 18:13:44 -07005865 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005866 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005867 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005868 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005869 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005870 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005871 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005872 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005873
François Gaffie11d30102018-11-02 16:09:09 +01005874 if (profile->supportsDevice(device)) {
5875 profiles.add(profile);
5876 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5877 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005878 }
5879 }
5880 }
5881
Eric Laurent0dd51852019-04-19 18:18:58 -07005882 if (profiles.isEmpty()) {
5883 ALOGW("%s: No input profile available for device %s",
5884 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005885 return BAD_VALUE;
5886 }
5887
5888 // open inputs for matching profiles if needed. Direct inputs are also opened to
5889 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5890 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5891
Eric Laurent1c333e22014-05-20 10:48:17 -07005892 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005893
Eric Laurentd4692962014-05-05 18:13:44 -07005894 // nothing to do if one input is already opened for this profile
5895 size_t input_index;
5896 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5897 desc = mInputs.valueAt(input_index);
5898 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005899 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005900 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005901 }
Eric Laurentd4692962014-05-05 18:13:44 -07005902 break;
5903 }
5904 }
5905 if (input_index != mInputs.size()) {
5906 continue;
5907 }
5908
Eric Laurent3974e3b2017-12-07 17:58:43 -08005909 if (!profile->canOpenNewIo()) {
5910 ALOGW("Max Input number %u already opened for this profile %s",
5911 profile->maxOpenCount, profile->getTagName().c_str());
5912 continue;
5913 }
5914
Eric Laurentfe231122017-11-17 17:48:06 -08005915 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005916 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005917 status_t status = desc->open(nullptr,
5918 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005919 AUDIO_SOURCE_MIC,
5920 AUDIO_INPUT_FLAG_NONE,
5921 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005922
Eric Laurentcf2c0212014-07-25 16:20:43 -07005923 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005924 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005925 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005926 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005927 mpClientInterface->setParameters(input, String8(param));
5928 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005929 }
François Gaffie11d30102018-11-02 16:09:09 +01005930 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005931 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005932 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005933 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005934 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005935 }
5936
Eric Laurent0dd51852019-04-19 18:18:58 -07005937 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005938 addInput(input, desc);
5939 }
5940 } // endif input != 0
5941
Eric Laurentcf2c0212014-07-25 16:20:43 -07005942 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08005943 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005944 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005945 profiles.removeAt(profile_index);
5946 profile_index--;
5947 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005948 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005949 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005950 }
Eric Laurentd4692962014-05-05 18:13:44 -07005951 ALOGV("checkInputsForDevice(): adding input %d", input);
5952 }
5953 } // end scan profiles
5954
5955 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005956 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005957 return BAD_VALUE;
5958 }
5959 } else {
5960 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005961 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005962 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005963 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005964 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005965 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005966 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005967 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005968 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5969 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005970 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005971 }
5972 }
5973 }
5974 } // end disconnect
5975
5976 return NO_ERROR;
5977}
5978
5979
Eric Laurente0720872014-03-11 09:30:41 -07005980void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005981{
5982 ALOGV("closeOutput(%d)", output);
5983
François Gaffie1c878552018-11-22 16:53:21 +01005984 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5985 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005986 ALOGW("closeOutput() unknown output %d", output);
5987 return;
5988 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005989 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005990 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005991
Eric Laurente552edb2014-03-10 17:42:56 -07005992 // look for duplicated outputs connected to the output being removed.
5993 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005994 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5995 if (dupOutput->isDuplicated() &&
5996 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5997 sp<SwAudioOutputDescriptor> remainingOutput =
5998 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005999 // As all active tracks on duplicated output will be deleted,
6000 // and as they were also referenced on the other output, the reference
6001 // count for their stream type must be adjusted accordingly on
6002 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006003 const bool wasActive = remainingOutput->isActive();
6004 // Note: no-op on the closing output where all clients has already been set inactive
6005 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006006 // stop() will be a no op if the output is still active but is needed in case all
6007 // active streams refcounts where cleared above
6008 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006009 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006010 }
Eric Laurente552edb2014-03-10 17:42:56 -07006011 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6012 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6013
6014 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006015 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006016 }
6017 }
6018
Eric Laurent05b90f82014-08-27 15:32:29 -07006019 nextAudioPortGeneration();
6020
François Gaffie1c878552018-11-22 16:53:21 +01006021 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006022 if (index >= 0) {
6023 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006024 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6025 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006026 mAudioPatches.removeItemsAt(index);
6027 mpClientInterface->onAudioPatchListUpdate();
6028 }
6029
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006030 if (closingOutputWasActive) {
6031 closingOutput->stop();
6032 }
François Gaffie1c878552018-11-22 16:53:21 +01006033 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006034
François Gaffie53615e22015-03-19 09:24:12 +01006035 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006036 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006037 if (closingOutput == mSpatializerOutput) {
6038 mSpatializerOutput.clear();
6039 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006040
6041 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6042 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006043 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006044 bool directOutputOpen = false;
6045 for (size_t i = 0; i < mOutputs.size(); i++) {
6046 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6047 directOutputOpen = true;
6048 break;
6049 }
6050 }
6051 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006052 ALOGV("no direct outputs open, reset MSD patches");
6053 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6054 // how output devices for patching are resolved. Avoid by caching and reusing the
6055 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6056 // devices to patch to. This may be complicated by the fact that devices may become
6057 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006058 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006059 }
6060 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006061}
6062
6063void AudioPolicyManager::closeInput(audio_io_handle_t input)
6064{
6065 ALOGV("closeInput(%d)", input);
6066
6067 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6068 if (inputDesc == NULL) {
6069 ALOGW("closeInput() unknown input %d", input);
6070 return;
6071 }
6072
Eric Laurent6a94d692014-05-20 11:18:06 -07006073 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006074
François Gaffie11d30102018-11-02 16:09:09 +01006075 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006076 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006077 if (index >= 0) {
6078 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006079 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6080 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006081 mAudioPatches.removeItemsAt(index);
6082 mpClientInterface->onAudioPatchListUpdate();
6083 }
6084
Eric Laurentfe231122017-11-17 17:48:06 -08006085 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006086 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006087
François Gaffie11d30102018-11-02 16:09:09 +01006088 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6089 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006090 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006091 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006092 }
Eric Laurente552edb2014-03-10 17:42:56 -07006093}
6094
François Gaffie11d30102018-11-02 16:09:09 +01006095SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6096 const DeviceVector &devices,
6097 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006098{
6099 SortedVector<audio_io_handle_t> outputs;
6100
François Gaffie11d30102018-11-02 16:09:09 +01006101 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006102 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006103 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006104 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006105 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006106 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006107 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006108 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006109 outputs.add(openOutputs.keyAt(i));
6110 }
6111 }
6112 return outputs;
6113}
6114
Mikhail Naganov37977152018-07-11 15:54:44 -07006115void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6116{
6117 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6118 // output is suspended before any tracks are moved to it
6119 checkA2dpSuspend();
6120 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006121 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006122 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006123 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006124 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006125 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6126 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6127 // configuration changes will ultimately be rerouted correctly. We can still avoid
6128 // unnecessary rerouting by caching and reusing the arguments to
6129 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6130 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006131 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006132 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006133 // an event that changed routing likely occurred, inform upper layers
6134 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006135}
6136
François Gaffiec005e562018-11-06 15:04:49 +01006137bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6138 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006139{
François Gaffiec005e562018-11-06 15:04:49 +01006140 return mEngine->getProductStrategyForAttributes(lAttr) ==
6141 mEngine->getProductStrategyForAttributes(rAttr);
6142}
6143
Francois Gaffieff1eb522020-05-06 18:37:04 +02006144void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6145{
6146 for (size_t i = 0; i < mAudioSources.size(); i++) {
6147 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6148 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006149 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006150 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006151 connectAudioSource(sourceDesc);
6152 }
6153 }
6154}
6155
6156void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6157{
6158 for (size_t i = 0; i < mAudioSources.size(); i++) {
6159 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6160 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6161 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6162 disconnectAudioSource(sourceDesc);
6163 }
6164 }
6165}
6166
François Gaffiec005e562018-11-06 15:04:49 +01006167void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6168{
6169 auto psId = mEngine->getProductStrategyForAttributes(attr);
6170
6171 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6172 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006173
François Gaffie11d30102018-11-02 16:09:09 +01006174 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6175 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006176
Eric Laurentc209fe42020-06-05 18:11:23 -07006177 uint32_t maxLatency = 0;
6178 bool invalidate = false;
6179 // take into account dynamic audio policies related changes: if a client is now associated
6180 // to a different policy mix than at creation time, invalidate corresponding stream
6181 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6182 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6183 if (desc->isDuplicated()) {
6184 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006185 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006186 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6187 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6188 continue;
6189 }
6190 sp<AudioPolicyMix> primaryMix;
6191 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
6192 client->flags(), primaryMix, nullptr);
6193 if (status != OK) {
6194 continue;
6195 }
yucliuf4de36d2020-09-14 14:57:56 -07006196 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006197 invalidate = true;
6198 if (desc->isStrategyActive(psId)) {
6199 maxLatency = desc->latency();
6200 }
6201 break;
6202 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006203 }
6204 }
6205
Eric Laurentc209fe42020-06-05 18:11:23 -07006206 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006207 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6208 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006209 for (audio_io_handle_t srcOut : srcOutputs) {
6210 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006211 if (desc == nullptr) continue;
6212
6213 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006214 maxLatency = desc->latency();
6215 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006216
6217 if (invalidate) continue;
6218
6219 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006220 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006221 // a client on a non direct outputs has necessarily a linear PCM format
6222 // so we can call selectOutput() safely
6223 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6224 client->flags(),
6225 client->config().format,
6226 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006227 client->config().sample_rate,
6228 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006229 if (newOutput != srcOut) {
6230 invalidate = true;
6231 break;
6232 }
6233 } else {
6234 sp<IOProfile> profile = getProfileForOutput(newDevices,
6235 client->config().sample_rate,
6236 client->config().format,
6237 client->config().channel_mask,
6238 client->flags(),
6239 true /* directOnly */);
6240 if (profile != desc->mProfile) {
6241 invalidate = true;
6242 break;
6243 }
6244 }
6245 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006246 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006247
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006248 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006249 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006250 std::to_string(srcOutputs[0]).c_str(),
6251 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006252 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006253 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006254 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006255 if (desc == nullptr) continue;
6256
6257 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006258 setStrategyMute(psId, true, desc);
6259 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006260 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006261 }
François Gaffiec005e562018-11-06 15:04:49 +01006262 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006263 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006264 connectAudioSource(source);
6265 }
Eric Laurente552edb2014-03-10 17:42:56 -07006266 }
6267
François Gaffiec005e562018-11-06 15:04:49 +01006268 // Move effects associated to this stream from previous output to new output
6269 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006270 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006271 }
François Gaffiec005e562018-11-06 15:04:49 +01006272 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006273 if (invalidate) {
6274 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6275 mpClientInterface->invalidateStream(stream);
6276 }
Eric Laurente552edb2014-03-10 17:42:56 -07006277 }
6278 }
6279}
6280
Eric Laurente0720872014-03-11 09:30:41 -07006281void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006282{
François Gaffiec005e562018-11-06 15:04:49 +01006283 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6284 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6285 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006286 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006287 }
Eric Laurente552edb2014-03-10 17:42:56 -07006288}
6289
Kevin Rocard153f92d2018-12-18 18:33:28 -08006290void AudioPolicyManager::checkSecondaryOutputs() {
6291 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006292 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006293 for (size_t i = 0; i < mOutputs.size(); i++) {
6294 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6295 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006296 sp<AudioPolicyMix> primaryMix;
6297 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006298 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006299 client->flags(), primaryMix, &secondaryMixes);
6300 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6301 for (auto &secondaryMix : secondaryMixes) {
6302 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6303 if (outputDesc != nullptr &&
6304 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6305 secondaryDescs.push_back(outputDesc);
6306 }
6307 }
6308
jiabin10a03f12021-05-07 23:46:28 +00006309 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006310 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006311 } else if (!std::equal(
6312 client->getSecondaryOutputs().begin(),
6313 client->getSecondaryOutputs().end(),
6314 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006315 if (!audio_is_linear_pcm(client->config().format)) {
6316 // If the format is not PCM, the tracks should be invalidated to get correct
6317 // behavior when the secondary output is changed.
6318 streamsToInvalidate.insert(client->stream());
6319 } else {
6320 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6321 std::vector<audio_io_handle_t> secondaryOutputIds;
6322 for (const auto &secondaryDesc: secondaryDescs) {
6323 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6324 weakSecondaryDescs.push_back(secondaryDesc);
6325 }
6326 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6327 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006328 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006329 }
6330 }
6331 }
jiabin10a03f12021-05-07 23:46:28 +00006332 if (!trackSecondaryOutputs.empty()) {
6333 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6334 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006335 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006336 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006337 mpClientInterface->invalidateStream(stream);
6338 }
6339}
6340
Eric Laurent2517af32020-11-25 15:31:27 +01006341bool AudioPolicyManager::isScoRequestedForComm() const {
6342 AudioDeviceTypeAddrVector devices;
6343 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6344 for (const auto &device : devices) {
6345 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6346 return true;
6347 }
6348 }
6349 return false;
6350}
6351
Eric Laurente0720872014-03-11 09:30:41 -07006352void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006353{
François Gaffie53615e22015-03-19 09:24:12 +01006354 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006355 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006356 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006357 return;
6358 }
6359
Eric Laurent3a4311c2014-03-17 12:00:47 -07006360 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006361 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6362 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006363 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006364
6365 // if suspended, restore A2DP output if:
6366 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006367 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006368 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006369 //
Eric Laurentf732e072016-08-03 19:30:28 -07006370 // if not suspended, suspend A2DP output if:
6371 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006372 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006373 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006374 //
6375 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006376 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006377 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006378 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006379 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006380
6381 mpClientInterface->restoreOutput(a2dpOutput);
6382 mA2dpSuspended = false;
6383 }
6384 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006385 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006386 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006387 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006388 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006389
6390 mpClientInterface->suspendOutput(a2dpOutput);
6391 mA2dpSuspended = true;
6392 }
6393 }
6394}
6395
François Gaffie11d30102018-11-02 16:09:09 +01006396DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6397 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006398{
François Gaffie11d30102018-11-02 16:09:09 +01006399 DeviceVector devices;
6400
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006401 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006402 if (index >= 0) {
6403 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006404 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006405 ALOGV("%s device %s forced by patch %d", __func__,
6406 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6407 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006408 }
6409 }
6410
Dean Wheatley514b4312020-06-17 21:45:00 +10006411 // Do not retrieve engine device for outputs through MSD
6412 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6413 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6414 return outputDesc->devices();
6415 }
6416
Eric Laurent97ac8712018-07-27 18:59:02 -07006417 // Honor explicit routing requests only if no client using default routing is active on this
6418 // input: a specific app can not force routing for other apps by setting a preferred device.
6419 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006420 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006421 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006422 if (device != nullptr) {
6423 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006424 }
6425
François Gaffiea807ef92018-11-05 10:44:33 +01006426 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6427 // of setForceUse / Default Bus device here
6428 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6429 if (device != nullptr) {
6430 return DeviceVector(device);
6431 }
6432
François Gaffiec005e562018-11-06 15:04:49 +01006433 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6434 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6435 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306436 auto hasStreamActive = [&](auto stream) {
6437 return hasStream(streams, stream) && isStreamActive(stream, 0);
6438 };
Eric Laurent484e9272018-06-07 17:29:23 -07006439
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306440 auto doGetOutputDevicesForVoice = [&]() {
6441 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006442 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306443 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006444 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6445 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306446 };
6447
6448 // With low-latency playing on speaker, music on WFD, when the first low-latency
6449 // output is stopped, getNewOutputDevices checks for a product strategy
6450 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006451 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306452 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6453 // stream is associated to the output descriptor.
6454 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6455 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6456 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6457 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006458 // Retrieval of devices for voice DL is done on primary output profile, cannot
6459 // check the route (would force modifying configuration file for this profile)
6460 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6461 break;
6462 }
Eric Laurente552edb2014-03-10 17:42:56 -07006463 }
François Gaffiec005e562018-11-06 15:04:49 +01006464 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006465 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006466}
6467
François Gaffie11d30102018-11-02 16:09:09 +01006468sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6469 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006470{
François Gaffie11d30102018-11-02 16:09:09 +01006471 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006472
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006473 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006474 if (index >= 0) {
6475 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006476 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006477 ALOGV("getNewInputDevice() device %s forced by patch %d",
6478 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6479 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006480 }
6481 }
6482
Eric Laurent97ac8712018-07-27 18:59:02 -07006483 // Honor explicit routing requests only if no client using default routing is active on this
6484 // input: a specific app can not force routing for other apps by setting a preferred device.
6485 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006486 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6487 if (device != nullptr) {
6488 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006489 }
6490
Eric Laurentdc95a252018-04-12 12:46:56 -07006491 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006492 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006493 audio_attributes_t attributes;
6494 uid_t uid;
6495 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6496 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006497 attributes = topClient->attributes();
6498 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006499 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006500 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6501 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006502 }
6503
Francois Gaffie716e1432019-01-14 16:58:59 +01006504 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6505 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006506 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006507 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006508 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006509 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006510
Eric Laurente552edb2014-03-10 17:42:56 -07006511 return device;
6512}
6513
Eric Laurent794fde22016-03-11 09:50:45 -08006514bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6515 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006516 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006517}
6518
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006519DeviceTypeSet AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006520 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006521 // getOutputDevicesForStream's behavior for invalid streams.
6522 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6523 // device for music stream), but we want to return the empty set.
6524 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006525 return DeviceTypeSet{};
Eric Laurent6a94d692014-05-20 11:18:06 -07006526 }
François Gaffie11d30102018-11-02 16:09:09 +01006527 DeviceVector activeDevices;
6528 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006529 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6530 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006531 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006532 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006533 }
François Gaffiec005e562018-11-06 15:04:49 +01006534 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006535 devices.merge(curDevices);
6536 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006537 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006538 if (outputDesc->isActive(toVolumeSource(curStream, false))) {
François Gaffie11d30102018-11-02 16:09:09 +01006539 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006540 }
6541 }
Eric Laurente552edb2014-03-10 17:42:56 -07006542 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006543
Eric Laurentb0688d62018-08-14 15:49:18 -07006544 // Favor devices selected on active streams if any to report correct device in case of
6545 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006546 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006547 devices = activeDevices;
6548 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006549 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6550 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006551 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006552 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006553 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006554 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006555 }
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006556 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07006557}
6558
Dorin Drimusf2196d82022-01-03 12:11:18 +01006559// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006560status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006561 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006562 if (devices == nullptr) {
6563 return BAD_VALUE;
6564 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006565
6566 // Devices are determined in the following precedence:
6567 //
6568 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6569 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6570 //
6571 // If no such dynamic policy then
6572 // 2) Devices containing an active client using setPreferredDevice
6573 // with same strategy as the attributes.
6574 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6575 //
6576 // If no corresponding active client with setPreferredDevice then
6577 // 3) Devices associated with the strategy determined by the attributes
6578 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6579 //
6580 // See related getOutputForAttrInt().
6581
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006582 // check dynamic policies but only for primary descriptors (secondary not used for audible
6583 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006584 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006585 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Andy Hung6d23c0f2022-02-16 09:37:15 -08006586 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr /* secondaryMixes */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006587 if (status != OK) {
6588 return status;
6589 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006590
6591 DeviceVector curDevices;
6592 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6593 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6594 // as they are unaffected by device/stream volume
6595 // (per SwAudioOutputDescriptor::isFixedVolume()).
6596 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6597 ) {
6598 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6599 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6600 curDevices.add(deviceDesc);
6601 } else {
6602 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6603 // which selects setPreferredDevice if active. This means forVolume call
6604 // will take an active setPreferredDevice, if such exists.
6605
6606 curDevices = mEngine->getOutputDevicesForAttributes(
6607 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006608 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006609
6610 if (forVolume) {
6611 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6612 // for single volume control in AudioService (such relationship should exist if
6613 // SPEAKER_SAFE is present).
6614 //
6615 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6616 DeviceVector speakerSafeDevices =
6617 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6618 if (!speakerSafeDevices.isEmpty()) {
6619 curDevices.merge(
6620 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6621 curDevices.remove(speakerSafeDevices);
6622 }
6623 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006624 for (const auto& device : curDevices) {
6625 devices->push_back(device->getDeviceTypeAddr());
6626 }
6627 return NO_ERROR;
6628}
6629
Eric Laurente0720872014-03-11 09:30:41 -07006630void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006631 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006632 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006633 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006634 updateDevicesAndOutputs();
6635 break;
6636 default:
6637 break;
6638 }
6639}
6640
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006641uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006642
6643 // skip beacon mute management if a dedicated TTS output is available
6644 if (mTtsOutputAvailable) {
6645 return 0;
6646 }
6647
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006648 switch(event) {
6649 case STARTING_OUTPUT:
6650 mBeaconMuteRefCount++;
6651 break;
6652 case STOPPING_OUTPUT:
6653 if (mBeaconMuteRefCount > 0) {
6654 mBeaconMuteRefCount--;
6655 }
6656 break;
6657 case STARTING_BEACON:
6658 mBeaconPlayingRefCount++;
6659 break;
6660 case STOPPING_BEACON:
6661 if (mBeaconPlayingRefCount > 0) {
6662 mBeaconPlayingRefCount--;
6663 }
6664 break;
6665 }
6666
6667 if (mBeaconMuteRefCount > 0) {
6668 // any playback causes beacon to be muted
6669 return setBeaconMute(true);
6670 } else {
6671 // no other playback: unmute when beacon starts playing, mute when it stops
6672 return setBeaconMute(mBeaconPlayingRefCount == 0);
6673 }
6674}
6675
6676uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6677 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6678 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6679 // keep track of muted state to avoid repeating mute/unmute operations
6680 if (mBeaconMuted != mute) {
6681 // mute/unmute AUDIO_STREAM_TTS on all outputs
6682 ALOGV("\t muting %d", mute);
6683 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006684 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6685 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6686 ALOGV("\t no tts volume source available");
6687 return 0;
6688 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006689 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006690 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006691 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006692 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006693 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006694 maxLatency = latency;
6695 }
6696 }
6697 mBeaconMuted = mute;
6698 return maxLatency;
6699 }
6700 return 0;
6701}
6702
Eric Laurente0720872014-03-11 09:30:41 -07006703void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006704{
François Gaffiec005e562018-11-06 15:04:49 +01006705 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006706 mPreviousOutputs = mOutputs;
6707}
6708
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006709uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006710 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006711 uint32_t delayMs)
6712{
6713 // mute/unmute strategies using an incompatible device combination
6714 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6715 // if unmuting, unmute only after the specified delay
6716 if (outputDesc->isDuplicated()) {
6717 return 0;
6718 }
6719
6720 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006721 DeviceVector devices = outputDesc->devices();
6722 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006723
François Gaffiec005e562018-11-06 15:04:49 +01006724 auto productStrategies = mEngine->getOrderedProductStrategies();
6725 for (const auto &productStrategy : productStrategies) {
6726 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6727 DeviceVector curDevices =
6728 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6729 curDevices = curDevices.filter(outputDesc->supportedDevices());
6730 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006731 bool doMute = false;
6732
François Gaffiec005e562018-11-06 15:04:49 +01006733 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006734 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006735 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6736 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006737 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006738 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006739 }
Eric Laurent99401132014-05-07 19:48:15 -07006740 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006741 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006742 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006743 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006744 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006745 continue;
6746 }
François Gaffiec005e562018-11-06 15:04:49 +01006747 ALOGVV("%s() %s (curDevice %s)", __func__,
6748 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6749 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6750 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006751 if (mute) {
6752 // FIXME: should not need to double latency if volume could be applied
6753 // immediately by the audioflinger mixer. We must account for the delay
6754 // between now and the next time the audioflinger thread for this output
6755 // will process a buffer (which corresponds to one buffer size,
6756 // usually 1/2 or 1/4 of the latency).
6757 if (muteWaitMs < desc->latency() * 2) {
6758 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006759 }
6760 }
6761 }
6762 }
6763 }
6764 }
6765
Eric Laurent99401132014-05-07 19:48:15 -07006766 // temporary mute output if device selection changes to avoid volume bursts due to
6767 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006768 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006769 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006770
Eric Laurentdc462862016-07-19 12:29:53 -07006771 if (muteWaitMs < tempMuteWaitMs) {
6772 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006773 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006774
6775 // If recommended duration is defined, replace temporary mute duration to avoid
6776 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6777 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6778 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6779 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6780 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6781
François Gaffieaaac0fd2018-11-22 17:56:39 +01006782 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6783 // make sure that we do not start the temporary mute period too early in case of
6784 // delayed device change
6785 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6786 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006787 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006788 }
6789 }
6790
Eric Laurente552edb2014-03-10 17:42:56 -07006791 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6792 if (muteWaitMs > delayMs) {
6793 muteWaitMs -= delayMs;
6794 usleep(muteWaitMs * 1000);
6795 return muteWaitMs;
6796 }
6797 return 0;
6798}
6799
François Gaffie11d30102018-11-02 16:09:09 +01006800uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6801 const DeviceVector &devices,
6802 bool force,
6803 int delayMs,
6804 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006805 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006806{
François Gaffie11d30102018-11-02 16:09:09 +01006807 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006808 uint32_t muteWaitMs;
6809
6810 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006811 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6812 nullptr /* patchHandle */, requiresMuteCheck);
6813 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6814 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006815 return muteWaitMs;
6816 }
Eric Laurente552edb2014-03-10 17:42:56 -07006817
6818 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006819 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006820 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006821 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006822
François Gaffie11d30102018-11-02 16:09:09 +01006823 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6824
6825 if (!filteredDevices.isEmpty()) {
6826 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006827 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006828
6829 // if the outputs are not materially active, there is no need to mute.
6830 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006831 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006832 } else {
6833 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6834 muteWaitMs = 0;
6835 }
Eric Laurente552edb2014-03-10 17:42:56 -07006836
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006837 bool outputRouted = outputDesc->isRouted();
6838
Eric Laurent79ea9582020-06-11 18:49:24 -07006839 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6840 // output profile or if new device is not supported AND previous device(s) is(are) still
6841 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006842 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006843 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6844 // restore previous device after evaluating strategy mute state
6845 outputDesc->setDevices(prevDevices);
6846 return muteWaitMs;
6847 }
6848
Eric Laurente552edb2014-03-10 17:42:56 -07006849 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006850 // the requested device is AUDIO_DEVICE_NONE
6851 // OR the requested device is the same as current device
6852 // AND force is not specified
6853 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006854 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006855 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01006856 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6857 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006858 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6859 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6860 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6861 }
Eric Laurente552edb2014-03-10 17:42:56 -07006862 return muteWaitMs;
6863 }
6864
François Gaffie11d30102018-11-02 16:09:09 +01006865 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006866
Eric Laurente552edb2014-03-10 17:42:56 -07006867 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006868 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006869 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006870 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006871 PatchBuilder patchBuilder;
6872 patchBuilder.addSource(outputDesc);
6873 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6874 for (const auto &filteredDevice : filteredDevices) {
6875 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006876 }
6877
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006878 // Add half reported latency to delayMs when muteWaitMs is null in order
6879 // to avoid disordered sequence of muting volume and changing devices.
6880 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6881 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006882 }
Eric Laurente552edb2014-03-10 17:42:56 -07006883
6884 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006885 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006886
6887 return muteWaitMs;
6888}
6889
Eric Laurentc75307b2015-03-17 15:29:32 -07006890status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006891 int delayMs,
6892 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006893{
Eric Laurent6a94d692014-05-20 11:18:06 -07006894 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006895 if (patchHandle == nullptr && !outputDesc->isRouted()) {
6896 return INVALID_OPERATION;
6897 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006898 if (patchHandle) {
6899 index = mAudioPatches.indexOfKey(*patchHandle);
6900 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006901 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006902 }
6903 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006904 return INVALID_OPERATION;
6905 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006906 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006907 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006908 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006909 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006910 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006911 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006912 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006913 return status;
6914}
6915
6916status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006917 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006918 bool force,
6919 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006920{
6921 status_t status = NO_ERROR;
6922
Eric Laurent1f2f2232014-06-02 12:01:23 -07006923 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006924 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6925 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006926
François Gaffie11d30102018-11-02 16:09:09 +01006927 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006928 PatchBuilder patchBuilder;
6929 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006930 // AUDIO_SOURCE_HOTWORD is for internal use only:
6931 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006932 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6933 auto result = usecase;
6934 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6935 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6936 }
6937 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006938 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006939 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006940 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006941 }
6942 }
6943 return status;
6944}
6945
Eric Laurent6a94d692014-05-20 11:18:06 -07006946status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6947 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006948{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006949 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006950 ssize_t index;
6951 if (patchHandle) {
6952 index = mAudioPatches.indexOfKey(*patchHandle);
6953 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006954 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006955 }
6956 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006957 return INVALID_OPERATION;
6958 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006959 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006960 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006961 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006962 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006963 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006964 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006965 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006966 return status;
6967}
6968
François Gaffie11d30102018-11-02 16:09:09 +01006969sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006970 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006971 audio_format_t& format,
6972 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006973 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006974{
6975 // Choose an input profile based on the requested capture parameters: select the first available
6976 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006977 //
6978 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6979 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006980
Glenn Kasten730b9262018-03-29 15:01:26 -07006981 sp<IOProfile> firstInexact;
6982 uint32_t updatedSamplingRate = 0;
6983 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6984 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006985 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006986 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006987 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006988 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006989 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006990 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006991 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006992 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006993 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006994 &channelMask /*updatedChannelMask*/,
6995 // FIXME ugly cast
6996 (audio_output_flags_t) flags,
6997 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006998 return profile;
6999 }
François Gaffie11d30102018-11-02 16:09:09 +01007000 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007001 samplingRate,
7002 &updatedSamplingRate,
7003 format,
7004 &updatedFormat,
7005 channelMask,
7006 &updatedChannelMask,
7007 // FIXME ugly cast
7008 (audio_output_flags_t) flags,
7009 false /*exactMatchRequiredForInputFlags*/)) {
7010 firstInexact = profile;
7011 }
7012
Eric Laurente552edb2014-03-10 17:42:56 -07007013 }
7014 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007015 if (firstInexact != nullptr) {
7016 samplingRate = updatedSamplingRate;
7017 format = updatedFormat;
7018 channelMask = updatedChannelMask;
7019 return firstInexact;
7020 }
Eric Laurente552edb2014-03-10 17:42:56 -07007021 return NULL;
7022}
7023
François Gaffieaaac0fd2018-11-22 17:56:39 +01007024float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7025 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007026 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007027 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007028{
jiabin9a3361e2019-10-01 09:38:30 -07007029 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007030
7031 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7032 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7033 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7034 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007035 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7036 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7037 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7038 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7039 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007040
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007041 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007042 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7043 mOutputs.isActive(ringVolumeSrc, 0)) {
7044 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007045 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007046 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007047 }
7048
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007049 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007050 if ((volumeSource != callVolumeSrc && (isInCall() ||
7051 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007052 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007053 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7054 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007055 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7056 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7057 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007058 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007059 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007060 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007061 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007062 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007063 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007064 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7065 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7066 // programmatically muted.
7067 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7068 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7069 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007070 bool exemptFromCapping =
7071 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7072 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007073 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7074 volumeSource, volumeDb);
7075 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007076 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7077 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7078 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007079 }
7080 }
Eric Laurente552edb2014-03-10 17:42:56 -07007081 // if a headset is connected, apply the following rules to ring tones and notifications
7082 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007083 // - always attenuate notifications volume by 6dB
7084 // - attenuate ring tones volume by 6dB unless music is not playing and
7085 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007086 // - if music is playing, always limit the volume to current music volume,
7087 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007088 if (!Intersection(deviceTypes,
7089 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7090 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007091 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7092 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007093 ((volumeSource == alarmVolumeSrc ||
7094 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007095 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7096 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7097 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007098 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7099 curves.canBeMuted()) {
7100
Eric Laurente552edb2014-03-10 17:42:56 -07007101 // when the phone is ringing we must consider that music could have been paused just before
7102 // by the music application and behave as if music was active if the last music track was
7103 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007104 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007105 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007106 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007107 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007108 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7109 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007110 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007111 float musicVolDb = computeVolume(musicCurves,
7112 musicVolumeSrc,
7113 musicCurves.getVolumeIndex(musicDevice),
7114 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007115 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7116 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7117 if (volumeDb > minVolDb) {
7118 volumeDb = minVolDb;
7119 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007120 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007121 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7122 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7123 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007124 // on A2DP, also ensure notification volume is not too low compared to media when
7125 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007126 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007127 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007128 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7129 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007130 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7131 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007132 }
7133 }
jiabin9a3361e2019-10-01 09:38:30 -07007134 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007135 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007136 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007137 }
7138 }
7139
François Gaffie43c73442018-11-08 08:21:55 +01007140 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007141}
7142
Eric Laurent3839bc02018-07-10 18:33:34 -07007143int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007144 VolumeSource fromVolumeSource,
7145 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007146{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007147 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007148 return srcIndex;
7149 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007150 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7151 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007152 float minSrc = (float)srcCurves.getVolumeIndexMin();
7153 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7154 float minDst = (float)dstCurves.getVolumeIndexMin();
7155 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007156
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007157 // preserve mute request or correct range
7158 if (srcIndex < minSrc) {
7159 if (srcIndex == 0) {
7160 return 0;
7161 }
7162 srcIndex = minSrc;
7163 } else if (srcIndex > maxSrc) {
7164 srcIndex = maxSrc;
7165 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007166 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7167}
7168
François Gaffieaaac0fd2018-11-22 17:56:39 +01007169status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7170 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007171 int index,
7172 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007173 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007174 int delayMs,
7175 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007176{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007177 // do not change actual attributes volume if the attributes is muted
7178 if (outputDesc->isMuted(volumeSource)) {
7179 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7180 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007181 return NO_ERROR;
7182 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007183 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7184 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7185 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7186 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007187
Eric Laurent2517af32020-11-25 15:31:27 +01007188 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07007189 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007190 // if sco and call follow same curves, bypass forceUseForComm
7191 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007192 ((isVoiceVolSrc && isScoRequested) ||
7193 (isBtScoVolSrc && !isScoRequested))) {
7194 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
7195 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07007196 // Do not return an error here as AudioService will always set both voice call
7197 // and bluetooth SCO volumes due to stream aliasing.
7198 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007199 }
jiabin9a3361e2019-10-01 09:38:30 -07007200 if (deviceTypes.empty()) {
7201 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007202 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007203
jiabin9a3361e2019-10-01 09:38:30 -07007204 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7205 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007206 // Force VoIP volume to max for bluetooth SCO device except if muted
7207 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007208 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007209 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007210 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007211 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007212 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007213 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007214
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007215 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007216 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007217 // 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 +01007218 if (isVoiceVolSrc) {
7219 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007220 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007221 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007222 }
Eric Laurent18fba842016-03-31 14:41:26 -07007223 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007224 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7225 mLastVoiceVolume = voiceVolume;
7226 }
7227 }
Eric Laurente552edb2014-03-10 17:42:56 -07007228 return NO_ERROR;
7229}
7230
Eric Laurentc75307b2015-03-17 15:29:32 -07007231void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007232 const DeviceTypeSet& deviceTypes,
7233 int delayMs,
7234 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007235{
jiabincd510522020-01-22 09:40:55 -08007236 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007237 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7238 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7239 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007240 curves.getVolumeIndex(deviceTypes),
7241 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007242 }
7243}
7244
François Gaffiec005e562018-11-06 15:04:49 +01007245void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7246 bool on,
7247 const sp<AudioOutputDescriptor>& outputDesc,
7248 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007249 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007250{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007251 std::vector<VolumeSource> sourcesToMute;
7252 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7253 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7254 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007255 VolumeSource source = toVolumeSource(attributes, false);
7256 if ((source != VOLUME_SOURCE_NONE) &&
7257 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7258 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007259 sourcesToMute.push_back(source);
7260 }
Eric Laurente552edb2014-03-10 17:42:56 -07007261 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007262 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007263 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007264 }
7265
Eric Laurente552edb2014-03-10 17:42:56 -07007266}
7267
François Gaffieaaac0fd2018-11-22 17:56:39 +01007268void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7269 bool on,
7270 const sp<AudioOutputDescriptor>& outputDesc,
7271 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007272 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007273{
jiabin9a3361e2019-10-01 09:38:30 -07007274 if (deviceTypes.empty()) {
7275 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007276 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007277 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007278 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007279 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007280 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007281 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007282 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7283 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007284 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007285 }
7286 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007287 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7288 // ignored
7289 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007290 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007291 if (!outputDesc->isMuted(volumeSource)) {
7292 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007293 return;
7294 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007295 if (outputDesc->decMuteCount(volumeSource) == 0) {
7296 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007297 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007298 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007299 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007300 delayMs);
7301 }
7302 }
7303}
7304
François Gaffie53615e22015-03-19 09:24:12 +01007305bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7306{
François Gaffiec005e562018-11-06 15:04:49 +01007307 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007308 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7309 return true;
7310 }
7311
7312 // has known usage?
7313 switch (paa->usage) {
7314 case AUDIO_USAGE_UNKNOWN:
7315 case AUDIO_USAGE_MEDIA:
7316 case AUDIO_USAGE_VOICE_COMMUNICATION:
7317 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7318 case AUDIO_USAGE_ALARM:
7319 case AUDIO_USAGE_NOTIFICATION:
7320 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7321 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7322 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7323 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7324 case AUDIO_USAGE_NOTIFICATION_EVENT:
7325 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7326 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7327 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7328 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007329 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007330 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007331 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007332 case AUDIO_USAGE_EMERGENCY:
7333 case AUDIO_USAGE_SAFETY:
7334 case AUDIO_USAGE_VEHICLE_STATUS:
7335 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007336 break;
7337 default:
7338 return false;
7339 }
7340 return true;
7341}
7342
François Gaffie2110e042015-03-24 08:41:51 +01007343audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7344{
7345 return mEngine->getForceUse(usage);
7346}
7347
7348bool AudioPolicyManager::isInCall()
7349{
7350 return isStateInCall(mEngine->getPhoneState());
7351}
7352
7353bool AudioPolicyManager::isStateInCall(int state)
7354{
7355 return is_state_in_call(state);
7356}
7357
Eric Laurent74b71512019-11-06 17:21:57 -08007358bool AudioPolicyManager::isCallAudioAccessible()
7359{
7360 audio_mode_t mode = mEngine->getPhoneState();
7361 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007362 || (mode == AUDIO_MODE_CALL_SCREEN)
7363 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007364}
7365
Eric Laurentd60560a2015-04-10 11:31:20 -07007366void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7367{
7368 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007369 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007370 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007371 sourceDesc->sinkDevice()->equals(deviceDesc))
7372 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007373 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007374 }
7375 }
7376
7377 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7378 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7379 bool release = false;
7380 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7381 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7382 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7383 source->ext.device.type == deviceDesc->type()) {
7384 release = true;
7385 }
7386 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007387 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007388 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7389 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7390 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007391 sink->ext.device.type == deviceDesc->type() &&
7392 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7393 || strncmp(sink->ext.device.address, address,
7394 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007395 release = true;
7396 }
7397 }
7398 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007399 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7400 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007401 }
7402 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007403
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007404 mInputs.clearSessionRoutesForDevice(deviceDesc);
7405
Francois Gaffie716e1432019-01-14 16:58:59 +01007406 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007407}
7408
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007409void AudioPolicyManager::modifySurroundFormats(
7410 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007411 std::unordered_set<audio_format_t> enforcedSurround(
7412 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007413 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7414 for (const auto& pair : mConfig.getSurroundFormats()) {
7415 allSurround.insert(pair.first);
7416 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7417 }
Phil Burk09bc4612016-02-24 15:58:15 -08007418
7419 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7420 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007421 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007422 // This is the resulting set of formats depending on the surround mode:
7423 // 'all surround' = allSurround
7424 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7425 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7426 // 'manual surround' = mManualSurroundFormats
7427 // AUTO: formats v 'enforced surround'
7428 // ALWAYS: formats v 'all surround' v 'enforced surround'
7429 // NEVER: formats ^ 'non-surround'
7430 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007431
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007432 std::unordered_set<audio_format_t> formatSet;
7433 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7434 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007435 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007436 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007437 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007438 formatSet.insert(*formatIter);
7439 }
7440 }
7441 } else {
7442 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7443 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007444 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007445
jiabin81772902018-04-02 17:52:27 -07007446 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007447 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007448 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7449 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7450 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007451 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007452 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7453 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7454 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007455 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007456 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007457 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007458 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007459 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007460 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007461}
7462
jiabin06e4bab2019-07-29 10:13:34 -07007463void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7464 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007465 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7466 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7467
7468 // If NEVER, then remove support for channelMasks > stereo.
7469 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007470 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7471 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007472 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007473 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007474 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007475 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007476 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007477 }
7478 }
jiabin81772902018-04-02 17:52:27 -07007479 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7480 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7481 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007482 bool supports5dot1 = false;
7483 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007484 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007485 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7486 supports5dot1 = true;
7487 break;
7488 }
7489 }
7490 // If not then add 5.1 support.
7491 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007492 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007493 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007494 }
Phil Burk09bc4612016-02-24 15:58:15 -08007495 }
7496}
7497
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007498void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007499 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007500 AudioProfileVector &profiles)
7501{
7502 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007503 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007504
François Gaffie112b0af2015-11-19 16:13:25 +01007505 // Format MUST be checked first to update the list of AudioProfile
7506 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007507 reply = mpClientInterface->getParameters(
7508 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007509 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007510 AudioParameter repliedParameters(reply);
7511 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007512 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007513 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7514 return;
7515 }
Phil Burk09bc4612016-02-24 15:58:15 -08007516 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007517 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007518 if (device == AUDIO_DEVICE_OUT_HDMI
7519 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007520 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007521 }
jiabin3e277cc2019-09-10 14:27:34 -07007522 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007523 }
François Gaffie112b0af2015-11-19 16:13:25 +01007524
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007525 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007526 ChannelMaskSet channelMasks;
7527 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007528 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007529 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007530
7531 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007532 reply = mpClientInterface->getParameters(
7533 ioHandle,
7534 requestedParameters.toString() + ";" +
7535 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007536 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007537 AudioParameter repliedParameters(reply);
7538 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007539 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007540 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007541 }
7542 }
7543 if (profiles.hasDynamicChannelsFor(format)) {
7544 reply = mpClientInterface->getParameters(ioHandle,
7545 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007546 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007547 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007548 AudioParameter repliedParameters(reply);
7549 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007550 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007551 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007552 if (device == AUDIO_DEVICE_OUT_HDMI
7553 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007554 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007555 }
François Gaffie112b0af2015-11-19 16:13:25 +01007556 }
7557 }
jiabin3e277cc2019-09-10 14:27:34 -07007558 addDynamicAudioProfileAndSort(
7559 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007560 }
7561}
Eric Laurentd60560a2015-04-10 11:31:20 -07007562
Mikhail Naganovdc769682018-05-04 15:34:08 -07007563status_t AudioPolicyManager::installPatch(const char *caller,
7564 audio_patch_handle_t *patchHandle,
7565 AudioIODescriptorInterface *ioDescriptor,
7566 const struct audio_patch *patch,
7567 int delayMs)
7568{
7569 ssize_t index = mAudioPatches.indexOfKey(
7570 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7571 *patchHandle : ioDescriptor->getPatchHandle());
7572 sp<AudioPatch> patchDesc;
7573 status_t status = installPatch(
7574 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7575 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007576 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007577 }
7578 return status;
7579}
7580
7581status_t AudioPolicyManager::installPatch(const char *caller,
7582 ssize_t index,
7583 audio_patch_handle_t *patchHandle,
7584 const struct audio_patch *patch,
7585 int delayMs,
7586 uid_t uid,
7587 sp<AudioPatch> *patchDescPtr)
7588{
7589 sp<AudioPatch> patchDesc;
7590 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7591 if (index >= 0) {
7592 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007593 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007594 }
7595
7596 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7597 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7598 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7599 if (status == NO_ERROR) {
7600 if (index < 0) {
7601 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007602 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007603 } else {
7604 patchDesc->mPatch = *patch;
7605 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007606 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007607 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007608 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007609 }
7610 nextAudioPortGeneration();
7611 mpClientInterface->onAudioPatchListUpdate();
7612 }
7613 if (patchDescPtr) *patchDescPtr = patchDesc;
7614 return status;
7615}
7616
jiabinbce0c1d2020-10-05 11:20:18 -07007617bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7618{
7619 const TrackClientVector activeClients = output->getActiveClients();
7620 if (activeClients.empty()) {
7621 return true;
7622 }
7623 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7624 if (index < 0) {
7625 ALOGE("%s, no audio patch found while there are active clients on output %d",
7626 __func__, output->getId());
7627 return false;
7628 }
7629 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7630 DeviceVector routedDevices;
7631 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7632 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7633 patchDesc->mPatch.sinks[i].id);
7634 if (device == nullptr) {
7635 ALOGE("%s, no audio device found with id(%d)",
7636 __func__, patchDesc->mPatch.sinks[i].id);
7637 return false;
7638 }
7639 routedDevices.add(device);
7640 }
7641 for (const auto& client : activeClients) {
7642 // TODO: b/175343099 only travel the valid client
7643 sp<DeviceDescriptor> preferredDevice =
7644 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7645 if (mEngine->getOutputDevicesForAttributes(
7646 client->attributes(), preferredDevice, false) == routedDevices) {
7647 return false;
7648 }
7649 }
7650 return true;
7651}
7652
7653sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007654 const sp<IOProfile>& profile, const DeviceVector& devices,
7655 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007656{
7657 for (const auto& device : devices) {
7658 // TODO: This should be checking if the profile supports the device combo.
7659 if (!profile->supportsDevice(device)) {
7660 return nullptr;
7661 }
7662 }
7663 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7664 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007665 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007666 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7667 if (status != NO_ERROR) {
7668 return nullptr;
7669 }
7670
7671 // Here is where the out_set_parameters() for card & device gets called
7672 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7673 const audio_devices_t deviceType = device->type();
7674 const String8 &address = String8(device->address().c_str());
7675 if (!address.isEmpty()) {
7676 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7677 mpClientInterface->setParameters(output, String8(param));
7678 free(param);
7679 }
7680 updateAudioProfiles(device, output, profile->getAudioProfiles());
7681 if (!profile->hasValidAudioProfile()) {
7682 ALOGW("%s() missing param", __func__);
7683 desc->close();
7684 return nullptr;
7685 } else if (profile->hasDynamicAudioProfile()) {
7686 desc->close();
7687 output = AUDIO_IO_HANDLE_NONE;
7688 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7689 profile->pickAudioProfile(
7690 config.sample_rate, config.channel_mask, config.format);
7691 config.offload_info.sample_rate = config.sample_rate;
7692 config.offload_info.channel_mask = config.channel_mask;
7693 config.offload_info.format = config.format;
7694
Eric Laurentb4f42a92022-01-17 17:37:31 +01007695 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007696 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7697 if (status != NO_ERROR) {
7698 return nullptr;
7699 }
7700 }
7701
7702 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007703
jiabinbce0c1d2020-10-05 11:20:18 -07007704 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7705 sp<AudioPolicyMix> policyMix;
7706 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7707 policyMix->setOutput(desc);
7708 desc->mPolicyMix = policyMix;
7709 } else {
7710 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7711 address.string());
7712 }
7713
Eric Laurentb4f42a92022-01-17 17:37:31 +01007714 } else if (hasPrimaryOutput() && profile->getModule()
7715 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7716 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7717 // no duplicated output for:
7718 // - direct outputs
7719 // - outputs used by dynamic policy mixes
7720 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007721 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7722
7723 //TODO: configure audio effect output stage here
7724
7725 // open a duplicating output thread for the new output and the primary output
7726 sp<SwAudioOutputDescriptor> dupOutputDesc =
7727 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7728 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7729 if (status == NO_ERROR) {
7730 // add duplicated output descriptor
7731 addOutput(duplicatedOutput, dupOutputDesc);
7732 } else {
7733 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7734 mPrimaryOutput->mIoHandle, output);
7735 desc->close();
7736 removeOutput(output);
7737 nextAudioPortGeneration();
7738 return nullptr;
7739 }
7740 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007741 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7742 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7743 mPrimaryOutput = desc;
7744 }
jiabinbce0c1d2020-10-05 11:20:18 -07007745 return desc;
7746}
7747
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007748} // namespace android