blob: 57205516880539ddef3f54c1165f8191804a99f5 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080037#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110038#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070039
40#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010041#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070042#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070044#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070045#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070046#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070047#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070048#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070049#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <utils/Log.h>
51
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010053#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010057using android::media::audio::common::AudioDevice;
58using android::media::audio::common::AudioDeviceAddress;
59using android::media::audio::common::AudioPortDeviceExt;
60using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000061using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070062
Eric Laurentdc462862016-07-19 12:29:53 -070063//FIXME: workaround for truncated touch sounds
64// to be removed when the problem is handled by system UI
65#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070066
67// Largest difference in dB on earpiece in call between the voice volume and another
68// media / notification / system volume.
69constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
70
Mikhail Naganov15be9d22017-11-08 14:18:13 +110071// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110072static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
73 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110074 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
75// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110076static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110077 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
78 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
79 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
80
jiabin06e4bab2019-07-29 10:13:34 -070081template <typename T>
82bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
83{
84 if (left.size() != right.size()) {
85 return false;
86 }
87 for (size_t index = 0; index < right.size(); index++) {
88 if (left[index] != right[index]) {
89 return false;
90 }
91 }
92 return true;
93}
94
95template <typename T>
96bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
97{
98 return !(left == right);
99}
100
Eric Laurente552edb2014-03-10 17:42:56 -0700101// ----------------------------------------------------------------------------
102// AudioPolicyInterface implementation
103// ----------------------------------------------------------------------------
104
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100105status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
106 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
107 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800108 nextAudioPortGeneration();
109 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110}
111
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100112status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
113 audio_policy_dev_state_t state,
114 const char* device_address,
115 const char* device_name,
116 audio_format_t encodedFormat) {
117 media::AudioPort aidlPort;
118 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
119 status == OK) {
120 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
121 } else {
122 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
123 return status;
124 }
125}
126
François Gaffie11d30102018-11-02 16:09:09 +0100127void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
128 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200129{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000130 audio_port_v7 devicePort;
131 device->toAudioPort(&devicePort);
132 if (status_t status = mpClientInterface->setDeviceConnectedState(
133 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
134 status != OK) {
135 ALOGE("Error %d while setting connected state for device %s", status,
136 device->getDeviceTypeAddr().toString(false).c_str());
137 }
François Gaffie44481e72016-04-20 07:49:57 +0200138}
139
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100140status_t AudioPolicyManager::setDeviceConnectionStateInt(
141 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
142 audio_format_t encodedFormat) {
143 // TODO: b/211601178 Forward 'port' to Audio HAL via mHwModules. For now, only device_type,
144 // device_address and device_name are forwarded.
145 if (port.ext.getTag() != AudioPortExt::device) {
146 return BAD_VALUE;
147 }
148 audio_devices_t device_type;
149 std::string device_address;
150 if (status_t status = aidl2legacy_AudioDevice_audio_device(
151 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
152 status != OK) {
153 return status;
154 };
155 const char* device_name = port.name.c_str();
156 // connect/disconnect only 1 device at a time
157 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
158 return BAD_VALUE;
159
160 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
161 device_type, device_address.c_str(), device_name, encodedFormat,
162 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
163 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
164}
165
François Gaffie11d30102018-11-02 16:09:09 +0100166status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800167 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100168 const char* device_address,
169 const char* device_name,
170 audio_format_t encodedFormat) {
171 media::AudioPort aidlPort;
172 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
173 status == OK) {
174 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
175 } else {
176 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
177 return status;
178 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179}
Paul McLeane743a472015-01-28 11:07:31 -0800180
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
182 audio_policy_dev_state_t state)
183{
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700185 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700186 SortedVector <audio_io_handle_t> outputs;
187
François Gaffie11d30102018-11-02 16:09:09 +0100188 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 // save a copy of the opened output descriptors before any output is opened or closed
191 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
192 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700193 switch (state)
194 {
195 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800196 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700197 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100198 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700199 return INVALID_OPERATION;
200 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800201 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700202 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Eric Laurente552edb2014-03-10 17:42:56 -0700204 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200205 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700206 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700207 }
208
François Gaffie44481e72016-04-20 07:49:57 +0200209 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
210 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100211 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200212
François Gaffie11d30102018-11-02 16:09:09 +0100213 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
214 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200215
Francois Gaffie716e1432019-01-14 16:58:59 +0100216 mHwModules.cleanUpForDevice(device);
217
François Gaffie11d30102018-11-02 16:09:09 +0100218 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700219 return INVALID_OPERATION;
220 }
François Gaffie2110e042015-03-24 08:41:51 +0100221
jiabin1c4794b2020-05-05 10:08:05 -0700222 // Populate encapsulation information when a output device is connected.
223 device->setEncapsulationInfoFromHal(mpClientInterface);
224
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700225 // outputs should never be empty here
226 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
227 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100228 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800229
Eric Laurent3ae5f312015-02-03 17:12:08 -0800230 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700231 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700232 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700235 return INVALID_OPERATION;
236 }
237
François Gaffie11d30102018-11-02 16:09:09 +0100238 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700239
Paul McLeane743a472015-01-28 11:07:31 -0800240 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100241 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700242
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100244 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700245
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100246 mOutputs.clearSessionRoutesForDevice(device);
247
François Gaffie11d30102018-11-02 16:09:09 +0100248 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100249
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800250 // Reset active device codec
251 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
252
Kriti Dangef6be8f2020-11-05 11:58:19 +0100253 // remove device from mReportedFormatsMap cache
254 mReportedFormatsMap.erase(device);
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 } break;
257
258 default:
François Gaffie11d30102018-11-02 16:09:09 +0100259 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700260 return BAD_VALUE;
261 }
262
Eric Laurent736a1022019-03-27 18:28:46 -0700263 // Propagate device availability to Engine
264 setEngineDeviceConnectionState(device, state);
265
Eric Laurentae970022019-01-29 14:25:04 -0800266 // No need to evaluate playback routing when connecting a remote submix
267 // output device used by a dynamic policy of type recorder as no
268 // playback use case is affected.
269 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700270 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800271 for (audio_io_handle_t output : outputs) {
272 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800273 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
274 if (policyMix != nullptr
275 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700276 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800277 doCheckForDeviceAndOutputChanges = false;
278 break;
279 }
280 }
281 }
282
283 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700284 // outputs must be closed after checkOutputForAllStrategies() is executed
285 if (!outputs.isEmpty()) {
286 for (audio_io_handle_t output : outputs) {
287 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100288 // close unused outputs after device disconnection or direct outputs that have
289 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200290 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
291 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurent39095982021-08-24 18:29:27 +0200292 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200293 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700294 closeOutput(output);
295 }
Eric Laurente552edb2014-03-10 17:42:56 -0700296 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
298 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800301 };
302
303 if (doCheckForDeviceAndOutputChanges) {
304 checkForDeviceAndOutputChanges(checkCloseOutputs);
305 } else {
306 checkCloseOutputs();
307 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100308 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700309 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100310 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700311 const DeviceVector activeMediaDevices =
312 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700313 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700314 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530315 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
316 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100317 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700318 // do not force device change on duplicated output because if device is 0, it will
319 // also force a device 0 for the two outputs it is duplicated to which may override
320 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100321 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100322 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700323 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 // always force when disconnecting (a non-duplicated device)
325 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100326 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 }
jiabinbce0c1d2020-10-05 11:20:18 -0700328 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000329 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700330 desc->supportsDevicesForPlayback(activeMediaDevices)) {
331 // Reopen the output to query the dynamic profiles when there is not active
332 // clients or all active clients will be rerouted. Otherwise, set the flag
333 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
334 // can be reopened to query dynamic profiles when all clients are inactive.
335 if (areAllActiveTracksRerouted(desc)) {
336 outputsToReopen.push_back(mOutputs.keyAt(i));
337 } else {
338 desc->mPendingReopenToQueryProfiles = true;
339 }
340 }
341 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
342 // Clear the flag that previously set for re-querying profiles.
343 desc->mPendingReopenToQueryProfiles = false;
344 }
345 }
346 for (const auto& output : outputsToReopen) {
347 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
348 closeOutput(output);
349 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700350 }
351
Eric Laurentd60560a2015-04-10 11:31:20 -0700352 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100353 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700354 }
355
Eric Laurent72aa32f2014-05-30 18:51:48 -0700356 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700357 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700358 } // end if is output device
359
Eric Laurente552edb2014-03-10 17:42:56 -0700360 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700361 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100362 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700363 switch (state)
364 {
365 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700366 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100368 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700369 return INVALID_OPERATION;
370 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700371
372 if (mAvailableInputDevices.add(device) < 0) {
373 return NO_MEMORY;
374 }
375
François Gaffie44481e72016-04-20 07:49:57 +0200376 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
377 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100378 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200379
Eric Laurent0dd51852019-04-19 18:18:58 -0700380 if (checkInputsForDevice(device, state) != NO_ERROR) {
381 mAvailableInputDevices.remove(device);
382
François Gaffie11d30102018-11-02 16:09:09 +0100383 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100384
385 mHwModules.cleanUpForDevice(device);
386
Eric Laurentd4692962014-05-05 18:13:44 -0700387 return INVALID_OPERATION;
388 }
389
Eric Laurentd4692962014-05-05 18:13:44 -0700390 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700391
392 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700393 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700394 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700396 return INVALID_OPERATION;
397 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700398
François Gaffie11d30102018-11-02 16:09:09 +0100399 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700400
401 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100402 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700403
François Gaffie11d30102018-11-02 16:09:09 +0100404 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700405
406 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100407
408 // remove device from mReportedFormatsMap cache
409 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 default:
François Gaffie11d30102018-11-02 16:09:09 +0100413 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700414 return BAD_VALUE;
415 }
416
Eric Laurent736a1022019-03-27 18:28:46 -0700417 // Propagate device availability to Engine
418 setEngineDeviceConnectionState(device, state);
419
Eric Laurent0dd51852019-04-19 18:18:58 -0700420 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700421 // As the input device list can impact the output device selection, update
422 // getDeviceForStrategy() cache
423 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700424
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100425 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200426 // Reconnect Audio Source
427 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
428 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
429 checkAudioSourceForAttributes(attributes);
430 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700431 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100432 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700433 }
434
Eric Laurentb52c1522014-05-20 11:27:36 -0700435 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700436 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700437 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700438
François Gaffie11d30102018-11-02 16:09:09 +0100439 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700440 return BAD_VALUE;
441}
442
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100443status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
444 const char* device_name,
445 media::AudioPort* aidlPort) {
446 DeviceDescriptorBase devDescr(device, device_address);
447 devDescr.setName(device_name);
448 return devDescr.writeToParcelable(aidlPort);
449}
450
Eric Laurent736a1022019-03-27 18:28:46 -0700451void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
452 audio_policy_dev_state_t state) {
453
454 // the Engine does not have to know about remote submix devices used by dynamic audio policies
455 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
456 return;
457 }
458 mEngine->setDeviceConnectionState(device, state);
459}
460
461
Eric Laurente0720872014-03-11 09:30:41 -0700462audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100463 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700464{
Eric Laurent634b7142016-04-20 13:48:02 -0700465 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800466 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
467 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700468 (strlen(device_address) != 0)/*matchAddress*/);
469
470 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100471 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700472 device, device_address);
473 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
474 }
François Gaffie53615e22015-03-19 09:24:12 +0100475
Eric Laurent3a4311c2014-03-17 12:00:47 -0700476 DeviceVector *deviceVector;
477
Eric Laurente552edb2014-03-10 17:42:56 -0700478 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700479 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700480 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700481 deviceVector = &mAvailableInputDevices;
482 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100483 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700484 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700485 }
Eric Laurent634b7142016-04-20 13:48:02 -0700486
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800487 return (deviceVector->getDevice(
488 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700489 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800490}
491
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800492status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
493 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800494 const char *device_name,
495 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800496{
497 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700498 String8 reply;
499 AudioParameter param;
500 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800502 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
503 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800505 // connect/disconnect only 1 device at a time
506 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
507
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700509 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800511 // Nothing to do: device is not connected
512 return NO_ERROR;
513 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800514 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800515
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700516 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 // configure codecs.
518 // Handle two specific cases by sending a set parameter to
519 // configure A2DP codecs. No need to toggle device state.
520 // Case 1: A2DP active device switches from primary to primary
521 // module
522 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200523 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700524 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
526 if (availablePrimaryOutputDevices().contains(devDesc) &&
527 (module != 0 && module->getHandle() == primaryHandle)) {
528 reply = mpClientInterface->getParameters(
529 AUDIO_IO_HANDLE_NONE,
530 String8(AudioParameter::keyReconfigA2dpSupported));
531 AudioParameter repliedParameters(reply);
532 repliedParameters.getInt(
533 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
534 if (isReconfigA2dpSupported) {
535 const String8 key(AudioParameter::keyReconfigA2dp);
536 param.add(key, String8("true"));
537 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
538 devDesc->setEncodedFormat(encodedFormat);
539 return NO_ERROR;
540 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700541 }
542 }
cnx421bd2dcc42020-07-11 14:58:44 +0800543 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
544 for (size_t i = 0; i < mOutputs.size(); i++) {
545 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
546 // mute media strategies and delay device switch by the largest
547 // This avoid sending the music tail into the earpiece or headset.
548 setStrategyMute(musicStrategy, true, desc);
549 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
550 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
551 nullptr, true /*fromCache*/).types());
552 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800553 // Toggle the device state: UNAVAILABLE -> AVAILABLE
554 // This will force reading again the device configuration
555 status = setDeviceConnectionState(device,
556 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800557 device_address, device_name,
558 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800559 if (status != NO_ERROR) {
560 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
561 status);
562 return status;
563 }
564
565 status = setDeviceConnectionState(device,
566 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800567 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 if (status != NO_ERROR) {
569 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
570 status);
571 return status;
572 }
573
574 return NO_ERROR;
575}
576
Pattydd807582021-11-04 21:01:03 +0800577status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
578 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800579{
Pattydd807582021-11-04 21:01:03 +0800580 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800581 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800582 std::unordered_set<audio_format_t> formatSet;
583 sp<HwModule> primaryModule =
584 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700585 if (primaryModule == nullptr) {
586 ALOGE("%s() unable to get primary module", __func__);
587 return NO_INIT;
588 }
Pattydd807582021-11-04 21:01:03 +0800589
590 DeviceTypeSet audioDeviceSet;
591
592 switch(device) {
593 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
594 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
595 break;
596 case AUDIO_DEVICE_OUT_BLE_HEADSET:
597 audioDeviceSet = getAudioDeviceOutAllBleSet();
598 break;
599 default:
600 ALOGE("%s() device type 0x%08x not supported", __func__, device);
601 return BAD_VALUE;
602 }
603
jiabin9a3361e2019-10-01 09:38:30 -0700604 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800605 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800606 for (const auto& device : declaredDevices) {
607 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800608 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800609 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800610 return status;
611}
612
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100613DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
614{
615 DeviceVector rxSinkdevices{};
616 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
617 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
618 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
619 auto rxSinkDevice = rxSinkdevices.itemAt(0);
620 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
621 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
622 // retrieve Rx Source device descriptor
623 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
624 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
625
626 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
627 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
628 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
629 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
630 return DeviceVector(rxSinkDevice);
631 }
632 }
633 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
634 // the device returned is not necessarily reachable via this output
635 // (filter later by setOutputDevices())
636 return getNewOutputDevices(mPrimaryOutput, fromCache);
637}
638
639status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
640{
641 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
642 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
643 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
644 }
645 return INVALID_OPERATION;
646}
647
648status_t AudioPolicyManager::updateCallRoutingInternal(
649 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700650{
651 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100652 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700653 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700654 if(!hasPrimaryOutput() ||
655 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100656 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700657 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100658 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100659
Francois Gaffie716e1432019-01-14 16:58:59 +0100660 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100661 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100663
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100664 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100665 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700666
Francois Gaffie601801d2021-06-22 13:27:39 +0200667 disconnectTelephonyAudioSource(mCallRxSourceClient);
668 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700669
François Gaffie9eb18552018-11-05 10:33:26 +0100670 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700671 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100672 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700673 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100674 // retrieve Rx Source and Tx Sink device descriptors
675 sp<DeviceDescriptor> rxSourceDevice =
676 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
677 String8(),
678 AUDIO_FORMAT_DEFAULT);
679 sp<DeviceDescriptor> txSinkDevice =
680 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
681 String8(),
682 AUDIO_FORMAT_DEFAULT);
683
684 // RX and TX Telephony device are declared by Primary Audio HAL
685 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
686 (telephonyRxModule->getHalVersionMajor() >= 3)) {
687 if (rxSourceDevice == 0 || txSinkDevice == 0) {
688 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100689 ALOGE("%s() no telephony Tx and/or RX device", __func__);
690 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100691 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100692 // createAudioPatchInternal now supports both HW / SW bridging
693 createRxPatch = true;
694 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100695 } else {
696 // If the RX device is on the primary HW module, then use legacy routing method for
697 // voice calls via setOutputDevice() on primary output.
698 // Otherwise, create two audio patches for TX and RX path.
699 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
700 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700701 // If the TX device is also on the primary HW module, setOutputDevice() will take care
702 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100703 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
704 (txSinkDevice != 0);
705 }
706 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
707 // Otherwise, create two audio patches for TX and RX path.
708 if (!createRxPatch) {
709 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700710 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200711 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800712 // If the TX device is on the primary HW module but RX device is
713 // on other HW module, SinkMetaData of telephony input should handle it
714 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700715 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700716 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100717 // terminate active capture if on the same HW module as the call TX source device
718 // FIXME: would be better to refine to only inputs whose profile connects to the
719 // call TX device but this information is not in the audio patch and logic here must be
720 // symmetric to the one in startInput()
721 for (const auto& activeDesc : mInputs.getActiveInputs()) {
722 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
723 closeActiveClients(activeDesc);
724 }
725 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200726 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800727 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100728 if (waitMs != nullptr) {
729 *waitMs = muteWaitMs;
730 }
731 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800732}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700733
Mikhail Naganov100f0122018-11-29 11:22:16 -0800734bool AudioPolicyManager::isDeviceOfModule(
735 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
736 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
737 if (module != 0) {
738 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
739 .indexOf(devDesc) != NAME_NOT_FOUND
740 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
741 .indexOf(devDesc) != NAME_NOT_FOUND;
742 }
743 return false;
744}
745
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200746void AudioPolicyManager::connectTelephonyRxAudioSource()
747{
Francois Gaffie601801d2021-06-22 13:27:39 +0200748 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200749 const struct audio_port_config source = {
750 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
751 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
752 };
753 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200754 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
755 ALOGE_IF(mCallRxSourceClient == nullptr,
756 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200757}
758
Francois Gaffie601801d2021-06-22 13:27:39 +0200759void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200760{
Francois Gaffie601801d2021-06-22 13:27:39 +0200761 if (clientDesc == nullptr) {
762 return;
763 }
764 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
765 "%s error stopping audio source", __func__);
766 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200767}
768
769void AudioPolicyManager::connectTelephonyTxAudioSource(
770 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
771 uint32_t delayMs)
772{
Francois Gaffie601801d2021-06-22 13:27:39 +0200773 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200774 if (srcDevice == nullptr || sinkDevice == nullptr) {
775 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
776 return;
777 }
778 PatchBuilder patchBuilder;
779 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
780 ALOGV("%s between source %s and sink %s", __func__,
781 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200782 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200783 const audio_attributes_t aa = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
784 struct audio_port_config source = {};
785 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200786 mCallTxSourceClient = new InternalSourceClientDescriptor(
787 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200788 mCommunnicationStrategy, toVolumeSource(aa));
789 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
790 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200791 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
792 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200793 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
794 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200795 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200796 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200797}
798
Eric Laurente0720872014-03-11 09:30:41 -0700799void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700800{
801 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100802 // store previous phone state for management of sonification strategy below
803 int oldState = mEngine->getPhoneState();
804
805 if (mEngine->setPhoneState(state) != NO_ERROR) {
806 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700807 return;
808 }
François Gaffie2110e042015-03-24 08:41:51 +0100809 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700810 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700811 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700812 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800813 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700814 }
815
François Gaffie2110e042015-03-24 08:41:51 +0100816 /**
817 * Switching to or from incall state or switching between telephony and VoIP lead to force
818 * routing command.
819 */
Eric Laurent74b71512019-11-06 17:21:57 -0800820 bool force = ((isStateInCall(oldState) != isStateInCall(state))
821 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700822
823 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700824 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700825
Eric Laurente552edb2014-03-10 17:42:56 -0700826 int delayMs = 0;
827 if (isStateInCall(state)) {
828 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100829 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
830 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700831 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700832 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700833 // mute media and sonification strategies and delay device switch by the largest
834 // latency of any output where either strategy is active.
835 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100836 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
837 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
838 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700839 (delayMs < (int)desc->latency()*2)) {
840 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700841 }
François Gaffiec005e562018-11-06 15:04:49 +0100842 setStrategyMute(musicStrategy, true, desc);
843 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
844 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
845 nullptr, true /*fromCache*/).types());
846 setStrategyMute(sonificationStrategy, true, desc);
847 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
848 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
849 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700850 }
851 }
852
Eric Laurent87ffa392015-05-22 10:32:38 -0700853 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700854 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100855 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700856 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100857 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
858 // force routing command to audio hardware when ending call
859 // even if no device change is needed
860 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
861 rxDevices = mPrimaryOutput->devices();
862 }
863 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200864 disconnectTelephonyAudioSource(mCallRxSourceClient);
865 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100866 }
François Gaffie11d30102018-11-02 16:09:09 +0100867 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700868 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700869 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700870
871 // reevaluate routing on all outputs in case tracks have been started during the call
872 for (size_t i = 0; i < mOutputs.size(); i++) {
873 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100874 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200875 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
876 bool forceRouting = !newDevices.isEmpty();
877 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
878 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700879 }
880 }
881
Eric Laurente552edb2014-03-10 17:42:56 -0700882 if (isStateInCall(state)) {
883 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700884 // force reevaluating accessibility routing when call starts
885 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700886 }
887
888 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100889 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
890 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700891}
892
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700893audio_mode_t AudioPolicyManager::getPhoneState() {
894 return mEngine->getPhoneState();
895}
896
Eric Laurente0720872014-03-11 09:30:41 -0700897void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100898 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700899{
François Gaffie2110e042015-03-24 08:41:51 +0100900 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700901 if (config == mEngine->getForceUse(usage)) {
902 return;
903 }
Eric Laurente552edb2014-03-10 17:42:56 -0700904
François Gaffie2110e042015-03-24 08:41:51 +0100905 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
906 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
907 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700908 }
François Gaffie2110e042015-03-24 08:41:51 +0100909 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
910 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
911 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700912
913 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700914 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800915
Eric Laurent22fcda22019-05-17 16:28:47 -0700916 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
917 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
918 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
919 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
920 }
921
Eric Laurentdc462862016-07-19 12:29:53 -0700922 //FIXME: workaround for truncated touch sounds
923 // to be removed when the problem is handled by system UI
924 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700925 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
926 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
927 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700928
929 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100930 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700931}
932
Eric Laurente0720872014-03-11 09:30:41 -0700933void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700934{
935 ALOGV("setSystemProperty() property %s, value %s", property, value);
936}
937
Dorin Drimusecc9f422022-03-09 17:57:40 +0100938// Find an MSD output profile compatible with the parameters passed.
939// When "directOnly" is set, restrict search to profiles for direct outputs.
940sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
941 const DeviceVector& devices,
942 uint32_t samplingRate,
943 audio_format_t format,
944 audio_channel_mask_t channelMask,
945 audio_output_flags_t flags,
946 bool directOnly)
947{
948 flags = getRelevantFlags(flags, directOnly);
949
950 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
951 if (msdModule != nullptr) {
952 // for the msd module check if there are patches to the output devices
953 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
954 HwModuleCollection modules;
955 modules.add(msdModule);
956 return searchCompatibleProfileHwModules(
957 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
958 flags, directOnly);
959 }
960 }
961 return nullptr;
962}
963
Michael Chana94fbb22018-04-24 14:31:19 +1000964// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
965// search to profiles for direct outputs.
966sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100967 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000968 uint32_t samplingRate,
969 audio_format_t format,
970 audio_channel_mask_t channelMask,
971 audio_output_flags_t flags,
972 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700973{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100974 flags = getRelevantFlags(flags, directOnly);
975
976 return searchCompatibleProfileHwModules(
977 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
978}
979
980audio_output_flags_t AudioPolicyManager::getRelevantFlags (
981 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000982 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100983 // only retain flags that will drive the direct output profile selection
984 // if explicitly requested
985 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000986 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100987 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
988 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +1000989 }
Dorin Drimusecc9f422022-03-09 17:57:40 +0100990 return flags;
991}
Eric Laurent861a6282015-05-18 15:40:16 -0700992
Dorin Drimusecc9f422022-03-09 17:57:40 +0100993sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
994 const HwModuleCollection& hwModules,
995 const DeviceVector& devices,
996 uint32_t samplingRate,
997 audio_format_t format,
998 audio_channel_mask_t channelMask,
999 audio_output_flags_t flags,
1000 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001001 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001002 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001003 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001004 if (!curProfile->isCompatibleProfile(devices,
1005 samplingRate, NULL /*updatedSamplingRate*/,
1006 format, NULL /*updatedFormat*/,
1007 channelMask, NULL /*updatedChannelMask*/,
1008 flags)) {
1009 continue;
1010 }
1011 // reject profiles not corresponding to a device currently available
1012 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1013 continue;
1014 }
1015 // reject profiles if connected device does not support codec
1016 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1017 continue;
1018 }
1019 if (!directOnly) {
1020 return curProfile;
1021 }
1022
1023 // when searching for direct outputs, if several profiles are compatible, give priority
1024 // to one with offload capability
1025 if (profile != 0 &&
1026 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001027 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001028 }
1029 profile = curProfile;
1030 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1031 break;
1032 }
Eric Laurente552edb2014-03-10 17:42:56 -07001033 }
1034 }
Eric Laurent861a6282015-05-18 15:40:16 -07001035 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001036}
1037
Eric Laurentfa0f6742021-08-17 18:39:44 +02001038sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001039 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001040{
1041 for (const auto& hwModule : mHwModules) {
1042 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001043 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001044 continue;
1045 }
1046 // reject profiles not corresponding to a device currently available
1047 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1048 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1049 continue;
1050 }
1051 if (!devices.empty()) {
1052 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1053 != devices.size()) {
1054 continue;
1055 }
1056 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001057 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1058 return curProfile;
1059 }
1060 }
1061 return nullptr;
1062}
1063
Eric Laurentf4e63452017-11-06 19:31:46 +00001064audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001065{
François Gaffiec005e562018-11-06 15:04:49 +01001066 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001067
1068 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1069 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1070 // format, flags, etc. This may result in some discrepancy for functions that utilize
1071 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1072 // and AudioSystem::getOutputSamplingRate().
1073
François Gaffie11d30102018-11-02 16:09:09 +01001074 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001075 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001076
François Gaffie11d30102018-11-02 16:09:09 +01001077 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1078 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001079 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001080}
1081
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001082status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1083 const audio_attributes_t *srcAttr,
1084 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001085{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001086 if (srcAttr != NULL) {
1087 if (!isValidAttributes(srcAttr)) {
1088 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1089 __func__,
1090 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1091 srcAttr->tags);
1092 return BAD_VALUE;
1093 }
1094 *dstAttr = *srcAttr;
1095 } else {
1096 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1097 ALOGE("%s: invalid stream type", __func__);
1098 return BAD_VALUE;
1099 }
François Gaffiec005e562018-11-06 15:04:49 +01001100 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001101 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001102
1103 // Only honor audibility enforced when required. The client will be
1104 // forced to reconnect if the forced usage changes.
1105 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001106 dstAttr->flags = static_cast<audio_flags_mask_t>(
1107 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001108 }
1109
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001110 return NO_ERROR;
1111}
1112
Kevin Rocard153f92d2018-12-18 18:33:28 -08001113status_t AudioPolicyManager::getOutputForAttrInt(
1114 audio_attributes_t *resultAttr,
1115 audio_io_handle_t *output,
1116 audio_session_t session,
1117 const audio_attributes_t *attr,
1118 audio_stream_type_t *stream,
1119 uid_t uid,
1120 const audio_config_t *config,
1121 audio_output_flags_t *flags,
1122 audio_port_handle_t *selectedDeviceId,
1123 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001124 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001125 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001126{
François Gaffiec005e562018-11-06 15:04:49 +01001127 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001128 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001129 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001130 const sp<DeviceDescriptor> requestedDevice =
1131 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1132
Eric Laurent8a1095a2019-11-08 14:44:16 -08001133 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001134 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1135 if (status != NO_ERROR) {
1136 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001137 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001138 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001139 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001140 }
François Gaffiec005e562018-11-06 15:04:49 +01001141 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001142
François Gaffiec005e562018-11-06 15:04:49 +01001143 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1144 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001145
Kevin Rocard153f92d2018-12-18 18:33:28 -08001146 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1147 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1148 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001149 sp<AudioPolicyMix> primaryMix;
1150 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001151 if (status != OK) {
1152 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001153 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001154
Kevin Rocard153f92d2018-12-18 18:33:28 -08001155 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001156 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001157
1158 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001159 if ((usePrimaryOutputFromPolicyMixes
1160 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001161 && !audio_is_linear_pcm(config->format)) {
1162 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001163 return BAD_VALUE;
1164 }
1165 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001166 sp<DeviceDescriptor> deviceDesc =
1167 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1168 primaryMix->mDeviceAddress,
1169 AUDIO_FORMAT_DEFAULT);
1170 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001171 if (deviceDesc != nullptr
1172 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001173 audio_io_handle_t newOutput;
1174 status = openDirectOutput(
1175 *stream, session, config,
1176 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1177 DeviceVector(deviceDesc), &newOutput);
1178 if (status != NO_ERROR) {
1179 policyDesc = nullptr;
1180 } else {
1181 policyDesc = mOutputs.valueFor(newOutput);
1182 primaryMix->setOutput(policyDesc);
1183 }
1184 }
1185 if (policyDesc != nullptr) {
1186 policyDesc->mPolicyMix = primaryMix;
1187 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001188 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001189
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001190 ALOGV("getOutputForAttr() returns output %d", *output);
1191 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1192 *outputType = API_OUT_MIX_PLAYBACK;
1193 } else {
1194 *outputType = API_OUTPUT_LEGACY;
1195 }
1196 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001197 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001198 }
François Gaffiec005e562018-11-06 15:04:49 +01001199 // Virtual sources must always be dynamicaly or explicitly routed
1200 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1201 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1202 return BAD_VALUE;
1203 }
1204 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1205 // in order to let the choice of the order to future vendor engine
1206 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001207
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001208 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001209 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001210 }
1211
Nadav Barb2f18162018-07-18 13:01:53 +03001212 // Set incall music only if device was explicitly set, and fallback to the device which is
1213 // chosen by the engine if not.
1214 // FIXME: provide a more generic approach which is not device specific and move this back
1215 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001216 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001217 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001218 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001219 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001220 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001221 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001222 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001223 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001224 }
1225 }
1226
François Gaffiec005e562018-11-06 15:04:49 +01001227 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1228 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1229 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001230
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001231 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001232 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001233 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001234 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001235 ALOGV("%s() Using MSD devices %s instead of devices %s",
1236 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001237 } else {
1238 *output = AUDIO_IO_HANDLE_NONE;
1239 }
1240 }
1241 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001242 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001243 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001244 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001245 if (*output == AUDIO_IO_HANDLE_NONE) {
1246 return INVALID_OPERATION;
1247 }
Paul McLeanaa981192015-03-21 09:55:15 -07001248
François Gaffiec005e562018-11-06 15:04:49 +01001249 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001250 for (auto &outputDevice : outputDevices) {
1251 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1252 *selectedDeviceId = outputDevice->getId();
1253 break;
1254 }
1255 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001256
Eric Laurent8a1095a2019-11-08 14:44:16 -08001257 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1258 *outputType = API_OUTPUT_TELEPHONY_TX;
1259 } else {
1260 *outputType = API_OUTPUT_LEGACY;
1261 }
1262
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001263 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1264
1265 return NO_ERROR;
1266}
1267
1268status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1269 audio_io_handle_t *output,
1270 audio_session_t session,
1271 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001272 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001273 const audio_config_t *config,
1274 audio_output_flags_t *flags,
1275 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001276 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001277 std::vector<audio_io_handle_t> *secondaryOutputs,
1278 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001279{
1280 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1281 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1282 return INVALID_OPERATION;
1283 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001284 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001285 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001286 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001287 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001288 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001289 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001290 const sp<DeviceDescriptor> requestedDevice =
1291 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1292
1293 // Prevent from storing invalid requested device id in clients
1294 const audio_port_handle_t sanitizedRequestedPortId =
1295 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1296 *selectedDeviceId = sanitizedRequestedPortId;
1297
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001298 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001299 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001300 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001301 if (status != NO_ERROR) {
1302 return status;
1303 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001304 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001305 if (secondaryOutputs != nullptr) {
1306 for (auto &secondaryMix : secondaryMixes) {
1307 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1308 if (outputDesc != nullptr &&
1309 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1310 secondaryOutputs->push_back(outputDesc->mIoHandle);
1311 weakSecondaryOutputDescs.push_back(outputDesc);
1312 }
1313 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001314 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001315
Eric Laurent8fc147b2018-07-22 19:13:55 -07001316 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001317 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001318 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001319 };
jiabin4ef93452019-09-10 14:29:54 -07001320 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001321
Eric Laurentc209fe42020-06-05 18:11:23 -07001322 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001323 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001324 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001325 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001326 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001327 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001328 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001329 std::move(weakSecondaryOutputDescs),
1330 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001331 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001332
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001333 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1334 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001335
Eric Laurente83b55d2014-11-14 10:06:21 -08001336 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001337}
1338
Eric Laurentc529cf62020-04-17 18:19:10 -07001339status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1340 audio_session_t session,
1341 const audio_config_t *config,
1342 audio_output_flags_t flags,
1343 const DeviceVector &devices,
1344 audio_io_handle_t *output) {
1345
1346 *output = AUDIO_IO_HANDLE_NONE;
1347
1348 // skip direct output selection if the request can obviously be attached to a mixed output
1349 // and not explicitly requested
1350 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1351 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1352 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1353 return NAME_NOT_FOUND;
1354 }
1355
1356 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1357 // This prevents creating an offloaded track and tearing it down immediately after start
1358 // when audioflinger detects there is an active non offloadable effect.
1359 // FIXME: We should check the audio session here but we do not have it in this context.
1360 // This may prevent offloading in rare situations where effects are left active by apps
1361 // in the background.
1362 sp<IOProfile> profile;
1363 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1364 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1365 profile = getProfileForOutput(
1366 devices, config->sample_rate, config->format, config->channel_mask,
1367 flags, true /* directOnly */);
1368 }
1369
1370 if (profile == nullptr) {
1371 return NAME_NOT_FOUND;
1372 }
1373
1374 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1375 for (size_t i = 0; i < mOutputs.size(); i++) {
1376 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1377 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1378 // reuse direct output if currently open by the same client
1379 // and configured with same parameters
1380 if ((config->sample_rate == desc->getSamplingRate()) &&
1381 (config->format == desc->getFormat()) &&
1382 (config->channel_mask == desc->getChannelMask()) &&
1383 (session == desc->mDirectClientSession)) {
1384 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001385 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001386 mOutputs.keyAt(i), session);
1387 *output = mOutputs.keyAt(i);
1388 return NO_ERROR;
1389 }
1390 }
1391 }
1392
1393 if (!profile->canOpenNewIo()) {
1394 return NAME_NOT_FOUND;
1395 }
1396
1397 sp<SwAudioOutputDescriptor> outputDesc =
1398 new SwAudioOutputDescriptor(profile, mpClientInterface);
1399
Michael Chan6fb34492020-12-08 15:44:49 +11001400 // An MSD patch may be using the only output stream that can service this request. Release
1401 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001402 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001403
Eric Laurentf1f22e72021-07-13 14:04:14 +02001404 status_t status =
1405 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001406
1407 // only accept an output with the requested parameters
1408 if (status != NO_ERROR ||
1409 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1410 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1411 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1412 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1413 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1414 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1415 config->channel_mask, outputDesc->getChannelMask());
1416 if (*output != AUDIO_IO_HANDLE_NONE) {
1417 outputDesc->close();
1418 }
1419 // fall back to mixer output if possible when the direct output could not be open
1420 if (audio_is_linear_pcm(config->format) &&
1421 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1422 return NAME_NOT_FOUND;
1423 }
1424 *output = AUDIO_IO_HANDLE_NONE;
1425 return BAD_VALUE;
1426 }
1427 outputDesc->mDirectOpenCount = 1;
1428 outputDesc->mDirectClientSession = session;
1429
1430 addOutput(*output, outputDesc);
1431 mPreviousOutputs = mOutputs;
1432 ALOGV("%s returns new direct output %d", __func__, *output);
1433 mpClientInterface->onAudioPortListUpdate();
1434 return NO_ERROR;
1435}
1436
François Gaffie11d30102018-11-02 16:09:09 +01001437audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1438 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001439 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001440 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001441 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001442 audio_output_flags_t *flags,
1443 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001444{
Andy Hungc88b0642018-04-27 15:42:35 -07001445 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001446
jiabine375d412019-02-26 12:54:53 -08001447 // Discard haptic channel mask when forcing muting haptic channels.
1448 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001449 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1450 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001451
Eric Laurente552edb2014-03-10 17:42:56 -07001452 // open a direct output if required by specified parameters
1453 //force direct flag if offload flag is set: offloading implies a direct output stream
1454 // and all common behaviors are driven by checking only the direct flag
1455 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001456 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1457 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001458 }
Nadav Bar766fb022018-01-07 12:18:03 +02001459 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1460 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001461 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001462
1463 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1464
Eric Laurente83b55d2014-11-14 10:06:21 -08001465 // only allow deep buffering for music stream type
1466 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001467 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001468 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001469 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001470 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1471 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001472 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001473 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001474 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001475 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001476 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001477 audio_is_linear_pcm(config->format) &&
1478 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001479 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001480 AUDIO_OUTPUT_FLAG_DIRECT);
1481 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001482 }
Eric Laurente552edb2014-03-10 17:42:56 -07001483
Carter Hsua3abb402021-10-26 11:11:20 +08001484 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1485 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1486 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1487 }
1488
Eric Laurentfa0f6742021-08-17 18:39:44 +02001489 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001490 && canBeSpatializedInt(attr, config,
1491 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02001492 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001493 }
1494
Eric Laurentc529cf62020-04-17 18:19:10 -07001495 audio_config_t directConfig = *config;
1496 directConfig.channel_mask = channelMask;
1497 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1498 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001499 return output;
1500 }
1501
Eric Laurent14cbfca2016-03-17 09:42:16 -07001502 // A request for HW A/V sync cannot fallback to a mixed output because time
1503 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001504 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001505 return AUDIO_IO_HANDLE_NONE;
1506 }
1507
Eric Laurente552edb2014-03-10 17:42:56 -07001508 // ignoring channel mask due to downmix capability in mixer
1509
1510 // open a non direct output
1511
1512 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001513 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001514 // get which output is suitable for the specified stream. The actual
1515 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001516 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001517
Eric Laurent8838a382014-09-08 16:44:28 -07001518 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001519 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001520 output = selectOutput(
1521 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001522 }
François Gaffie11d30102018-11-02 16:09:09 +01001523 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001524 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001525 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001526
Eric Laurente552edb2014-03-10 17:42:56 -07001527 return output;
1528}
1529
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001530sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001531 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1532 mAvailableInputDevices);
1533 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1534}
1535
1536DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1537 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1538 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001539}
1540
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001541const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001542 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001543 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1544 if (msdModule != 0) {
1545 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1546 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1547 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1548 const struct audio_port_config *source = &patch->mPatch.sources[j];
1549 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1550 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001551 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001552 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001553 }
1554 }
1555 }
1556 return msdPatches;
1557}
1558
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001559bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1560 ssize_t index = mAudioPatches.indexOfKey(handle);
1561 if (index < 0) {
1562 return false;
1563 }
1564 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1565 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1566 if (msdModule == nullptr) {
1567 return false;
1568 }
1569 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1570 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1571 return true;
1572 }
1573 index = getMsdOutputPatches().indexOfKey(handle);
1574 if (index < 0) {
1575 return false;
1576 }
1577 return true;
1578}
1579
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001580status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1581 const InputProfileCollection &inputProfiles,
1582 const OutputProfileCollection &outputProfiles,
1583 const sp<DeviceDescriptor> &sourceDevice,
1584 const sp<DeviceDescriptor> &sinkDevice,
1585 AudioProfileVector& sourceProfiles,
1586 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001587 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001588 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001589 return NO_INIT;
1590 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001591 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001592 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001593 return NO_INIT;
1594 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001595 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001596 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1597 inProfile->supportsDevice(sourceDevice)) {
1598 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001599 }
1600 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001601 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001602 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001603 outProfile->supportsDevice(sinkDevice)) {
1604 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001605 }
1606 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001607 return NO_ERROR;
1608}
1609
1610status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1611 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1612 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1613{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001614 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001615 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1616 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1617 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001618 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001619 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1620 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001621 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622 }
1623 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1624 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1625 sinkConfig->format = bestSinkConfig.format;
1626 // For encoded streams force direct flag to prevent downstream mixing.
1627 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1628 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001629 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1630 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001631 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001632 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1633 // raw and IEC61937 framed streams.
1634 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1635 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1636 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001637 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1638 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1639 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1640 sourceConfig->format = bestSinkConfig.format;
1641 // Copy input stream directly without any processing (e.g. resampling).
1642 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1643 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1644 if (hwAvSync) {
1645 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1646 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1647 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1648 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1649 }
1650 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1651 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1652 sinkConfig->config_mask |= config_mask;
1653 sourceConfig->config_mask |= config_mask;
1654 return NO_ERROR;
1655}
1656
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001657PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1658 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001659{
1660 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001661 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1662 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1663 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1664 if (deviceModule == nullptr) {
1665 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1666 return patchBuilder;
1667 }
1668 const InputProfileCollection inputProfiles = msdIsSource ?
1669 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1670 const OutputProfileCollection outputProfiles = msdIsSource ?
1671 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1672
1673 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1674 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1675 device : getMsdAudioOutDevices().itemAt(0);
1676 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1677
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001678 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1679 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001680 AudioProfileVector sourceProfiles;
1681 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001682 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1683 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001684 for (auto hwAvSync : { true, false }) {
1685 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1686 sourceProfiles, sinkProfiles) != NO_ERROR) {
1687 continue;
1688 }
1689 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1690 &sinkConfig) == NO_ERROR) {
1691 // Found a matching config. Re-create PatchBuilder with this config.
1692 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1693 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001694 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001695 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001696 " supporting PCM format conversion.", __func__);
1697 return patchBuilder;
1698}
1699
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001700status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001701 DeviceVector devices;
1702 if (outputDevices != nullptr && outputDevices->size() > 0) {
1703 devices.add(*outputDevices);
1704 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001705 // Use media strategy for unspecified output device. This should only
1706 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1707 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001708 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001709 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001710 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001711 }
Michael Chan6fb34492020-12-08 15:44:49 +11001712 std::vector<PatchBuilder> patchesToCreate;
1713 for (auto i = 0u; i < devices.size(); ++i) {
1714 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001715 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001716 }
1717 // Retain only the MSD patches associated with outputDevices request.
1718 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001719 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001720 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1721 auto retainedPatch = false;
1722 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1723 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1724 patchesToRemove.removeItemsAt(i);
1725 retainedPatch = true;
1726 break;
1727 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001728 }
Michael Chan6fb34492020-12-08 15:44:49 +11001729 if (retainedPatch) {
1730 it = patchesToCreate.erase(it);
1731 continue;
1732 }
1733 ++it;
1734 }
1735 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1736 return NO_ERROR;
1737 }
1738 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1739 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001740 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001741 }
Michael Chan6fb34492020-12-08 15:44:49 +11001742 status_t status = NO_ERROR;
1743 for (const auto &p : patchesToCreate) {
1744 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1745 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1746 char message[256];
1747 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1748 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1749 currStatus == NO_ERROR ? "Success" : "Error",
1750 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1751 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1752 if (currStatus == NO_ERROR) {
1753 ALOGD("%s", message);
1754 } else {
1755 ALOGE("%s", message);
1756 if (status == NO_ERROR) {
1757 status = currStatus;
1758 }
1759 }
1760 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001761 return status;
1762}
1763
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001764void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1765 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001766 for (size_t i = 0; i < msdPatches.size(); i++) {
1767 const auto& patch = msdPatches[i];
1768 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1769 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1770 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1771 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1772 releaseAudioPatch(patch->getHandle(), mUidCached);
1773 break;
1774 }
1775 }
1776 }
1777}
1778
Dorin Drimus94d94412022-02-02 09:05:02 +01001779bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1780 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1781 AudioPatchCollection msdPatches = getMsdOutputPatches();
1782 for (size_t i = 0; i < msdPatches.size(); i++) {
1783 const auto& patch = msdPatches[i];
1784 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1785 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1786 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1787 const auto& foundDevice = devicesToCheck.getDevice(
1788 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1789 if (foundDevice != nullptr) {
1790 devicesToCheck.remove(foundDevice);
1791 if (devicesToCheck.isEmpty()) {
1792 return true;
1793 }
1794 }
1795 }
1796 }
1797 }
1798 return false;
1799}
1800
Eric Laurente0720872014-03-11 09:30:41 -07001801audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001802 audio_output_flags_t flags,
1803 audio_format_t format,
1804 audio_channel_mask_t channelMask,
1805 uint32_t samplingRate,
1806 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001807{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001808 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1809 "%s called with format %#x", __func__, format);
1810
jiabinebb6af42020-06-09 17:31:17 -07001811 // Return the output that haptic-generating attached to when 1) session id is specified,
1812 // 2) haptic-generating effect exists for given session id and 3) the output that
1813 // haptic-generating effect attached to is in given outputs.
1814 if (sessionId != AUDIO_SESSION_NONE) {
1815 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1816 sessionId, FX_IID_HAPTICGENERATOR);
1817 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1818 return hapticGeneratingOutput;
1819 }
1820 }
1821
Eric Laurent16c66dd2019-05-01 17:54:10 -07001822 // Flags disqualifying an output: the match must happen before calling selectOutput()
1823 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1824 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1825
1826 // Flags expressing a functional request: must be honored in priority over
1827 // other criteria
1828 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1829 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001830 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1831 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001832 // Flags expressing a performance request: have lower priority than serving
1833 // requested sampling rate or channel mask
1834 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1835 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1836 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1837
1838 const audio_output_flags_t functionalFlags =
1839 (audio_output_flags_t)(flags & kFunctionalFlags);
1840 const audio_output_flags_t performanceFlags =
1841 (audio_output_flags_t)(flags & kPerformanceFlags);
1842
1843 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1844
Eric Laurente552edb2014-03-10 17:42:56 -07001845 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001846 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001847 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001848 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001849 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001850 // with tiebreak preferring the minimum number of extra functional flags
1851 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001852 // 3: the output supporting the exact channel mask
1853 // 4: the output with a higher channel count than requested
1854 // 5: the output with a higher sampling rate than requested
1855 // 6: the output with the highest number of requested performance flags
1856 // 7: the output with the bit depth the closest to the requested one
1857 // 8: the primary output
1858 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001859
Eric Laurent16c66dd2019-05-01 17:54:10 -07001860 // matching criteria values in priority order for best matching output so far
1861 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001862
Eric Laurent16c66dd2019-05-01 17:54:10 -07001863 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1864 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1865 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001866
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001867 for (audio_io_handle_t output : outputs) {
1868 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001869 // matching criteria values in priority order for current output
1870 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001871
Eric Laurent16c66dd2019-05-01 17:54:10 -07001872 if (outputDesc->isDuplicated()) {
1873 continue;
1874 }
1875 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1876 continue;
1877 }
Eric Laurent8838a382014-09-08 16:44:28 -07001878
Eric Laurent16c66dd2019-05-01 17:54:10 -07001879 // If haptic channel is specified, use the haptic output if present.
1880 // When using haptic output, same audio format and sample rate are required.
1881 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001882 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001883 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1884 continue;
1885 }
1886 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001887 && format == outputDesc->getFormat()
1888 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001889 currentMatchCriteria[0] = outputHapticChannelCount;
1890 }
1891
1892 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001893 const int matchingFunctionalFlags =
1894 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1895 const int totalFunctionalFlags =
1896 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1897 // Prefer matching functional flags, but subtract unnecessary functional flags.
1898 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001899
1900 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001901 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1902 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001903 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1904 channelCount <= outputChannelCount) {
1905 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001906 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1907 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001908 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001909 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001910 currentMatchCriteria[3] = outputChannelCount;
1911 }
1912
1913 // sampling rate match
1914 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001915 samplingRate <= outputDesc->getSamplingRate()) {
1916 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001917 }
1918
1919 // performance flags match
1920 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1921
1922 // format match
1923 if (format != AUDIO_FORMAT_INVALID) {
1924 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001925 PolicyAudioPort::kFormatDistanceMax -
1926 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001927 }
1928
1929 // primary output match
1930 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1931
1932 // compare match criteria by priority then value
1933 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1934 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1935 bestMatchCriteria = currentMatchCriteria;
1936 bestOutput = output;
1937
1938 std::stringstream result;
1939 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1940 std::ostream_iterator<int>(result, " "));
1941 ALOGV("%s new bestOutput %d criteria %s",
1942 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001943 }
1944 }
1945
Eric Laurent16c66dd2019-05-01 17:54:10 -07001946 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001947}
1948
Eric Laurent8fc147b2018-07-22 19:13:55 -07001949status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001950{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001951 ALOGV("%s portId %d", __FUNCTION__, portId);
1952
1953 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1954 if (outputDesc == 0) {
1955 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001956 return BAD_VALUE;
1957 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001958 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001959
Eric Laurent8fc147b2018-07-22 19:13:55 -07001960 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001961 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001962
Eric Laurent733ce942017-12-07 12:18:25 -08001963 status_t status = outputDesc->start();
1964 if (status != NO_ERROR) {
1965 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001966 }
1967
Eric Laurent97ac8712018-07-27 18:59:02 -07001968 uint32_t delayMs;
1969 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001970
1971 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001972 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001973 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001974 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001975 if (delayMs != 0) {
1976 usleep(delayMs * 1000);
1977 }
1978
1979 return status;
1980}
1981
Eric Laurent97ac8712018-07-27 18:59:02 -07001982status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1983 const sp<TrackClientDescriptor>& client,
1984 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001985{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001986 // cannot start playback of STREAM_TTS if any other output is being used
1987 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001988
1989 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001990 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001991 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001992 auto clientStrategy = client->strategy();
1993 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001994 if (stream == AUDIO_STREAM_TTS) {
1995 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001996 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01001997 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001998 return INVALID_OPERATION;
1999 } else {
2000 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2001 }
2002 } else {
2003 // some playback other than beacon starts
2004 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2005 }
2006
Eric Laurent77305a62016-07-25 16:39:22 -07002007 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002008 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002009 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002010
François Gaffie11d30102018-11-02 16:09:09 +01002011 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002012 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002013 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002014 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002015 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002016 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002017 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002018 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002019 } else {
2020 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002021 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002022 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2023 AUDIO_FORMAT_DEFAULT);
2024 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2025 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002026 }
2027
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002028 // requiresMuteCheck is false when we can bypass mute strategy.
2029 // It covers a common case when there is no materially active audio
2030 // and muting would result in unnecessary delay and dropped audio.
2031 const uint32_t outputLatencyMs = outputDesc->latency();
2032 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
2033
Eric Laurente552edb2014-03-10 17:42:56 -07002034 // increment usage count for this stream on the requested output:
2035 // NOTE that the usage count is the same for duplicated output and hardware output which is
2036 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002037 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002038
2039 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002040 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2041 client->isPreferredDeviceForExclusiveUse()) {
2042 // Preferred device may be exclusive, use only if no other active clients on this output
2043 devices = DeviceVector(
2044 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2045 } else {
2046 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2047 }
François Gaffie11d30102018-11-02 16:09:09 +01002048 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002049 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002050 }
2051 }
Eric Laurente552edb2014-03-10 17:42:56 -07002052
François Gaffiec005e562018-11-06 15:04:49 +01002053 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002054 selectOutputForMusicEffects();
2055 }
2056
François Gaffie1c878552018-11-22 16:53:21 +01002057 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002058 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002059 if (devices.isEmpty()) {
2060 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002061 }
François Gaffiec005e562018-11-06 15:04:49 +01002062 bool shouldWait =
2063 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2064 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2065 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002066 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002067 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002068 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002069 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002070 // An output has a shared device if
2071 // - managed by the same hw module
2072 // - supports the currently selected device
2073 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002074 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002075
Eric Laurent77305a62016-07-25 16:39:22 -07002076 // force a device change if any other output is:
2077 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002078 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002079 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002080 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002081 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002082 // change the device currently selected by the other output.
2083 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002084 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002085 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002086 force = true;
2087 }
2088 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002089 // a notification so that audio focus effect can propagate, or that a mute/unmute
2090 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002091 const uint32_t latencyMs = desc->latency();
2092 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2093
2094 if (shouldWait && isActive && (waitMs < latencyMs)) {
2095 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002096 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002097
2098 // Require mute check if another output is on a shared device
2099 // and currently active to have proper drain and avoid pops.
2100 // Note restoring AudioTracks onto this output needs to invoke
2101 // a volume ramp if there is no mute.
2102 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002103 }
2104 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002105
2106 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002107 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002108
Eric Laurente552edb2014-03-10 17:42:56 -07002109 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002110 auto &curves = getVolumeCurves(client->attributes());
2111 checkAndSetVolume(curves, client->volumeSource(),
2112 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002113 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002114 outputDesc->devices().types(), 0 /*delay*/,
2115 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002116
2117 // update the outputs if starting an output with a stream that can affect notification
2118 // routing
2119 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002120
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002121 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002122 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002123 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2124 }
Eric Laurentdc462862016-07-19 12:29:53 -07002125
2126 if (waitMs > muteWaitMs) {
2127 *delayMs = waitMs - muteWaitMs;
2128 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002129
2130 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2131 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2132 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2133 // change occurs after the MixerThread starts and causes a stream volume
2134 // glitch.
2135 //
2136 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002137 }
Eric Laurentdc462862016-07-19 12:29:53 -07002138
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002139 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002140 mEngine->getForceUse(
2141 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002142 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002143 }
2144
Eric Laurent97ac8712018-07-27 18:59:02 -07002145 // Automatically enable the remote submix input when output is started on a re routing mix
2146 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002147 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2148 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002149 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2150 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2151 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002152 "remote-submix",
2153 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002154 }
2155
Eric Laurente552edb2014-03-10 17:42:56 -07002156 return NO_ERROR;
2157}
2158
Eric Laurent8fc147b2018-07-22 19:13:55 -07002159status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002160{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002161 ALOGV("%s portId %d", __FUNCTION__, portId);
2162
2163 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2164 if (outputDesc == 0) {
2165 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002166 return BAD_VALUE;
2167 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002168 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002169
Eric Laurent97ac8712018-07-27 18:59:02 -07002170 ALOGV("stopOutput() output %d, stream %d, session %d",
2171 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002172
Eric Laurent97ac8712018-07-27 18:59:02 -07002173 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002174
Eric Laurent733ce942017-12-07 12:18:25 -08002175 if (status == NO_ERROR ) {
2176 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002177 }
2178 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002179}
2180
Eric Laurent97ac8712018-07-27 18:59:02 -07002181status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2182 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002183{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002184 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002185 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002186 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002187
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002188 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2189
François Gaffie1c878552018-11-22 16:53:21 +01002190 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2191 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002192 // Automatically disable the remote submix input when output is stopped on a
2193 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002194 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002195 if (isSingleDeviceType(
2196 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002197 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002198 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002199 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2200 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002201 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002202 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002203 }
2204 }
2205 bool forceDeviceUpdate = false;
2206 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002207 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002208 forceDeviceUpdate = true;
2209 }
2210
Eric Laurente552edb2014-03-10 17:42:56 -07002211 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002212 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002213
Eric Laurente552edb2014-03-10 17:42:56 -07002214 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002215 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002216 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002217 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002218
2219 // If the routing does not change, if an output is routed on a device using HwGain
2220 // (aka setAudioPortConfig) and there are still active clients following different
2221 // volume group(s), force reapply volume
2222 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2223 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2224
Eric Laurente552edb2014-03-10 17:42:56 -07002225 // delay the device switch by twice the latency because stopOutput() is executed when
2226 // the track stop() command is received and at that time the audio track buffer can
2227 // still contain data that needs to be drained. The latency only covers the audio HAL
2228 // and kernel buffers. Also the latency does not always include additional delay in the
2229 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002230 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2231 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002232
2233 // force restoring the device selection on other active outputs if it differs from the
2234 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002235 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002236 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002237 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002238 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002239 desc->isActive() &&
2240 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002241 (newDevices != desc->devices())) {
2242 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2243 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002244
François Gaffie11d30102018-11-02 16:09:09 +01002245 setOutputDevices(desc, newDevices2, force, delayMs);
2246
Eric Laurent57de36c2016-09-28 16:59:11 -07002247 // re-apply device specific volume if not done by setOutputDevice()
2248 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002249 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002250 }
Eric Laurente552edb2014-03-10 17:42:56 -07002251 }
2252 }
2253 // update the outputs if stopping one with a stream that can affect notification routing
2254 handleNotificationRoutingForStream(stream);
2255 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002256
2257 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2258 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002259 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002260 }
2261
François Gaffiec005e562018-11-06 15:04:49 +01002262 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002263 selectOutputForMusicEffects();
2264 }
Eric Laurente552edb2014-03-10 17:42:56 -07002265 return NO_ERROR;
2266 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002267 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002268 return INVALID_OPERATION;
2269 }
2270}
2271
jiabinbce0c1d2020-10-05 11:20:18 -07002272bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002273{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002274 ALOGV("%s portId %d", __FUNCTION__, portId);
2275
2276 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2277 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002278 // If an output descriptor is closed due to a device routing change,
2279 // then there are race conditions with releaseOutput from tracks
2280 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2281 // destroyed shortly thereafter.
2282 //
2283 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002284 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002285 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002286 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002287
2288 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002289
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302290 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2291 if (outputDesc->isClientActive(client)) {
2292 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2293 stopOutput(portId);
2294 }
2295
Eric Laurent8fc147b2018-07-22 19:13:55 -07002296 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2297 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002298 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002299 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002300 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002301 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002302 if (--outputDesc->mDirectOpenCount == 0) {
2303 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002304 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002305 }
2306 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302307
Andy Hung39efb7a2018-09-26 15:39:28 -07002308 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002309 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2310 // The output is pending reopened to query dynamic profiles and
2311 // there is no active clients
2312 closeOutput(outputDesc->mIoHandle);
2313 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2314 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2315 if (newOutputDesc == nullptr) {
2316 ALOGE("%s failed to open output", __func__);
2317 }
2318 return true;
2319 }
2320 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002321}
2322
Eric Laurentcaf7f482014-11-25 17:50:47 -08002323status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2324 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002325 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002326 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002327 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002328 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002329 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002330 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002331 input_type_t *inputType,
2332 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002333{
François Gaffiec005e562018-11-06 15:04:49 +01002334 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002335 "flags %#x attributes=%s requested device ID %d",
2336 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2337 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002338
Eric Laurentad2e7b92017-09-14 20:06:42 -07002339 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002340 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002341 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002342 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002343 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002344 sp<AudioInputDescriptor> inputDesc;
2345 sp<RecordClientDescriptor> clientDesc;
2346 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002347 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002348 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002349
2350 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2351 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2352 return INVALID_OPERATION;
2353 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002354
Francois Gaffie716e1432019-01-14 16:58:59 +01002355 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2356 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002357 }
2358
Paul McLean466dc8e2015-04-17 13:15:36 -06002359 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002360 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002361 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002362
Eric Laurentad2e7b92017-09-14 20:06:42 -07002363 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2364 // possible
2365 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2366 *input != AUDIO_IO_HANDLE_NONE) {
2367 ssize_t index = mInputs.indexOfKey(*input);
2368 if (index < 0) {
2369 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2370 status = BAD_VALUE;
2371 goto error;
2372 }
2373 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002374 RecordClientVector clients = inputDesc->getClientsForSession(session);
2375 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002376 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2377 status = BAD_VALUE;
2378 goto error;
2379 }
2380 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2381 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002382 // corresponds to a new client and is only permitted from the same UID.
2383 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002384 if (clients.size() > 1) {
2385 for (const auto& client : clients) {
2386 // The client map is ordered by key values (portId) and portIds are allocated
2387 // incrementaly. So the first client in this list is the one opened by audio flinger
2388 // when the mmap stream is created and should be ignored as it does not correspond
2389 // to an actual client
2390 if (client == *clients.cbegin()) {
2391 continue;
2392 }
2393 if (uid != client->uid() && !client->isSilenced()) {
2394 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2395 uid, client->portId(), client->uid());
2396 status = INVALID_OPERATION;
2397 goto error;
2398 }
Eric Laurent331679c2018-04-16 17:03:16 -07002399 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002400 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002401 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002402 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002403
Eric Laurentfecbceb2021-02-09 14:46:43 +01002404 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002405 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002406 }
2407
2408 *input = AUDIO_IO_HANDLE_NONE;
2409 *inputType = API_INPUT_INVALID;
2410
Francois Gaffie716e1432019-01-14 16:58:59 +01002411 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002412
Francois Gaffie716e1432019-01-14 16:58:59 +01002413 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2414 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2415 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002416 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002417 ALOGW("%s could not find input mix for attr %s",
2418 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002419 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002420 }
jiabinc1de2df2019-05-07 14:26:40 -07002421 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2422 String8(attr->tags + strlen("addr=")),
2423 AUDIO_FORMAT_DEFAULT);
2424 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002425 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002426 __func__, attributes.source, attributes.tags);
2427 status = BAD_VALUE;
2428 goto error;
2429 }
2430
Kevin Rocard25f9b052019-02-27 15:08:54 -08002431 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2432 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2433 } else {
2434 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2435 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002436 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002437 if (explicitRoutingDevice != nullptr) {
2438 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002439 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002440 // Prevent from storing invalid requested device id in clients
2441 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002442 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002443 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2444 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002445 }
François Gaffie11d30102018-11-02 16:09:09 +01002446 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002447 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002448 status = BAD_VALUE;
2449 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002450 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002451 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2452 *inputType = API_INPUT_MIX_CAPTURE;
2453 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002454 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2455 // there is an external policy, but this input is attached to a mix of recorders,
2456 // meaning it receives audio injected into the framework, so the recorder doesn't
2457 // know about it and is therefore considered "legacy"
2458 *inputType = API_INPUT_LEGACY;
2459 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002460 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002461 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002462 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002463 } else {
2464 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002465 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002466
Eric Laurent599c7582015-12-07 18:05:55 -08002467 }
2468
François Gaffiec005e562018-11-06 15:04:49 +01002469 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002470 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002471 status = INVALID_OPERATION;
2472 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002473 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002474
Eric Laurent8f42ea12018-08-08 09:08:25 -07002475exit:
2476
François Gaffiec005e562018-11-06 15:04:49 +01002477 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2478 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002479
Francois Gaffie716e1432019-01-14 16:58:59 +01002480 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002481 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002482 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002483
Mikhail Naganov2996f672019-04-18 12:29:59 -07002484 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002485 requestedDeviceId, attributes.source, flags,
2486 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002487 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002488 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002489
2490 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2491 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002492
Eric Laurent599c7582015-12-07 18:05:55 -08002493 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002494
2495error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002496 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002497}
2498
2499
François Gaffie11d30102018-11-02 16:09:09 +01002500audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002501 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002502 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002503 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002504 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002505 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002506{
2507 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002508 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002509 bool isSoundTrigger = false;
2510
François Gaffiec005e562018-11-06 15:04:49 +01002511 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002512 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2513 if (index >= 0) {
2514 input = mSoundTriggerSessions.valueFor(session);
2515 isSoundTrigger = true;
2516 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2517 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2518 } else {
2519 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002520 }
François Gaffiec005e562018-11-06 15:04:49 +01002521 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002522 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002523 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002524 }
2525
Carter Hsua3abb402021-10-26 11:11:20 +08002526 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2527 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2528 }
2529
Andy Hungf129b032015-04-07 13:45:50 -07002530 // find a compatible input profile (not necessarily identical in parameters)
2531 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002532 // sampling rate and flags may be updated by getInputProfile
2533 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2534 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002535 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002536 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002537 audio_input_flags_t profileFlags = flags;
2538 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002539 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002540 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002541 profileFlags);
2542 if (profile != 0) {
2543 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002544 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2545 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002546 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002547 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2548 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002549 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002550 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002551 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002552 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002553 }
Eric Laurente552edb2014-03-10 17:42:56 -07002554 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002555 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002556 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002557 if (samplingRate == 0) {
2558 samplingRate = profileSamplingRate;
2559 }
Eric Laurente552edb2014-03-10 17:42:56 -07002560
Eric Laurent322b4d22015-04-03 15:57:54 -07002561 if (profile->getModuleHandle() == 0) {
2562 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002563 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002564 }
2565
Eric Laurentec376dc2021-04-08 20:41:22 +02002566 // Reuse an already opened input if a client with the same session ID already exists
2567 // on that input
2568 for (size_t i = 0; i < mInputs.size(); i++) {
2569 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2570 if (desc->mProfile != profile) {
2571 continue;
2572 }
2573 RecordClientVector clients = desc->clientsList();
2574 for (const auto &client : clients) {
2575 if (session == client->session()) {
2576 return desc->mIoHandle;
2577 }
2578 }
2579 }
2580
Eric Laurent3974e3b2017-12-07 17:58:43 -08002581 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002582 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002583 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002584 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002585 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002586 continue;
2587 }
2588 // if sound trigger, reuse input if used by other sound trigger on same session
2589 // else
2590 // reuse input if active client app is not in IDLE state
2591 //
2592 RecordClientVector clients = desc->clientsList();
2593 bool doClose = false;
2594 for (const auto& client : clients) {
2595 if (isSoundTrigger != client->isSoundTrigger()) {
2596 continue;
2597 }
2598 if (client->isSoundTrigger()) {
2599 if (session == client->session()) {
2600 return desc->mIoHandle;
2601 }
2602 continue;
2603 }
2604 if (client->active() && client->appState() != APP_STATE_IDLE) {
2605 return desc->mIoHandle;
2606 }
2607 doClose = true;
2608 }
2609 if (doClose) {
2610 closeInput(desc->mIoHandle);
2611 } else {
2612 i++;
2613 }
2614 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002615 }
2616
Eric Laurentfe231122017-11-17 17:48:06 -08002617 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002618
Eric Laurentfe231122017-11-17 17:48:06 -08002619 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2620 lConfig.sample_rate = profileSamplingRate;
2621 lConfig.channel_mask = profileChannelMask;
2622 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002623
François Gaffie11d30102018-11-02 16:09:09 +01002624 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002625
2626 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002627 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002628 (profileSamplingRate != lConfig.sample_rate) ||
2629 !audio_formats_match(profileFormat, lConfig.format) ||
2630 (profileChannelMask != lConfig.channel_mask)) {
2631 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002632 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002633 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002634 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002635 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002636 }
Eric Laurent599c7582015-12-07 18:05:55 -08002637 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002638 }
2639
Eric Laurentc722f302014-12-10 11:21:49 -08002640 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002641
Eric Laurent599c7582015-12-07 18:05:55 -08002642 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002643 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002644
Eric Laurent599c7582015-12-07 18:05:55 -08002645 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002646}
2647
Eric Laurent4eb58f12018-12-07 16:41:02 -08002648status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002649{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002650 ALOGV("%s portId %d", __FUNCTION__, portId);
2651
2652 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2653 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002654 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002655 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002656 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002657 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002658 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002659 if (client->active()) {
2660 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2661 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002662 }
2663
Eric Laurent8f42ea12018-08-08 09:08:25 -07002664 audio_session_t session = client->session();
2665
Eric Laurent4eb58f12018-12-07 16:41:02 -08002666 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002667
Eric Laurent4eb58f12018-12-07 16:41:02 -08002668 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002669
Eric Laurent4eb58f12018-12-07 16:41:02 -08002670 status_t status = inputDesc->start();
2671 if (status != NO_ERROR) {
2672 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002673 }
Eric Laurente552edb2014-03-10 17:42:56 -07002674
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002675 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002676 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002677 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002678
Eric Laurent8f42ea12018-08-08 09:08:25 -07002679 // indicate active capture to sound trigger service if starting capture from a mic on
2680 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002681 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002682 if (device != nullptr) {
2683 status = setInputDevice(input, device, true /* force */);
2684 } else {
2685 ALOGW("%s no new input device can be found for descriptor %d",
2686 __FUNCTION__, inputDesc->getId());
2687 status = BAD_VALUE;
2688 }
Eric Laurente552edb2014-03-10 17:42:56 -07002689
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002690 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002691 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002692 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002693 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002694 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2695 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002696 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002697 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002698
François Gaffie11d30102018-11-02 16:09:09 +01002699 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2700 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002701 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002702 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002703 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002704
Eric Laurent8f42ea12018-08-08 09:08:25 -07002705 // automatically enable the remote submix output when input is started if not
2706 // used by a policy mix of type MIX_TYPE_RECORDERS
2707 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002708 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002709 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002710 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002711 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002712 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2713 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002714 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002715 if (address != "") {
2716 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2717 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002718 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002719 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002720 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002721 } else if (status != NO_ERROR) {
2722 // Restore client activity state.
2723 inputDesc->setClientActive(client, false);
2724 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002725 }
2726
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002727 ALOGV("%s input %d source = %d status = %d exit",
2728 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002729
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002730 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002731}
2732
Eric Laurent8fc147b2018-07-22 19:13:55 -07002733status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002734{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002735 ALOGV("%s portId %d", __FUNCTION__, portId);
2736
2737 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2738 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002739 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002740 return BAD_VALUE;
2741 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002742 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002743 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002744 if (!client->active()) {
2745 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002746 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002747 }
Carter Hsue6139d52021-07-08 10:30:20 +08002748 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002749 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002750
Eric Laurent8f42ea12018-08-08 09:08:25 -07002751 inputDesc->stop();
2752 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002753 auto current_source = inputDesc->source();
2754 setInputDevice(input, getNewInputDevice(inputDesc),
2755 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002756 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002757 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002758 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002759 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002760 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2761 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002762 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002763 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002764
2765 // automatically disable the remote submix output when input is stopped if not
2766 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002767 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002768 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002769 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002770 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002771 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2772 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002773 }
2774 if (address != "") {
2775 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2776 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002777 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002778 }
2779 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002780 resetInputDevice(input);
2781
2782 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2783 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002784 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2785 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002786 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002787 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002788 }
2789 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002790 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002791 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002792}
2793
Eric Laurent8fc147b2018-07-22 19:13:55 -07002794void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002795{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002796 ALOGV("%s portId %d", __FUNCTION__, portId);
2797
2798 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2799 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002800 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002801 return;
2802 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002803 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002804 audio_io_handle_t input = inputDesc->mIoHandle;
2805
Eric Laurent8f42ea12018-08-08 09:08:25 -07002806 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002807
Andy Hung39efb7a2018-09-26 15:39:28 -07002808 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002809
Andy Hung39efb7a2018-09-26 15:39:28 -07002810 if (inputDesc->getClientCount() > 0) {
2811 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002812 return;
2813 }
2814
Eric Laurent05b90f82014-08-27 15:32:29 -07002815 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002816 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002817 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002818}
2819
Eric Laurent8f42ea12018-08-08 09:08:25 -07002820void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002821{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002822 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002823
2824 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002825 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002826 }
2827}
2828
Eric Laurent8f42ea12018-08-08 09:08:25 -07002829void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2830{
2831 stopInput(portId);
2832 releaseInput(portId);
2833}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834
Eric Laurent0dd51852019-04-19 18:18:58 -07002835void AudioPolicyManager::checkCloseInputs() {
2836 // After connecting or disconnecting an input device, close input if:
2837 // - it has no client (was just opened to check profile) OR
2838 // - none of its supported devices are connected anymore OR
2839 // - one of its clients cannot be routed to one of its supported
2840 // devices anymore. Otherwise update device selection
2841 std::vector<audio_io_handle_t> inputsToClose;
2842 for (size_t i = 0; i < mInputs.size(); i++) {
2843 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2844 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002845 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002846 inputsToClose.push_back(mInputs.keyAt(i));
2847 } else {
2848 bool close = false;
2849 for (const auto& client : input->clientsList()) {
2850 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002851 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002852 if (!input->supportedDevices().contains(device)) {
2853 close = true;
2854 break;
2855 }
2856 }
2857 if (close) {
2858 inputsToClose.push_back(mInputs.keyAt(i));
2859 } else {
2860 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2861 }
2862 }
2863 }
2864
2865 for (const audio_io_handle_t handle : inputsToClose) {
2866 ALOGV("%s closing input %d", __func__, handle);
2867 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002868 }
Eric Laurentd4692962014-05-05 18:13:44 -07002869}
2870
François Gaffie251c7f02018-11-07 10:41:08 +01002871void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002872{
2873 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002874 if (indexMin < 0 || indexMax < 0) {
2875 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2876 return;
2877 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002878 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002879
2880 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002881 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2882 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002883 continue;
2884 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002885 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002886 }
Eric Laurente552edb2014-03-10 17:42:56 -07002887}
2888
Eric Laurente0720872014-03-11 09:30:41 -07002889status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002890 int index,
2891 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002892{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002893 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002894 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2895 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2896 return NO_ERROR;
2897 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002898 ALOGV("%s: stream %s attributes=%s", __func__,
2899 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002900 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002901}
2902
Eric Laurente0720872014-03-11 09:30:41 -07002903status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002904 int *index,
2905 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002906{
François Gaffiec005e562018-11-06 15:04:49 +01002907 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2908 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002909 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002910 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002911 deviceTypes = mEngine->getOutputDevicesForStream(
2912 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002913 }
jiabin9a3361e2019-10-01 09:38:30 -07002914 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002915}
2916
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002917status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002918 int index,
2919 audio_devices_t device)
2920{
2921 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002922 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2923 if (group == VOLUME_GROUP_NONE) {
2924 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002925 return BAD_VALUE;
2926 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002927 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002928 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002929 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002930 VolumeSource vs = toVolumeSource(group);
2931 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2932
2933 status = setVolumeCurveIndex(index, device, curves);
2934 if (status != NO_ERROR) {
2935 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2936 return status;
2937 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002938
jiabin9a3361e2019-10-01 09:38:30 -07002939 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002940 auto curCurvAttrs = curves.getAttributes();
2941 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2942 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002943 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002944 } else if (!curves.getStreamTypes().empty()) {
2945 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002946 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002947 } else {
2948 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2949 return BAD_VALUE;
2950 }
jiabin9a3361e2019-10-01 09:38:30 -07002951 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2952 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002953
François Gaffiecfe17322018-11-07 13:41:29 +01002954 // update volume on all outputs and streams matching the following:
2955 // - The requested stream (or a stream matching for volume control) is active on the output
2956 // - The device (or devices) selected by the engine for this stream includes
2957 // the requested device
2958 // - For non default requested device, currently selected device on the output is either the
2959 // requested device or one of the devices selected by the engine for this stream
2960 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2961 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002962 for (size_t i = 0; i < mOutputs.size(); i++) {
2963 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002964 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002965
jiabin9a3361e2019-10-01 09:38:30 -07002966 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2967 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002968 }
François Gaffieed91f582020-01-31 10:35:37 +01002969 if (!(desc->isActive(vs) || isInCall())) {
2970 continue;
2971 }
2972 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2973 curDevices.find(device) == curDevices.end()) {
2974 continue;
2975 }
2976 bool applyVolume = false;
2977 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2978 curSrcDevices.insert(device);
2979 applyVolume = (curSrcDevices.find(
2980 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2981 } else {
2982 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2983 }
2984 if (!applyVolume) {
2985 continue; // next output
2986 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002987 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2988 // If a higher priority strategy is active, and the output is routed to a device with a
2989 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002990 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002991 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02002992 // If the volume source is active with higher priority source, ensure at least Sw Muted
2993 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002994 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2995 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2996 false /*preferredDevice*/);
2997 if (activeClients.empty()) {
2998 continue;
2999 }
3000 bool isPreempted = false;
3001 bool isHigherPriority = productStrategy < strategy;
3002 for (const auto &client : activeClients) {
3003 if (isHigherPriority && (client->volumeSource() != vs)) {
3004 ALOGV("%s: Strategy=%d (\nrequester:\n"
3005 " group %d, volumeGroup=%d attributes=%s)\n"
3006 " higher priority source active:\n"
3007 " volumeGroup=%d attributes=%s) \n"
3008 " on output %zu, bailing out", __func__, productStrategy,
3009 group, group, toString(attributes).c_str(),
3010 client->volumeSource(), toString(client->attributes()).c_str(), i);
3011 applyVolume = false;
3012 isPreempted = true;
3013 break;
3014 }
3015 // However, continue for loop to ensure no higher prio clients running on output
3016 if (client->volumeSource() == vs) {
3017 applyVolume = true;
3018 }
3019 }
3020 if (isPreempted || applyVolume) {
3021 break;
3022 }
3023 }
3024 if (!applyVolume) {
3025 continue; // next output
3026 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003027 }
François Gaffieed91f582020-01-31 10:35:37 +01003028 //FIXME: workaround for truncated touch sounds
3029 // delayed volume change for system stream to be removed when the problem is
3030 // handled by system UI
3031 status_t volStatus = checkAndSetVolume(
3032 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003033 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003034 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3035 if (volStatus != NO_ERROR) {
3036 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003037 }
3038 }
François Gaffiecfe17322018-11-07 13:41:29 +01003039 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3040 return status;
3041}
3042
François Gaffieaaac0fd2018-11-22 17:56:39 +01003043status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003044 audio_devices_t device,
3045 IVolumeCurves &volumeCurves)
3046{
3047 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3048 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003049 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3050 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003051 (index > volumeCurves.getVolumeIndexMax())) {
3052 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3053 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3054 return BAD_VALUE;
3055 }
3056 if (!audio_is_output_device(device)) {
3057 return BAD_VALUE;
3058 }
3059
3060 // Force max volume if stream cannot be muted
3061 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3062
François Gaffieaaac0fd2018-11-22 17:56:39 +01003063 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003064 volumeCurves.addCurrentVolumeIndex(device, index);
3065 return NO_ERROR;
3066}
3067
3068status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3069 int &index,
3070 audio_devices_t device)
3071{
3072 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3073 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003074 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003075 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003076 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3077 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003078 }
jiabin9a3361e2019-10-01 09:38:30 -07003079 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003080}
3081
3082status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3083 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003084 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003085{
jiabin9a3361e2019-10-01 09:38:30 -07003086 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003087 return BAD_VALUE;
3088 }
jiabin9a3361e2019-10-01 09:38:30 -07003089 index = curves.getVolumeIndex(deviceTypes);
3090 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003091 return NO_ERROR;
3092}
3093
3094status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3095 int &index)
3096{
3097 index = getVolumeCurves(attr).getVolumeIndexMin();
3098 return NO_ERROR;
3099}
3100
3101status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3102 int &index)
3103{
3104 index = getVolumeCurves(attr).getVolumeIndexMax();
3105 return NO_ERROR;
3106}
3107
Eric Laurent36829f92017-04-07 19:04:42 -07003108audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003109{
3110 // select one output among several suitable for global effects.
3111 // The priority is as follows:
3112 // 1: An offloaded output. If the effect ends up not being offloadable,
3113 // AudioFlinger will invalidate the track and the offloaded output
3114 // will be closed causing the effect to be moved to a PCM output.
3115 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003116 // 3: The primary output
3117 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003118
François Gaffiec005e562018-11-06 15:04:49 +01003119 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3120 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003121 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003122
Eric Laurent36829f92017-04-07 19:04:42 -07003123 if (outputs.size() == 0) {
3124 return AUDIO_IO_HANDLE_NONE;
3125 }
Eric Laurente552edb2014-03-10 17:42:56 -07003126
Eric Laurent36829f92017-04-07 19:04:42 -07003127 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3128 bool activeOnly = true;
3129
3130 while (output == AUDIO_IO_HANDLE_NONE) {
3131 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3132 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3133 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3134
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003135 for (audio_io_handle_t output : outputs) {
3136 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003137 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003138 continue;
3139 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003140 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3141 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003142 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003143 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003144 }
3145 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003146 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003147 }
3148 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003149 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003150 }
3151 }
3152 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3153 output = outputOffloaded;
3154 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3155 output = outputDeepBuffer;
3156 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3157 output = outputPrimary;
3158 } else {
3159 output = outputs[0];
3160 }
3161 activeOnly = false;
3162 }
3163
3164 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003165 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003166 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3167 mMusicEffectOutput = output;
3168 }
3169
3170 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003171 return output;
3172}
3173
Eric Laurent36829f92017-04-07 19:04:42 -07003174audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3175{
3176 return selectOutputForMusicEffects();
3177}
3178
Eric Laurente0720872014-03-11 09:30:41 -07003179status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003180 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003181 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003182 int session,
3183 int id)
3184{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003185 if (session != AUDIO_SESSION_DEVICE) {
3186 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003187 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003188 index = mInputs.indexOfKey(io);
3189 if (index < 0) {
3190 ALOGW("registerEffect() unknown io %d", io);
3191 return INVALID_OPERATION;
3192 }
Eric Laurente552edb2014-03-10 17:42:56 -07003193 }
3194 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003195 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3196 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3197 || strategy == PRODUCT_STRATEGY_NONE));
3198 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003199}
3200
Eric Laurentc241b0d2018-11-28 09:08:49 -08003201status_t AudioPolicyManager::unregisterEffect(int id)
3202{
3203 if (mEffects.getEffect(id) == nullptr) {
3204 return INVALID_OPERATION;
3205 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003206 if (mEffects.isEffectEnabled(id)) {
3207 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3208 setEffectEnabled(id, false);
3209 }
3210 return mEffects.unregisterEffect(id);
3211}
3212
3213status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3214{
3215 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3216 if (effect == nullptr) {
3217 return INVALID_OPERATION;
3218 }
3219
3220 status_t status = mEffects.setEffectEnabled(id, enabled);
3221 if (status == NO_ERROR) {
3222 mInputs.trackEffectEnabled(effect, enabled);
3223 }
3224 return status;
3225}
3226
Eric Laurent6c796322019-04-09 14:13:17 -07003227
3228status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3229{
3230 mEffects.moveEffects(ids, io);
3231 return NO_ERROR;
3232}
3233
Eric Laurentc75307b2015-03-17 15:29:32 -07003234bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3235{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003236 auto vs = toVolumeSource(stream, false);
3237 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003238}
3239
3240bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3241{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003242 auto vs = toVolumeSource(stream, false);
3243 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003244}
3245
Eric Laurente0720872014-03-11 09:30:41 -07003246bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003247{
3248 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003249 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003250 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003251 return true;
3252 }
3253 }
3254 return false;
3255}
3256
Eric Laurent275e8e92014-11-30 15:14:47 -08003257// Register a list of custom mixes with their attributes and format.
3258// When a mix is registered, corresponding input and output profiles are
3259// added to the remote submix hw module. The profile contains only the
3260// parameters (sampling rate, format...) specified by the mix.
3261// The corresponding input remote submix device is also connected.
3262//
3263// When a remote submix device is connected, the address is checked to select the
3264// appropriate profile and the corresponding input or output stream is opened.
3265//
3266// When capture starts, getInputForAttr() will:
3267// - 1 look for a mix matching the address passed in attribtutes tags if any
3268// - 2 if none found, getDeviceForInputSource() will:
3269// - 2.1 look for a mix matching the attributes source
3270// - 2.2 if none found, default to device selection by policy rules
3271// At this time, the corresponding output remote submix device is also connected
3272// and active playback use cases can be transferred to this mix if needed when reconnecting
3273// after AudioTracks are invalidated
3274//
3275// When playback starts, getOutputForAttr() will:
3276// - 1 look for a mix matching the address passed in attribtutes tags if any
3277// - 2 if none found, look for a mix matching the attributes usage
3278// - 3 if none found, default to device and output selection by policy rules.
3279
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003280status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003281{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003282 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3283 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003284 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003285 sp<HwModule> rSubmixModule;
3286 // examine each mix's route type
3287 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003288 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003289 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3290 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3291 ALOGE("Unsupported Policy Mix %zu of %zu: "
3292 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3293 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003294 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003295 break;
3296 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003297 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3298 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003299 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003300 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3301 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003302 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003303 rSubmixModule = mHwModules.getModuleFromName(
3304 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3305 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003306 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003307 i);
3308 res = INVALID_OPERATION;
3309 break;
3310 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003311 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003312
Eric Laurent97ac8712018-07-27 18:59:02 -07003313 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003314 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003315 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003316 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003317 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3318 } else {
3319 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3320 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003321 }
François Gaffie036e1e92015-03-19 10:16:24 +01003322
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003323 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003324 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003325 res = INVALID_OPERATION;
3326 break;
3327 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003328 audio_config_t outputConfig = mix.mFormat;
3329 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003330 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3331 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003332 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3333 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003334 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003335 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003336 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003337 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003338
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003339 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003340 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3341 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3342 ALOGE("Failed to set remote submix device available, type %u, address %s",
3343 mix.mDeviceType, address.string());
3344 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003345 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003346 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3347 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003348 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003349 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003350 i, mixes.size(), type, address.string());
3351
3352 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3353 mix.mDeviceType, mix.mDeviceAddress,
3354 String8(), AUDIO_FORMAT_DEFAULT);
3355 if (device == nullptr) {
3356 res = INVALID_OPERATION;
3357 break;
3358 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003359
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003360 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003361 // First try to find an already opened output supporting the device
3362 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003363 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003364
Eric Laurentc529cf62020-04-17 18:19:10 -07003365 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003366 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003367 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3368 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003369 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003370 } else {
3371 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003372 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003373 }
3374 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003375 // If no output found, try to find a direct output profile supporting the device
3376 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3377 sp<HwModule> module = mHwModules[i];
3378 for (size_t j = 0;
3379 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3380 j++) {
3381 sp<IOProfile> profile = module->getOutputProfiles()[j];
3382 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3383 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3384 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3385 address.string());
3386 res = INVALID_OPERATION;
3387 } else {
3388 foundOutput = true;
3389 }
3390 }
3391 }
3392 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003393 if (res != NO_ERROR) {
3394 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003395 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003396 res = INVALID_OPERATION;
3397 break;
3398 } else if (!foundOutput) {
3399 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003400 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003401 res = INVALID_OPERATION;
3402 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003403 } else {
3404 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003405 }
Eric Laurentc722f302014-12-10 11:21:49 -08003406 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003407 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003408 if (res != NO_ERROR) {
3409 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003410 } else if (checkOutputs) {
3411 checkForDeviceAndOutputChanges();
3412 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003413 }
3414 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003415}
3416
3417status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3418{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003419 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003420 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003421 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003422 sp<HwModule> rSubmixModule;
3423 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003424 for (const auto& mix : mixes) {
3425 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003426
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003427 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003428 rSubmixModule = mHwModules.getModuleFromName(
3429 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3430 if (rSubmixModule == 0) {
3431 res = INVALID_OPERATION;
3432 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003433 }
3434 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003435
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003436 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003437
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003438 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003439 res = INVALID_OPERATION;
3440 continue;
3441 }
3442
Kevin Rocard04ed0462019-05-02 17:53:24 -07003443 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3444 if (getDeviceConnectionState(device, address.string()) ==
3445 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3446 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3447 address.string(), "remote-submix",
3448 AUDIO_FORMAT_DEFAULT);
3449 if (res != OK) {
3450 ALOGE("Error making RemoteSubmix device unavailable for mix "
3451 "with type %d, address %s", device, address.string());
3452 }
3453 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003454 }
jiabin5740f082019-08-19 15:08:30 -07003455 rSubmixModule->removeOutputProfile(address.c_str());
3456 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003457
Kevin Rocard153f92d2018-12-18 18:33:28 -08003458 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003459 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003460 res = INVALID_OPERATION;
3461 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003462 } else {
3463 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003464 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003465 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003466 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003467 if (res == NO_ERROR && checkOutputs) {
3468 checkForDeviceAndOutputChanges();
3469 updateCallAndOutputRouting();
3470 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003471 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003472}
3473
Mikhail Naganov100f0122018-11-29 11:22:16 -08003474void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3475{
3476 size_t i = 0;
3477 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3478 for (const auto& fmt : mManualSurroundFormats) {
3479 if (i++ != 0) dst->append(", ");
3480 std::string sfmt;
3481 FormatConverter::toString(fmt, sfmt);
3482 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3483 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3484 }
3485}
3486
Eric Laurentc529cf62020-04-17 18:19:10 -07003487// Returns true if all devices types match the predicate and are supported by one HW module
3488bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003489 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003490 std::function<bool(audio_devices_t)> predicate,
3491 const char *context) {
3492 for (size_t i = 0; i < devices.size(); i++) {
3493 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003494 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003495 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003496 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003497 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003498 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003499 return false;
3500 }
3501 }
3502 return true;
3503}
3504
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003505status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003506 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003507 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003508 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3509 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003510 }
3511 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003512 if (res != NO_ERROR) {
3513 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3514 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003515 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003516
3517 checkForDeviceAndOutputChanges();
3518 updateCallAndOutputRouting();
3519
3520 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003521}
3522
3523status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3524 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003525 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3526 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003527 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003528 __FUNCTION__, uid);
3529 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003530 }
3531
Eric Laurentc529cf62020-04-17 18:19:10 -07003532 checkForDeviceAndOutputChanges();
3533 updateCallAndOutputRouting();
3534
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003535 return res;
3536}
3537
Eric Laurent2517af32020-11-25 15:31:27 +01003538
jiabin0a488932020-08-07 17:32:40 -07003539status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3540 device_role_t role,
3541 const AudioDeviceTypeAddrVector &devices) {
3542 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3543 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003544
Eric Laurentc529cf62020-04-17 18:19:10 -07003545 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003546 return BAD_VALUE;
3547 }
jiabin0a488932020-08-07 17:32:40 -07003548 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003549 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003550 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3551 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003552 return status;
3553 }
3554
3555 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003556
3557 bool forceVolumeReeval = false;
3558 // FIXME: workaround for truncated touch sounds
3559 // to be removed when the problem is handled by system UI
3560 uint32_t delayMs = 0;
3561 if (strategy == mCommunnicationStrategy) {
3562 forceVolumeReeval = true;
3563 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3564 updateInputRouting();
3565 }
3566 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003567
3568 return NO_ERROR;
3569}
3570
3571void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3572{
3573 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003574 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003575 // Only apply special touch sound delay once
3576 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003577 }
3578 for (size_t i = 0; i < mOutputs.size(); i++) {
3579 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3580 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003581 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3582 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003583 // As done in setDeviceConnectionState, we could also fix default device issue by
3584 // preventing the force re-routing in case of default dev that distinguishes on address.
3585 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003586 bool forceRouting = !newDevices.isEmpty();
3587 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3588 true /*requiresMuteCheck*/,
3589 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003590 // Only apply special touch sound delay once
3591 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003592 }
3593 if (forceVolumeReeval && !newDevices.isEmpty()) {
3594 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3595 }
3596 }
3597}
3598
Eric Laurent2517af32020-11-25 15:31:27 +01003599void AudioPolicyManager::updateInputRouting() {
3600 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303601 // Skip for hotword recording as the input device switch
3602 // is handled within sound trigger HAL
3603 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3604 continue;
3605 }
Eric Laurent2517af32020-11-25 15:31:27 +01003606 auto newDevice = getNewInputDevice(activeDesc);
3607 // Force new input selection if the new device can not be reached via current input
3608 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3609 setInputDevice(activeDesc->mIoHandle, newDevice);
3610 } else {
3611 closeInput(activeDesc->mIoHandle);
3612 }
3613 }
3614}
3615
jiabin0a488932020-08-07 17:32:40 -07003616status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3617 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003618{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003619 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003620
jiabin0a488932020-08-07 17:32:40 -07003621 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003622 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003623 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3624 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003625 return status;
3626 }
3627
3628 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003629
3630 bool forceVolumeReeval = false;
3631 // FIXME: workaround for truncated touch sounds
3632 // to be removed when the problem is handled by system UI
3633 uint32_t delayMs = 0;
3634 if (strategy == mCommunnicationStrategy) {
3635 forceVolumeReeval = true;
3636 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3637 updateInputRouting();
3638 }
3639 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003640
3641 return NO_ERROR;
3642}
3643
jiabin0a488932020-08-07 17:32:40 -07003644status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3645 device_role_t role,
3646 AudioDeviceTypeAddrVector &devices) {
3647 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003648}
3649
Jiabin Huang3b98d322020-09-03 17:54:16 +00003650status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3651 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3652 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3653 dumpAudioDeviceTypeAddrVector(devices).c_str());
3654
Mikhail Naganov55773032020-10-01 15:08:13 -07003655 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003656 return BAD_VALUE;
3657 }
3658 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3659 ALOGW_IF(status != NO_ERROR,
3660 "Engine could not set preferred devices %s for audio source %d role %d",
3661 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3662
3663 return status;
3664}
3665
3666status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3667 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3668 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3669 dumpAudioDeviceTypeAddrVector(devices).c_str());
3670
Mikhail Naganov55773032020-10-01 15:08:13 -07003671 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003672 return BAD_VALUE;
3673 }
3674 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3675 ALOGW_IF(status != NO_ERROR,
3676 "Engine could not add preferred devices %s for audio source %d role %d",
3677 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3678
Eric Laurent2517af32020-11-25 15:31:27 +01003679 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003680 return status;
3681}
3682
3683status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3684 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3685{
3686 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3687 dumpAudioDeviceTypeAddrVector(devices).c_str());
3688
Mikhail Naganov55773032020-10-01 15:08:13 -07003689 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003690 return BAD_VALUE;
3691 }
3692
3693 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3694 audioSource, role, devices);
3695 ALOGW_IF(status != NO_ERROR,
3696 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3697
Eric Laurent2517af32020-11-25 15:31:27 +01003698 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003699 return status;
3700}
3701
3702status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3703 device_role_t role) {
3704 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3705
3706 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3707 ALOGW_IF(status != NO_ERROR,
3708 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3709
Eric Laurent2517af32020-11-25 15:31:27 +01003710 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003711 return status;
3712}
3713
3714status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3715 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3716 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3717}
3718
Oscar Azucena90e77632019-11-27 17:12:28 -08003719status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003720 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003721 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003722 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3723 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003724 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003725 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3726 if (status != NO_ERROR) {
3727 ALOGE("%s() could not set device affinity for userId %d",
3728 __FUNCTION__, userId);
3729 return status;
3730 }
3731
3732 // reevaluate outputs for all devices
3733 checkForDeviceAndOutputChanges();
3734 updateCallAndOutputRouting();
3735
3736 return NO_ERROR;
3737}
3738
3739status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003740 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003741 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3742 if (status != NO_ERROR) {
3743 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3744 __FUNCTION__, userId);
3745 return status;
3746 }
3747
3748 // reevaluate outputs for all devices
3749 checkForDeviceAndOutputChanges();
3750 updateCallAndOutputRouting();
3751
3752 return NO_ERROR;
3753}
3754
Andy Hungc29d82b2018-10-05 12:23:17 -07003755void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003756{
Andy Hungc29d82b2018-10-05 12:23:17 -07003757 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003758 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003759 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003760 std::string stateLiteral;
3761 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003762 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003763 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3764 "communications", "media", "record", "dock", "system",
3765 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3766 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3767 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003768 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3769 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3770 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3771 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3772 dst->append(" (MANUAL: ");
3773 dumpManualSurroundFormats(dst);
3774 dst->append(")");
3775 }
3776 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003777 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003778 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3779 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003780 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003781 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003782
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003783 dst->append("\n");
3784 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3785 dst->append("\n");
3786 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003787 mHwModulesAll.dump(dst);
3788 mOutputs.dump(dst);
3789 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003790 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003791 mAudioPatches.dump(dst);
3792 mPolicyMixes.dump(dst);
3793 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003794
Kevin Rocardb99cc752019-03-21 20:52:24 -07003795 dst->appendFormat(" AllowedCapturePolicies:\n");
3796 for (auto& policy : mAllowedCapturePolicies) {
3797 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3798 }
3799
François Gaffiec005e562018-11-06 15:04:49 +01003800 dst->appendFormat("\nPolicy Engine dump:\n");
3801 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003802}
3803
3804status_t AudioPolicyManager::dump(int fd)
3805{
3806 String8 result;
3807 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003808 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003809 return NO_ERROR;
3810}
3811
Kevin Rocardb99cc752019-03-21 20:52:24 -07003812status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3813{
3814 mAllowedCapturePolicies[uid] = capturePolicy;
3815 return NO_ERROR;
3816}
3817
Eric Laurente552edb2014-03-10 17:42:56 -07003818// This function checks for the parameters which can be offloaded.
3819// This can be enhanced depending on the capability of the DSP and policy
3820// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003821audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003822{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003823 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003824 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003825 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003826 offloadInfo.format,
3827 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3828 offloadInfo.has_video);
3829
jiabin2b9d5a12021-12-10 01:06:29 +00003830 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003831 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003832 }
3833
3834 // See if there is a profile to support this.
3835 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003836 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003837 offloadInfo.sample_rate,
3838 offloadInfo.format,
3839 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003840 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3841 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003842 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3843 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3844 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003845 if (profile == nullptr) {
3846 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3847 }
3848 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3849 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3850 }
3851 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003852}
3853
Michael Chana94fbb22018-04-24 14:31:19 +10003854bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3855 const audio_attributes_t& attributes) {
3856 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003857 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003858 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3859 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003860 config.sample_rate,
3861 config.format,
3862 config.channel_mask,
3863 output_flags,
3864 true /* directOnly */);
3865 ALOGV("%s() profile %sfound with name: %s, "
3866 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3867 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003868 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003869 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003870
3871 // also try the MSD module if compatible profile not found
3872 if (profile == nullptr) {
3873 profile = getMsdProfileForOutput(outputDevices,
3874 config.sample_rate,
3875 config.format,
3876 config.channel_mask,
3877 output_flags,
3878 true /* directOnly */);
3879 ALOGV("%s() MSD profile %sfound with name: %s, "
3880 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3881 __FUNCTION__, profile != 0 ? "" : "NOT ",
3882 (profile != 0 ? profile->getTagName().c_str() : "null"),
3883 config.sample_rate, config.format, config.channel_mask, output_flags);
3884 }
3885 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003886}
3887
jiabin2b9d5a12021-12-10 01:06:29 +00003888bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3889 bool durationIgnored) {
3890 if (mMasterMono) {
3891 return false; // no offloading if mono is set.
3892 }
3893
3894 // Check if offload has been disabled
3895 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3896 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3897 return false;
3898 }
3899
3900 // Check if stream type is music, then only allow offload as of now.
3901 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3902 {
3903 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3904 return false;
3905 }
3906
3907 //TODO: enable audio offloading with video when ready
3908 const bool allowOffloadWithVideo =
3909 property_get_bool("audio.offload.video", false /* default_value */);
3910 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3911 ALOGV("%s: has_video == true, returning false", __func__);
3912 return false;
3913 }
3914
3915 //If duration is less than minimum value defined in property, return false
3916 const int min_duration_secs = property_get_int32(
3917 "audio.offload.min.duration.secs", -1 /* default_value */);
3918 if (!durationIgnored) {
3919 if (min_duration_secs >= 0) {
3920 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3921 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3922 __func__, min_duration_secs);
3923 return false;
3924 }
3925 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3926 ALOGV("%s: Offload denied by duration < default min(=%u)",
3927 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3928 return false;
3929 }
3930 }
3931
3932 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3933 // creating an offloaded track and tearing it down immediately after start when audioflinger
3934 // detects there is an active non offloadable effect.
3935 // FIXME: We should check the audio session here but we do not have it in this context.
3936 // This may prevent offloading in rare situations where effects are left active by apps
3937 // in the background.
3938 if (mEffects.isNonOffloadableEffectEnabled()) {
3939 return false;
3940 }
3941
3942 return true;
3943}
3944
3945audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
3946 const audio_config_t *config) {
3947 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
3948 offloadInfo.format = config->format;
3949 offloadInfo.sample_rate = config->sample_rate;
3950 offloadInfo.channel_mask = config->channel_mask;
3951 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
3952 offloadInfo.has_video = false;
3953 offloadInfo.is_streaming = false;
3954 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
3955
3956 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
3957 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3958 audio_flags_to_audio_output_flags(attr->flags, &flags);
3959 // only retain flags that will drive compressed offload or passthrough
3960 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
3961 if (offloadPossible) {
3962 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
3963 }
3964 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
3965
Dorin Drimusfae3c642022-03-17 18:36:30 +01003966 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00003967 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01003968 DeviceVector outputDevices = engineOutputDevices;
3969 // the MSD module checks for different conditions and output devices
3970 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
3971 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
3972 continue;
3973 }
3974 outputDevices = getMsdAudioOutDevices();
3975 }
jiabin2b9d5a12021-12-10 01:06:29 +00003976 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00003977 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00003978 config->sample_rate, nullptr /*updatedSamplingRate*/,
3979 config->format, nullptr /*updatedFormat*/,
3980 config->channel_mask, nullptr /*updatedChannelMask*/,
3981 flags)) {
3982 continue;
3983 }
3984 // reject profiles not corresponding to a device currently available
3985 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
3986 continue;
3987 }
3988 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
3989 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00003990 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00003991 != AUDIO_DIRECT_NOT_SUPPORTED) {
3992 // Already reports offload gapless supported. No need to report offload support.
3993 continue;
3994 }
3995 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
3996 != AUDIO_OUTPUT_FLAG_NONE) {
3997 // If offload gapless is reported, no need to report offload support.
3998 directMode = (audio_direct_mode_t) ((directMode &
3999 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4000 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4001 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004002 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004003 }
4004 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004005 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004006 }
4007 }
4008 }
4009 return directMode;
4010}
4011
Dorin Drimusf2196d82022-01-03 12:11:18 +01004012status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4013 AudioProfileVector& audioProfilesVector) {
4014 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004015 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004016 if (status != OK) {
4017 return status;
4018 }
4019 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4020 if (devices.empty()) {
4021 return OK; // no output devices for the attributes
4022 }
4023
4024 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004025 // the MSD module checks for different conditions
4026 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4027 continue;
4028 }
4029 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4030 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004031 continue;
4032 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004033 // allow only profiles that support all the available and routed devices
4034 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004035 != devices.size()) {
4036 continue;
4037 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004038 audioProfilesVector.addAllValidProfiles(
4039 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004040 }
4041 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004042
4043 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4044 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4045 if (msdModule != nullptr) {
4046 if (msdHasPatchesToAllDevices(devices)) {
4047 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4048 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4049 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4050 continue;
4051 }
4052 audioProfilesVector.addAllValidProfiles(
4053 outputProfile->asAudioPort()->getAudioProfiles());
4054 }
4055 } else {
4056 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4057 }
4058 }
4059
Dorin Drimusf2196d82022-01-03 12:11:18 +01004060 return NO_ERROR;
4061}
4062
Eric Laurent6a94d692014-05-20 11:18:06 -07004063status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4064 audio_port_type_t type,
4065 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004066 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004067 unsigned int *generation)
4068{
jiabin19cdba52020-11-24 11:28:58 -08004069 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4070 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004071 return BAD_VALUE;
4072 }
4073 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004074 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004075 *num_ports = 0;
4076 }
4077
4078 size_t portsWritten = 0;
4079 size_t portsMax = *num_ports;
4080 *num_ports = 0;
4081 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004082 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4083 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004084 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004085 for (const auto& dev : mAvailableOutputDevices) {
4086 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004087 continue;
4088 }
4089 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004090 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004091 }
4092 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004093 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004094 }
4095 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004096 for (const auto& dev : mAvailableInputDevices) {
4097 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004098 continue;
4099 }
4100 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004101 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004102 }
4103 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004104 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004105 }
4106 }
4107 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4108 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4109 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4110 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4111 }
4112 *num_ports += mInputs.size();
4113 }
4114 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004115 size_t numOutputs = 0;
4116 for (size_t i = 0; i < mOutputs.size(); i++) {
4117 if (!mOutputs[i]->isDuplicated()) {
4118 numOutputs++;
4119 if (portsWritten < portsMax) {
4120 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4121 }
4122 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004123 }
Eric Laurent84c70242014-06-23 08:46:27 -07004124 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004125 }
4126 }
4127 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004128 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004129 return NO_ERROR;
4130}
4131
jiabin19cdba52020-11-24 11:28:58 -08004132status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004133{
Eric Laurent99fcae42018-05-17 16:59:18 -07004134 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4135 return BAD_VALUE;
4136 }
4137 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4138 if (dev != 0) {
4139 dev->toAudioPort(port);
4140 return NO_ERROR;
4141 }
4142 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4143 if (dev != 0) {
4144 dev->toAudioPort(port);
4145 return NO_ERROR;
4146 }
4147 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4148 if (out != 0) {
4149 out->toAudioPort(port);
4150 return NO_ERROR;
4151 }
4152 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4153 if (in != 0) {
4154 in->toAudioPort(port);
4155 return NO_ERROR;
4156 }
4157 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004158}
4159
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004160status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4161 audio_patch_handle_t *handle,
4162 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004163{
François Gaffieafd4cea2019-11-18 15:50:22 +01004164 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004165 if (handle == NULL || patch == NULL) {
4166 return BAD_VALUE;
4167 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004168 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004169 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004170 return BAD_VALUE;
4171 }
4172 // only one source per audio patch supported for now
4173 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004174 return INVALID_OPERATION;
4175 }
Eric Laurent874c42872014-08-08 15:13:39 -07004176 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004177 return INVALID_OPERATION;
4178 }
Eric Laurent874c42872014-08-08 15:13:39 -07004179 for (size_t i = 0; i < patch->num_sinks; i++) {
4180 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4181 return INVALID_OPERATION;
4182 }
4183 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004184
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004185 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4186 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4187 if (srcDevice == nullptr || sinkDevice == nullptr) {
4188 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4189 return BAD_VALUE;
4190 }
4191 ALOGV("%s between source %s and sink %s", __func__,
4192 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4193 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4194 // Default attributes, default volume priority, not to infer with non raw audio patches.
4195 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4196 const struct audio_port_config *source = &patch->sources[0];
4197 sp<SourceClientDescriptor> sourceDesc =
4198 new InternalSourceClientDescriptor(
4199 portId, uid, attributes, *source, srcDevice, sinkDevice,
4200 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4201
4202 status_t status =
4203 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4204
4205 if (status != NO_ERROR) {
4206 return INVALID_OPERATION;
4207 }
4208 mAudioSources.add(portId, sourceDesc);
4209 return NO_ERROR;
4210}
4211
4212status_t AudioPolicyManager::connectAudioSourceToSink(
4213 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4214 const struct audio_patch *patch,
4215 audio_patch_handle_t &handle,
4216 uid_t uid, uint32_t delayMs)
4217{
4218 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4219 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4220 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4221 return INVALID_OPERATION;
4222 }
4223 sourceDesc->connect(handle, sinkDevice);
4224 if (isMsdPatch(handle)) {
4225 return NO_ERROR;
4226 }
4227 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4228 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4229 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4230 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4231 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4232 goto FailurePatchAdded;
4233 }
4234 status = swOutput->start();
4235 if (status != NO_ERROR) {
4236 goto FailureSourceAdded;
4237 }
4238 swOutput->addClient(sourceDesc);
4239 status = startSource(swOutput, sourceDesc, &delayMs);
4240 if (status != NO_ERROR) {
4241 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4242 goto FailureSourceActive;
4243 }
4244 if (delayMs != 0) {
4245 usleep(delayMs * 1000);
4246 }
4247 return NO_ERROR;
4248
4249FailureSourceActive:
4250 swOutput->stop();
4251 releaseOutput(sourceDesc->portId());
4252FailureSourceAdded:
4253 sourceDesc->setSwOutput(nullptr);
4254FailurePatchAdded:
4255 releaseAudioPatchInternal(handle);
4256 return INVALID_OPERATION;
4257}
4258
4259status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4260 audio_patch_handle_t *handle,
4261 uid_t uid, uint32_t delayMs,
4262 const sp<SourceClientDescriptor>& sourceDesc)
4263{
4264 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004265 sp<AudioPatch> patchDesc;
4266 ssize_t index = mAudioPatches.indexOfKey(*handle);
4267
François Gaffieafd4cea2019-11-18 15:50:22 +01004268 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4269 patch->sources[0].role,
4270 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004271#if LOG_NDEBUG == 0
4272 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004273 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4274 patch->sinks[i].role,
4275 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004276 }
4277#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004278
4279 if (index >= 0) {
4280 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004281 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4282 __func__, mUidCached, patchDesc->getUid(), uid);
4283 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004284 return INVALID_OPERATION;
4285 }
4286 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004287 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004288 }
4289
4290 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004291 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004292 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004293 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004294 return BAD_VALUE;
4295 }
Eric Laurent84c70242014-06-23 08:46:27 -07004296 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4297 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004298 if (patchDesc != 0) {
4299 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004300 ALOGV("%s source id differs for patch current id %d new id %d",
4301 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004302 return BAD_VALUE;
4303 }
4304 }
Eric Laurent874c42872014-08-08 15:13:39 -07004305 DeviceVector devices;
4306 for (size_t i = 0; i < patch->num_sinks; i++) {
4307 // Only support mix to devices connection
4308 // TODO add support for mix to mix connection
4309 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004310 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004311 return INVALID_OPERATION;
4312 }
4313 sp<DeviceDescriptor> devDesc =
4314 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4315 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004316 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004317 return BAD_VALUE;
4318 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004319
François Gaffie11d30102018-11-02 16:09:09 +01004320 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004321 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004322 NULL, // updatedSamplingRate
4323 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004324 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004325 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004326 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004327 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004328 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004329 return INVALID_OPERATION;
4330 }
4331 devices.add(devDesc);
4332 }
4333 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004334 return INVALID_OPERATION;
4335 }
Eric Laurent874c42872014-08-08 15:13:39 -07004336
Eric Laurent6a94d692014-05-20 11:18:06 -07004337 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004338 ALOGV("%s setting device %s on output %d",
4339 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004340 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004341 index = mAudioPatches.indexOfKey(*handle);
4342 if (index >= 0) {
4343 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004344 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004345 }
4346 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004347 patchDesc->setUid(uid);
4348 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004349 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004350 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004351 return INVALID_OPERATION;
4352 }
4353 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4354 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4355 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004356 // only one sink supported when connecting an input device to a mix
4357 if (patch->num_sinks > 1) {
4358 return INVALID_OPERATION;
4359 }
François Gaffie53615e22015-03-19 09:24:12 +01004360 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004361 if (inputDesc == NULL) {
4362 return BAD_VALUE;
4363 }
4364 if (patchDesc != 0) {
4365 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4366 return BAD_VALUE;
4367 }
4368 }
François Gaffie11d30102018-11-02 16:09:09 +01004369 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004370 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004371 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004372 return BAD_VALUE;
4373 }
4374
François Gaffie11d30102018-11-02 16:09:09 +01004375 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004376 patch->sinks[0].sample_rate,
4377 NULL, /*updatedSampleRate*/
4378 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004379 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004380 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004381 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004382 // FIXME for the parameter type,
4383 // and the NONE
4384 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004385 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004386 return INVALID_OPERATION;
4387 }
4388 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004389 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004390 device->toString().c_str(), inputDesc->mIoHandle);
4391 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004392 index = mAudioPatches.indexOfKey(*handle);
4393 if (index >= 0) {
4394 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004395 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004396 }
4397 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004398 patchDesc->setUid(uid);
4399 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004400 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004401 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004402 return INVALID_OPERATION;
4403 }
4404 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4405 // device to device connection
4406 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004407 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004408 return BAD_VALUE;
4409 }
4410 }
François Gaffie11d30102018-11-02 16:09:09 +01004411 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004412 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004413 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004414 return BAD_VALUE;
4415 }
Eric Laurent874c42872014-08-08 15:13:39 -07004416
Eric Laurent6a94d692014-05-20 11:18:06 -07004417 //update source and sink with our own data as the data passed in the patch may
4418 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004419 PatchBuilder patchBuilder;
4420 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004421
4422 // if first sink is to MSD, establish single MSD patch
4423 if (getMsdAudioOutDevices().contains(
4424 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4425 ALOGV("%s patching to MSD", __FUNCTION__);
4426 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4427 goto installPatch;
4428 }
4429
François Gaffieafd4cea2019-11-18 15:50:22 +01004430 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4431 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004432
Eric Laurent874c42872014-08-08 15:13:39 -07004433 for (size_t i = 0; i < patch->num_sinks; i++) {
4434 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004435 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004436 return INVALID_OPERATION;
4437 }
François Gaffie11d30102018-11-02 16:09:09 +01004438 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004439 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004440 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004441 return BAD_VALUE;
4442 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004443 audio_port_config sinkPortConfig = {};
4444 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4445 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004446
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004447 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4448 // volume management purpose (tracking activity)
4449 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4450 // in config XML to reach the sink so that is can be declared as available.
4451 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4452 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004453 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004454 // take care of dynamic routing for SwOutput selection,
4455 audio_attributes_t attributes = sourceDesc->attributes();
4456 audio_stream_type_t stream = sourceDesc->stream();
4457 audio_attributes_t resultAttr;
4458 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4459 config.sample_rate = sourceDesc->config().sample_rate;
4460 config.channel_mask = sourceDesc->config().channel_mask;
4461 config.format = sourceDesc->config().format;
4462 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4463 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4464 bool isRequestedDeviceForExclusiveUse = false;
4465 output_type_t outputType;
4466 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4467 &stream, sourceDesc->uid(), &config, &flags,
4468 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4469 nullptr, &outputType);
4470 if (output == AUDIO_IO_HANDLE_NONE) {
4471 ALOGV("%s no output for device %s",
4472 __FUNCTION__, sinkDevice->toString().c_str());
4473 return INVALID_OPERATION;
4474 }
4475 outputDesc = mOutputs.valueFor(output);
4476 if (outputDesc->isDuplicated()) {
4477 ALOGE("%s output is duplicated", __func__);
4478 return INVALID_OPERATION;
4479 }
4480 sourceDesc->setSwOutput(outputDesc);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004481 } else {
4482 // Same for "raw patches" aka created from createAudioPatch API
4483 SortedVector<audio_io_handle_t> outputs =
4484 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4485 // if the sink device is reachable via an opened output stream, request to
4486 // go via this output stream by adding a second source to the patch
4487 // description
4488 output = selectOutput(outputs);
4489 if (output == AUDIO_IO_HANDLE_NONE) {
4490 ALOGE("%s no output available for internal patch sink", __func__);
4491 return INVALID_OPERATION;
4492 }
4493 outputDesc = mOutputs.valueFor(output);
4494 if (outputDesc->isDuplicated()) {
4495 ALOGV("%s output for device %s is duplicated",
4496 __func__, sinkDevice->toString().c_str());
4497 return INVALID_OPERATION;
4498 }
4499 sourceDesc->setSwOutput(outputDesc);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004500 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004501 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004502 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004503 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004504 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004505 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4506 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004507 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4508 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004509 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004510 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004511 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004512 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004513 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004514 return INVALID_OPERATION;
4515 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004516 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004517 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004518 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004519 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004520 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004521 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4522 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4523 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004524 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004525 }
Eric Laurent83b88082014-06-20 18:31:16 -07004526 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004527 }
4528 // TODO: check from routing capabilities in config file and other conflicting patches
4529
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004530installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004531 status_t status = installPatch(
4532 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004533 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004534 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004535 return INVALID_OPERATION;
4536 }
4537 } else {
4538 return BAD_VALUE;
4539 }
4540 } else {
4541 return BAD_VALUE;
4542 }
4543 return NO_ERROR;
4544}
4545
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004546status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004547{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004548 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004549 ssize_t index = mAudioPatches.indexOfKey(handle);
4550
4551 if (index < 0) {
4552 return BAD_VALUE;
4553 }
4554 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004555 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4556 __func__, mUidCached, patchDesc->getUid(), uid);
4557 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004558 return INVALID_OPERATION;
4559 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004560 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4561 for (size_t i = 0; i < mAudioSources.size(); i++) {
4562 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4563 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4564 portId = sourceDesc->portId();
4565 break;
4566 }
4567 }
4568 return portId != AUDIO_PORT_HANDLE_NONE ?
4569 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004570}
Eric Laurent6a94d692014-05-20 11:18:06 -07004571
François Gaffieafd4cea2019-11-18 15:50:22 +01004572status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004573 uint32_t delayMs,
4574 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004575{
4576 ALOGV("%s patch %d", __func__, handle);
4577 if (mAudioPatches.indexOfKey(handle) < 0) {
4578 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4579 return BAD_VALUE;
4580 }
4581 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004582 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004583 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004584 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004585 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004586 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004587 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004588 return BAD_VALUE;
4589 }
4590
François Gaffie11d30102018-11-02 16:09:09 +01004591 setOutputDevices(outputDesc,
4592 getNewOutputDevices(outputDesc, true /*fromCache*/),
4593 true,
4594 0,
4595 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004596 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4597 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004598 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004599 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004600 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004601 return BAD_VALUE;
4602 }
4603 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004604 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004605 true,
4606 NULL);
4607 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004608 status_t status =
4609 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4610 ALOGV("%s patch panel returned %d patchHandle %d",
4611 __func__, status, patchDesc->getAfHandle());
4612 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004613 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004614 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004615 // SW or HW Bridge
4616 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4617 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004618 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004619 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4620 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4621 outputDesc = sourceDesc->swOutput().promote();
4622 }
4623 if (outputDesc == nullptr) {
4624 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4625 // releaseOutput has already called closeOutput in case of direct output
4626 return NO_ERROR;
4627 }
4628 if (!outputDesc->isActive() && !sourceDesc->useSwBridge()) {
4629 resetOutputDevice(outputDesc);
4630 } else {
4631 // Reuse patch handle if still valid / do not force rerouting if still routed
4632 patchHandle = outputDesc->getPatchHandle();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004633 setOutputDevices(outputDesc,
4634 getNewOutputDevices(outputDesc, true /*fromCache*/),
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004635 patchHandle == AUDIO_PATCH_HANDLE_NONE, /*force*/
Francois Gaffie7feb8542020-04-06 17:39:47 +02004636 0,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004637 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Francois Gaffie7feb8542020-04-06 17:39:47 +02004638 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004639 } else {
4640 return BAD_VALUE;
4641 }
4642 } else {
4643 return BAD_VALUE;
4644 }
4645 return NO_ERROR;
4646}
4647
4648status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4649 struct audio_patch *patches,
4650 unsigned int *generation)
4651{
François Gaffie53615e22015-03-19 09:24:12 +01004652 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004653 return BAD_VALUE;
4654 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004655 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004656 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004657}
4658
Eric Laurente1715a42014-05-20 11:30:42 -07004659status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004660{
Eric Laurente1715a42014-05-20 11:30:42 -07004661 ALOGV("setAudioPortConfig()");
4662
4663 if (config == NULL) {
4664 return BAD_VALUE;
4665 }
4666 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4667 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004668 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4669 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004670 }
4671
Eric Laurenta121f902014-06-03 13:32:54 -07004672 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004673 if (config->type == AUDIO_PORT_TYPE_MIX) {
4674 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004675 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004676 if (outputDesc == NULL) {
4677 return BAD_VALUE;
4678 }
Eric Laurent84c70242014-06-23 08:46:27 -07004679 ALOG_ASSERT(!outputDesc->isDuplicated(),
4680 "setAudioPortConfig() called on duplicated output %d",
4681 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004682 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004683 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004684 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004685 if (inputDesc == NULL) {
4686 return BAD_VALUE;
4687 }
Eric Laurenta121f902014-06-03 13:32:54 -07004688 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004689 } else {
4690 return BAD_VALUE;
4691 }
4692 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4693 sp<DeviceDescriptor> deviceDesc;
4694 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4695 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4696 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4697 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4698 } else {
4699 return BAD_VALUE;
4700 }
4701 if (deviceDesc == NULL) {
4702 return BAD_VALUE;
4703 }
Eric Laurenta121f902014-06-03 13:32:54 -07004704 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004705 } else {
4706 return BAD_VALUE;
4707 }
4708
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004709 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004710 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4711 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004712 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004713 audioPortConfig->toAudioPortConfig(&newConfig, config);
4714 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004715 }
Eric Laurenta121f902014-06-03 13:32:54 -07004716 if (status != NO_ERROR) {
4717 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004718 }
Eric Laurente1715a42014-05-20 11:30:42 -07004719
4720 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004721}
4722
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004723void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4724{
Eric Laurentd60560a2015-04-10 11:31:20 -07004725 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004726 clearAudioPatches(uid);
4727 clearSessionRoutes(uid);
4728}
4729
Eric Laurent6a94d692014-05-20 11:18:06 -07004730void AudioPolicyManager::clearAudioPatches(uid_t uid)
4731{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004732 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004733 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004734 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004735 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004736 }
4737 }
4738}
4739
François Gaffiec005e562018-11-06 15:04:49 +01004740void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004741{
François Gaffiec005e562018-11-06 15:04:49 +01004742 // Take the first attributes following the product strategy as it is used to retrieve the routed
4743 // device. All attributes wihin a strategy follows the same "routing strategy"
4744 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4745 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004746 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004747 for (size_t j = 0; j < mOutputs.size(); j++) {
4748 if (mOutputs.keyAt(j) == ouptutToSkip) {
4749 continue;
4750 }
4751 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004752 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004753 continue;
4754 }
4755 // If the default device for this strategy is on another output mix,
4756 // invalidate all tracks in this strategy to force re connection.
4757 // Otherwise select new device on the output mix.
4758 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004759 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4760 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004761 }
4762 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004763 setOutputDevices(
4764 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004765 }
4766 }
4767}
4768
4769void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4770{
4771 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004772 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004773 for (size_t i = 0; i < mOutputs.size(); i++) {
4774 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004775 for (const auto& client : outputDesc->getClientIterable()) {
4776 if (client->hasPreferredDevice() && client->uid() == uid) {
4777 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004778 auto clientStrategy = client->strategy();
4779 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4780 end(affectedStrategies)) {
4781 continue;
4782 }
4783 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004784 }
4785 }
4786 }
4787 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004788 for (const auto& strategy : affectedStrategies) {
4789 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004790 }
4791
4792 // remove input routes associated with this uid
4793 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004794 for (size_t i = 0; i < mInputs.size(); i++) {
4795 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004796 for (const auto& client : inputDesc->getClientIterable()) {
4797 if (client->hasPreferredDevice() && client->uid() == uid) {
4798 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4799 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004800 }
4801 }
4802 }
4803 // reroute inputs if necessary
4804 SortedVector<audio_io_handle_t> inputsToClose;
4805 for (size_t i = 0; i < mInputs.size(); i++) {
4806 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004807 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004808 inputsToClose.add(inputDesc->mIoHandle);
4809 }
4810 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004811 for (const auto& input : inputsToClose) {
4812 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004813 }
4814}
4815
Eric Laurentd60560a2015-04-10 11:31:20 -07004816void AudioPolicyManager::clearAudioSources(uid_t uid)
4817{
4818 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004819 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4820 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004821 stopAudioSource(mAudioSources.keyAt(i));
4822 }
4823 }
4824}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004825
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004826status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4827 audio_io_handle_t *ioHandle,
4828 audio_devices_t *device)
4829{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004830 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4831 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004832 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004833 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004834
François Gaffiedf372692015-03-19 10:43:27 +01004835 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004836}
4837
Eric Laurentd60560a2015-04-10 11:31:20 -07004838status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004839 const audio_attributes_t *attributes,
4840 audio_port_handle_t *portId,
4841 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004842{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004843 ALOGV("%s", __FUNCTION__);
4844 *portId = AUDIO_PORT_HANDLE_NONE;
4845
4846 if (source == NULL || attributes == NULL || portId == NULL) {
4847 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4848 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004849 return BAD_VALUE;
4850 }
4851
Eric Laurentd60560a2015-04-10 11:31:20 -07004852 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4853 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004854 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4855 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004856 return INVALID_OPERATION;
4857 }
4858
François Gaffie11d30102018-11-02 16:09:09 +01004859 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004860 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004861 String8(source->ext.device.address),
4862 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004863 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004864 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004865 return BAD_VALUE;
4866 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004867
jiabin4ef93452019-09-10 14:29:54 -07004868 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004869
François Gaffieaaac0fd2018-11-22 17:56:39 +01004870 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004871 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004872 mEngine->getStreamTypeForAttributes(*attributes),
4873 mEngine->getProductStrategyForAttributes(*attributes),
4874 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004875
4876 status_t status = connectAudioSource(sourceDesc);
4877 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004878 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004879 }
4880 return status;
4881}
4882
Francois Gaffie601801d2021-06-22 13:27:39 +02004883sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4884 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4885{
4886 ALOGV("%s", __FUNCTION__);
4887 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4888
4889 status_t status = startAudioSource(source, attributes, &portId, uid);
4890 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4891 return mAudioSources.valueFor(portId);
4892}
4893
4894
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004895status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004896{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004897 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004898
4899 // make sure we only have one patch per source.
4900 disconnectAudioSource(sourceDesc);
4901
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004902 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004903 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4904 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4905 sourceDesc->srcDevice()->type(),
4906 String8(sourceDesc->srcDevice()->address().c_str()),
4907 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004908 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004909 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004910 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004911 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004912 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4913 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4914 return INVALID_OPERATION;
4915 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004916 PatchBuilder patchBuilder;
4917 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4918 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01004919
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004920 return connectAudioSourceToSink(
4921 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07004922}
4923
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004924status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004925{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004926 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4927 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004928 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004929 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004930 return BAD_VALUE;
4931 }
4932 status_t status = disconnectAudioSource(sourceDesc);
4933
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004934 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004935 return status;
4936}
4937
Andy Hung2ddee192015-12-18 17:34:44 -08004938status_t AudioPolicyManager::setMasterMono(bool mono)
4939{
4940 if (mMasterMono == mono) {
4941 return NO_ERROR;
4942 }
4943 mMasterMono = mono;
4944 // if enabling mono we close all offloaded devices, which will invalidate the
4945 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4946 // for recreating the new AudioTrack as non-offloaded PCM.
4947 //
4948 // If disabling mono, we leave all tracks as is: we don't know which clients
4949 // and tracks are able to be recreated as offloaded. The next "song" should
4950 // play back offloaded.
4951 if (mMasterMono) {
4952 Vector<audio_io_handle_t> offloaded;
4953 for (size_t i = 0; i < mOutputs.size(); ++i) {
4954 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4955 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4956 offloaded.push(desc->mIoHandle);
4957 }
4958 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004959 for (const auto& handle : offloaded) {
4960 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004961 }
4962 }
4963 // update master mono for all remaining outputs
4964 for (size_t i = 0; i < mOutputs.size(); ++i) {
4965 updateMono(mOutputs.keyAt(i));
4966 }
4967 return NO_ERROR;
4968}
4969
4970status_t AudioPolicyManager::getMasterMono(bool *mono)
4971{
4972 *mono = mMasterMono;
4973 return NO_ERROR;
4974}
4975
Eric Laurentac9cef52017-06-09 15:46:26 -07004976float AudioPolicyManager::getStreamVolumeDB(
4977 audio_stream_type_t stream, int index, audio_devices_t device)
4978{
jiabin9a3361e2019-10-01 09:38:30 -07004979 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004980}
4981
jiabin81772902018-04-02 17:52:27 -07004982status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4983 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004984 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004985{
Kriti Dang6537def2021-03-02 13:46:59 +01004986 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4987 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004988 return BAD_VALUE;
4989 }
Kriti Dang6537def2021-03-02 13:46:59 +01004990 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4991 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004992
4993 size_t formatsWritten = 0;
4994 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004995
Kriti Dang6537def2021-03-02 13:46:59 +01004996 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004997 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4998 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004999 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005000 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005001 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005002 bool formatEnabled = true;
5003 switch (forceUse) {
5004 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005005 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005006 break;
5007 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5008 formatEnabled = false;
5009 break;
5010 default: // AUTO or ALWAYS => true
5011 break;
jiabin81772902018-04-02 17:52:27 -07005012 }
5013 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5014 }
jiabin81772902018-04-02 17:52:27 -07005015 }
5016 return NO_ERROR;
5017}
5018
Kriti Dang6537def2021-03-02 13:46:59 +01005019status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5020 audio_format_t *surroundFormats) {
5021 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5022 return BAD_VALUE;
5023 }
5024 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5025 __func__, *numSurroundFormats, surroundFormats);
5026
5027 size_t formatsWritten = 0;
5028 size_t formatsMax = *numSurroundFormats;
5029 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5030
5031 // Return formats from all device profiles that have already been resolved by
5032 // checkOutputsForDevice().
5033 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5034 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5035 audio_devices_t deviceType = device->type();
5036 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5037 // returns formats reported by HDMI devices.
5038 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5039 continue;
5040 }
5041 // Formats reported by sink devices
5042 std::unordered_set<audio_format_t> formatset;
5043 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5044 formatset.insert(it->second.begin(), it->second.end());
5045 }
5046
5047 // Formats hard-coded in the in policy configuration file (if any).
5048 FormatVector encodedFormats = device->encodedFormats();
5049 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5050 // Filter the formats which are supported by the vendor hardware.
5051 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5052 if (mConfig.getSurroundFormats().count(*it) != 0) {
5053 formats.insert(*it);
5054 } else {
5055 for (const auto& pair : mConfig.getSurroundFormats()) {
5056 if (pair.second.count(*it) != 0) {
5057 formats.insert(pair.first);
5058 break;
5059 }
5060 }
5061 }
5062 }
5063 }
5064 *numSurroundFormats = formats.size();
5065 for (const auto& format: formats) {
5066 if (formatsWritten < formatsMax) {
5067 surroundFormats[formatsWritten++] = format;
5068 }
5069 }
5070 return NO_ERROR;
5071}
5072
jiabin81772902018-04-02 17:52:27 -07005073status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5074{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005075 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005076 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5077 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005078 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005079 return BAD_VALUE;
5080 }
5081
Mikhail Naganov100f0122018-11-29 11:22:16 -08005082 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5083 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005084 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005085 return INVALID_OPERATION;
5086 }
5087
Mikhail Naganov100f0122018-11-29 11:22:16 -08005088 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005089 return NO_ERROR;
5090 }
5091
Mikhail Naganov100f0122018-11-29 11:22:16 -08005092 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005093 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005094 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005095 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005096 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005097 }
5098 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005099 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005100 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005101 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005102 }
5103 }
5104
5105 sp<SwAudioOutputDescriptor> outputDesc;
5106 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005107 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5108 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005109 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5110 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005111 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005112 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005113 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5114 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5115 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005116 name.c_str(),
5117 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005118 if (status != NO_ERROR) {
5119 continue;
5120 }
5121 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5122 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5123 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005124 name.c_str(),
5125 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005126 profileUpdated |= (status == NO_ERROR);
5127 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005128 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005129 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005130 AUDIO_DEVICE_IN_HDMI);
5131 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5132 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005133 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005134 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005135 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5136 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5137 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005138 name.c_str(),
5139 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005140 if (status != NO_ERROR) {
5141 continue;
5142 }
5143 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5144 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5145 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005146 name.c_str(),
5147 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005148 profileUpdated |= (status == NO_ERROR);
5149 }
5150
jiabin81772902018-04-02 17:52:27 -07005151 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005152 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005153 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005154 }
5155
5156 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5157}
5158
Eric Laurent5ada82e2019-08-29 17:53:54 -07005159void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005160{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005161 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005162 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005163 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005164 }
5165}
5166
jiabin6012f912018-11-02 17:06:30 -07005167bool AudioPolicyManager::isHapticPlaybackSupported()
5168{
5169 for (const auto& hwModule : mHwModules) {
5170 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5171 for (const auto &outProfile : outputProfiles) {
5172 struct audio_port audioPort;
5173 outProfile->toAudioPort(&audioPort);
5174 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5175 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5176 return true;
5177 }
5178 }
5179 }
5180 }
5181 return false;
5182}
5183
Carter Hsu325a8eb2022-01-19 19:56:51 +08005184bool AudioPolicyManager::isUltrasoundSupported()
5185{
5186 bool hasUltrasoundOutput = false;
5187 bool hasUltrasoundInput = false;
5188 for (const auto& hwModule : mHwModules) {
5189 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5190 if (!hasUltrasoundOutput) {
5191 for (const auto &outProfile : outputProfiles) {
5192 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5193 hasUltrasoundOutput = true;
5194 break;
5195 }
5196 }
5197 }
5198
5199 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5200 if (!hasUltrasoundInput) {
5201 for (const auto &inputProfile : inputProfiles) {
5202 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5203 hasUltrasoundInput = true;
5204 break;
5205 }
5206 }
5207 }
5208
5209 if (hasUltrasoundOutput && hasUltrasoundInput)
5210 return true;
5211 }
5212 return false;
5213}
5214
Eric Laurent8340e672019-11-06 11:01:08 -08005215bool AudioPolicyManager::isCallScreenModeSupported()
5216{
5217 return getConfig().isCallScreenModeSupported();
5218}
5219
5220
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005221status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005222{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005223 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005224 if (!sourceDesc->isConnected()) {
5225 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5226 return NO_ERROR;
5227 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005228 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5229 if (swOutput != 0) {
5230 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005231 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005232 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005233 }
jiabinbce0c1d2020-10-05 11:20:18 -07005234 if (releaseOutput(sourceDesc->portId())) {
5235 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5236 // no need to release audio patch here but just return NO_ERROR.
5237 return NO_ERROR;
5238 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005239 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005240 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005241 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005242 // close Hwoutput and remove from mHwOutputs
5243 } else {
5244 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5245 }
5246 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005247 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005248 sourceDesc->disconnect();
5249 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005250}
5251
François Gaffiec005e562018-11-06 15:04:49 +01005252sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5253 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005254{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005255 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005256 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005257 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005258 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005259 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5260 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005261 source = sourceDesc;
5262 break;
5263 }
5264 }
5265 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005266}
5267
Eric Laurent39095982021-08-24 18:29:27 +02005268/* static */
5269bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
5270 switch (channels) {
5271 case AUDIO_CHANNEL_OUT_5POINT1:
5272 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
5273 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
5274 case AUDIO_CHANNEL_OUT_7POINT1:
5275 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
5276 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
5277 return true;
5278 default:
5279 return false;
5280 }
5281}
5282
Eric Laurentb4f42a92022-01-17 17:37:31 +01005283bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005284 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005285 const AudioDeviceTypeAddrVector &devices,
5286 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005287{
5288 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5289 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005290 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005291 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005292 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5293 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5294 return false;
5295 }
5296 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5297 return false;
5298 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005299 }
5300
5301 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005302 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5303 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005304 // to the specified devices must exist.
5305 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005306 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005307 if (profile == nullptr) {
5308 return false;
5309 }
5310
5311 // The caller can have the audio config criteria ignored by either passing a null ptr or
5312 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005313 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005314 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005315 // If the spatializer output is already opened, only channel masks included in the
5316 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005317
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005318 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005319 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005320 return false;
5321 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005322 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5323 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005324 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005325 != config->channel_mask) {
5326 return false;
5327 }
5328 }
5329 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005330 return true;
5331}
5332
5333void AudioPolicyManager::checkVirtualizerClientRoutes() {
5334 std::set<audio_stream_type_t> streamsToInvalidate;
5335 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005336 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5337 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005338 audio_attributes_t attr = client->attributes();
5339 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5340 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5341 audio_config_base_t clientConfig = client->config();
5342 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005343 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005344 && canBeSpatializedInt(&attr, &config,
5345 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005346 streamsToInvalidate.insert(client->stream());
5347 }
5348 }
5349 }
5350
5351 for (audio_stream_type_t stream : streamsToInvalidate) {
5352 mpClientInterface->invalidateStream(stream);
5353 }
5354}
5355
Eric Laurentfa0f6742021-08-17 18:39:44 +02005356status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005357 const audio_attributes_t *attr,
5358 audio_io_handle_t *output) {
5359 *output = AUDIO_IO_HANDLE_NONE;
5360
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005361 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5362 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5363 audio_config_t *configPtr = nullptr;
5364 audio_config_t config;
5365 if (mixerConfig != nullptr) {
5366 config = audio_config_initializer(mixerConfig);
5367 configPtr = &config;
5368 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005369 if (!canBeSpatializedInt(
5370 attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02005371 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005372 return BAD_VALUE;
5373 }
5374
5375 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005376 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005377 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005378 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005379 return BAD_VALUE;
5380 }
5381
Eric Laurent39095982021-08-24 18:29:27 +02005382 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
5383 && configPtr != nullptr
5384 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
5385 *output = mSpatializerOutput->mIoHandle;
5386 ALOGV("%s returns current spatializer output %d", __func__, *output);
5387 return NO_ERROR;
5388 }
5389 mSpatializerOutput.clear();
5390 for (size_t i = 0; i < mOutputs.size(); i++) {
5391 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5392 if (!desc->isDuplicated() && desc->mProfile == profile) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005393 ALOGV("%s found output %d for spatializer profile", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005394 mSpatializerOutput = desc;
5395 break;
5396 }
5397 }
5398 if (mSpatializerOutput == nullptr) {
5399 ALOGW("%s no opened spatializer output for profile %s",
5400 __func__, profile->getName().c_str());
5401 return BAD_VALUE;
5402 }
5403
5404 if (configPtr != nullptr
5405 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5406 audio_config_base_t savedMixerConfig = {
5407 .sample_rate = mSpatializerOutput->getSamplingRate(),
5408 .format = mSpatializerOutput->getFormat(),
5409 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5410 };
5411 DeviceVector savedDevices = mSpatializerOutput->devices();
5412
Eric Laurentb4f42a92022-01-17 17:37:31 +01005413 ALOGV("%s reopening spatializer output to match channel mask %#x (current mask %#x)",
5414 __func__, configPtr->channel_mask, mSpatializerOutput->mMixerChannelMask);
Eric Laurent39095982021-08-24 18:29:27 +02005415
Eric Laurentb4f42a92022-01-17 17:37:31 +01005416 closeOutput(mSpatializerOutput->mIoHandle);
5417 //from now on mSpatializerOutput is null
5418
5419 sp<SwAudioOutputDescriptor> desc =
5420 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
5421 if (desc == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005422 // re open the spatializer output with previous channel mask
Eric Laurentb4f42a92022-01-17 17:37:31 +01005423 desc = openOutputWithProfileAndDevice(profile, savedDevices, &savedMixerConfig);
5424 if (desc == nullptr) {
5425 ALOGE("%s failed to restore mSpatializerOutput with previous config", __func__);
Eric Laurent39095982021-08-24 18:29:27 +02005426 } else {
5427 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005428 }
5429 mPreviousOutputs = mOutputs;
5430 mpClientInterface->onAudioPortListUpdate();
5431 *output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005432 ALOGW("%s could not open spatializer output with requested config", __func__);
5433 return BAD_VALUE;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005434 }
Eric Laurent39095982021-08-24 18:29:27 +02005435 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005436 mPreviousOutputs = mOutputs;
5437 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005438 }
5439
5440 checkVirtualizerClientRoutes();
5441
Eric Laurent39095982021-08-24 18:29:27 +02005442 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005443 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005444 return NO_ERROR;
5445}
5446
Eric Laurentfa0f6742021-08-17 18:39:44 +02005447status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5448 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005449 return INVALID_OPERATION;
5450 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005451 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005452 return BAD_VALUE;
5453 }
Eric Laurent39095982021-08-24 18:29:27 +02005454
Eric Laurentfa0f6742021-08-17 18:39:44 +02005455 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005456
5457 checkVirtualizerClientRoutes();
5458
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005459 return NO_ERROR;
5460}
5461
Eric Laurente552edb2014-03-10 17:42:56 -07005462// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005463// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005464// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005465uint32_t AudioPolicyManager::nextAudioPortGeneration()
5466{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005467 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005468}
5469
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005470static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005471 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5472 !audioPolicyXmlConfigFile.empty()) {
5473 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5474 if (ret == NO_ERROR) {
5475 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005476 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005477 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005478 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005479 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005480}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005481
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005482AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5483 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005484 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005485 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005486 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005487 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005488 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005489 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005490 mAudioPortGeneration(1),
5491 mBeaconMuteRefCount(0),
5492 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005493 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005494 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005495 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005496 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005497{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005498}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005499
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005500AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5501 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5502{
5503 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005504}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005505
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005506void AudioPolicyManager::loadConfig() {
5507 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005508 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005509 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005510 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005511}
5512
5513status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005514 {
5515 auto engLib = EngineLibrary::load(
5516 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5517 if (!engLib) {
5518 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5519 return NO_INIT;
5520 }
5521 mEngine = engLib->createEngine();
5522 if (mEngine == nullptr) {
5523 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5524 return NO_INIT;
5525 }
François Gaffie2110e042015-03-24 08:41:51 +01005526 }
5527 mEngine->setObserver(this);
5528 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005529 if (status != NO_ERROR) {
5530 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5531 return status;
5532 }
François Gaffie2110e042015-03-24 08:41:51 +01005533
Eric Laurent1d69c872021-01-11 18:53:01 +01005534 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5535 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5536
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005537 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005538 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005539 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005540
Eric Laurent3a4311c2014-03-17 12:00:47 -07005541 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005542 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5543 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5544 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005545 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005546 }
jiabin9ff780e2018-03-19 18:19:52 -07005547 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005548 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005549 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005550 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005551 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005552 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005553 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005554 }
5555 }
5556 }
Eric Laurente552edb2014-03-10 17:42:56 -07005557
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005558 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005559
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005560 // Silence ALOGV statements
5561 property_set("log.tag." LOG_TAG, "D");
5562
Eric Laurente552edb2014-03-10 17:42:56 -07005563 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005564 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005565}
5566
Eric Laurente0720872014-03-11 09:30:41 -07005567AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005568{
Eric Laurente552edb2014-03-10 17:42:56 -07005569 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005570 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005571 }
5572 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005573 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005574 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005575 mAvailableOutputDevices.clear();
5576 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005577 mOutputs.clear();
5578 mInputs.clear();
5579 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005580 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005581 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005582}
5583
Eric Laurente0720872014-03-11 09:30:41 -07005584status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005585{
Eric Laurent87ffa392015-05-22 10:32:38 -07005586 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005587}
5588
Eric Laurente552edb2014-03-10 17:42:56 -07005589// ---
5590
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005591void AudioPolicyManager::onNewAudioModulesAvailable()
5592{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005593 DeviceVector newDevices;
5594 onNewAudioModulesAvailableInt(&newDevices);
5595 if (!newDevices.empty()) {
5596 nextAudioPortGeneration();
5597 mpClientInterface->onAudioPortListUpdate();
5598 }
5599}
5600
5601void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5602{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005603 for (const auto& hwModule : mHwModulesAll) {
5604 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5605 continue;
5606 }
5607 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5608 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5609 ALOGW("could not open HW module %s", hwModule->getName());
5610 continue;
5611 }
5612 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005613 // open all output streams needed to access attached devices.
5614 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005615 // This also validates mAvailableOutputDevices list
5616 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5617 if (!outProfile->canOpenNewIo()) {
5618 ALOGE("Invalid Output profile max open count %u for profile %s",
5619 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5620 continue;
5621 }
5622 if (!outProfile->hasSupportedDevices()) {
5623 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5624 continue;
5625 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005626 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5627 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005628 mTtsOutputAvailable = true;
5629 }
5630
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005631 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5632 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5633 sp<DeviceDescriptor> supportedDevice = 0;
5634 if (supportedDevices.contains(mDefaultOutputDevice)) {
5635 supportedDevice = mDefaultOutputDevice;
5636 } else {
5637 // choose first device present in profile's SupportedDevices also part of
5638 // mAvailableOutputDevices.
5639 if (availProfileDevices.isEmpty()) {
5640 continue;
5641 }
5642 supportedDevice = availProfileDevices.itemAt(0);
5643 }
5644 if (!mOutputDevicesAll.contains(supportedDevice)) {
5645 continue;
5646 }
5647 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5648 mpClientInterface);
5649 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005650 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5651 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005652 AUDIO_STREAM_DEFAULT,
5653 AUDIO_OUTPUT_FLAG_NONE, &output);
5654 if (status != NO_ERROR) {
5655 ALOGW("Cannot open output stream for devices %s on hw module %s",
5656 supportedDevice->toString().c_str(), hwModule->getName());
5657 continue;
5658 }
5659 for (const auto &device : availProfileDevices) {
5660 // give a valid ID to an attached device once confirmed it is reachable
5661 if (!device->isAttached()) {
5662 device->attach(hwModule);
5663 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005664 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005665 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005666 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5667 }
5668 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005669 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005670 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5671 mPrimaryOutput = outputDesc;
5672 }
Eric Laurent39095982021-08-24 18:29:27 +02005673 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005674 outputDesc->close();
5675 } else {
5676 addOutput(output, outputDesc);
5677 setOutputDevices(outputDesc,
5678 DeviceVector(supportedDevice),
5679 true,
5680 0,
5681 NULL);
5682 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005683 }
5684 // open input streams needed to access attached devices to validate
5685 // mAvailableInputDevices list
5686 for (const auto& inProfile : hwModule->getInputProfiles()) {
5687 if (!inProfile->canOpenNewIo()) {
5688 ALOGE("Invalid Input profile max open count %u for profile %s",
5689 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5690 continue;
5691 }
5692 if (!inProfile->hasSupportedDevices()) {
5693 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5694 continue;
5695 }
5696 // chose first device present in profile's SupportedDevices also part of
5697 // available input devices
5698 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5699 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5700 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005701 ALOGV("%s: Input device list is empty! for profile %s",
5702 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005703 continue;
5704 }
5705 sp<AudioInputDescriptor> inputDesc =
5706 new AudioInputDescriptor(inProfile, mpClientInterface);
5707
5708 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5709 status_t status = inputDesc->open(nullptr,
5710 availProfileDevices.itemAt(0),
5711 AUDIO_SOURCE_MIC,
5712 AUDIO_INPUT_FLAG_NONE,
5713 &input);
5714 if (status != NO_ERROR) {
5715 ALOGW("Cannot open input stream for device %s on hw module %s",
5716 availProfileDevices.toString().c_str(),
5717 hwModule->getName());
5718 continue;
5719 }
5720 for (const auto &device : availProfileDevices) {
5721 // give a valid ID to an attached device once confirmed it is reachable
5722 if (!device->isAttached()) {
5723 device->attach(hwModule);
5724 device->importAudioPortAndPickAudioProfile(inProfile, true);
5725 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005726 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005727 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5728 }
5729 }
5730 inputDesc->close();
5731 }
5732 }
5733}
5734
Eric Laurent98e38192018-02-15 18:31:53 -08005735void AudioPolicyManager::addOutput(audio_io_handle_t output,
5736 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005737{
Eric Laurent1c333e22014-05-20 10:48:17 -07005738 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005739 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005740 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005741 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005742 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005743}
5744
François Gaffie53615e22015-03-19 09:24:12 +01005745void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5746{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005747 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5748 ALOGV("%s: removing primary output", __func__);
5749 mPrimaryOutput = nullptr;
5750 }
François Gaffie53615e22015-03-19 09:24:12 +01005751 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005752 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005753}
5754
Eric Laurent98e38192018-02-15 18:31:53 -08005755void AudioPolicyManager::addInput(audio_io_handle_t input,
5756 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005757{
Eric Laurent1c333e22014-05-20 10:48:17 -07005758 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005759 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005760}
Eric Laurente552edb2014-03-10 17:42:56 -07005761
François Gaffie11d30102018-11-02 16:09:09 +01005762status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005763 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005764 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005765{
François Gaffie11d30102018-11-02 16:09:09 +01005766 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005767 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005768 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005769
François Gaffie11d30102018-11-02 16:09:09 +01005770 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005771 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005772 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005773 }
Eric Laurente552edb2014-03-10 17:42:56 -07005774
Eric Laurent3b73df72014-03-11 09:06:29 -07005775 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005776 // first call getAudioPort to get the supported attributes from the HAL
5777 struct audio_port_v7 port = {};
5778 device->toAudioPort(&port);
5779 status_t status = mpClientInterface->getAudioPort(&port);
5780 if (status == NO_ERROR) {
5781 device->importAudioPort(port);
5782 }
5783
5784 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005785 for (size_t i = 0; i < mOutputs.size(); i++) {
5786 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005787 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005788 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005789 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5790 mOutputs.keyAt(i), device->toString().c_str());
5791 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005792 }
5793 }
5794 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005795 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005796 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005797 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5798 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005799 if (profile->supportsDevice(device)) {
5800 profiles.add(profile);
5801 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5802 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005803 }
5804 }
5805 }
5806
Eric Laurent7b279bb2015-12-14 10:18:23 -08005807 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005808
Eric Laurente552edb2014-03-10 17:42:56 -07005809 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005810 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005811 return BAD_VALUE;
5812 }
5813
5814 // open outputs for matching profiles if needed. Direct outputs are also opened to
5815 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5816 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005817 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005818
5819 // nothing to do if one output is already opened for this profile
5820 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005821 for (j = 0; j < outputs.size(); j++) {
5822 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005823 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005824 // matching profile: save the sample rates, format and channel masks supported
5825 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005826 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005827 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005828 }
Eric Laurente552edb2014-03-10 17:42:56 -07005829 break;
5830 }
5831 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005832 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005833 continue;
5834 }
5835
Eric Laurent3974e3b2017-12-07 17:58:43 -08005836 if (!profile->canOpenNewIo()) {
5837 ALOGW("Max Output number %u already opened for this profile %s",
5838 profile->maxOpenCount, profile->getTagName().c_str());
5839 continue;
5840 }
5841
Eric Laurent83efe1c2017-07-09 16:51:08 -07005842 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005843 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005844 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5845 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005846 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005847 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005848 profiles.removeAt(profile_index);
5849 profile_index--;
5850 } else {
5851 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005852 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005853 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005854 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5855 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005856 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005857 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005858
François Gaffie11d30102018-11-02 16:09:09 +01005859 if (device_distinguishes_on_address(deviceType)) {
5860 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5861 device->toString().c_str());
5862 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5863 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005864 }
Eric Laurente552edb2014-03-10 17:42:56 -07005865 ALOGV("checkOutputsForDevice(): adding output %d", output);
5866 }
5867 }
5868
5869 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005870 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005871 return BAD_VALUE;
5872 }
Eric Laurentd4692962014-05-05 18:13:44 -07005873 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005874 // check if one opened output is not needed any more after disconnecting one device
5875 for (size_t i = 0; i < mOutputs.size(); i++) {
5876 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005877 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005878 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005879 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005880 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005881 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005882 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005883 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5884 mOutputs.keyAt(i));
5885 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005886 }
Eric Laurente552edb2014-03-10 17:42:56 -07005887 }
5888 }
Eric Laurentd4692962014-05-05 18:13:44 -07005889 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005890 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005891 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5892 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005893 if (!profile->supportsDevice(device)) {
5894 continue;
5895 }
5896 ALOGV("checkOutputsForDevice(): "
5897 "clearing direct output profile %zu on module %s",
5898 j, hwModule->getName());
5899 profile->clearAudioProfiles();
5900 if (!profile->hasDynamicAudioProfile()) {
5901 continue;
5902 }
5903 // When a device is disconnected, if there is an IOProfile that contains dynamic
5904 // profiles and supports the disconnected device, call getAudioPort to repopulate
5905 // the capabilities of the devices that is supported by the IOProfile.
5906 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5907 if (supportedDevice == device ||
5908 !mAvailableOutputDevices.contains(supportedDevice)) {
5909 continue;
5910 }
5911 struct audio_port_v7 port;
5912 supportedDevice->toAudioPort(&port);
5913 status_t status = mpClientInterface->getAudioPort(&port);
5914 if (status == NO_ERROR) {
5915 supportedDevice->importAudioPort(port);
5916 }
Eric Laurente552edb2014-03-10 17:42:56 -07005917 }
5918 }
5919 }
5920 }
5921 return NO_ERROR;
5922}
5923
François Gaffie11d30102018-11-02 16:09:09 +01005924status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005925 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005926{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005927 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005928
François Gaffie11d30102018-11-02 16:09:09 +01005929 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005930 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005931 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005932 }
5933
Eric Laurentd4692962014-05-05 18:13:44 -07005934 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005935 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005936 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005937 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005938 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005939 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005940 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005941 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005942
François Gaffie11d30102018-11-02 16:09:09 +01005943 if (profile->supportsDevice(device)) {
5944 profiles.add(profile);
5945 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5946 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005947 }
5948 }
5949 }
5950
Eric Laurent0dd51852019-04-19 18:18:58 -07005951 if (profiles.isEmpty()) {
5952 ALOGW("%s: No input profile available for device %s",
5953 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005954 return BAD_VALUE;
5955 }
5956
5957 // open inputs for matching profiles if needed. Direct inputs are also opened to
5958 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5959 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5960
Eric Laurent1c333e22014-05-20 10:48:17 -07005961 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005962
Eric Laurentd4692962014-05-05 18:13:44 -07005963 // nothing to do if one input is already opened for this profile
5964 size_t input_index;
5965 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5966 desc = mInputs.valueAt(input_index);
5967 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005968 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005969 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005970 }
Eric Laurentd4692962014-05-05 18:13:44 -07005971 break;
5972 }
5973 }
5974 if (input_index != mInputs.size()) {
5975 continue;
5976 }
5977
Eric Laurent3974e3b2017-12-07 17:58:43 -08005978 if (!profile->canOpenNewIo()) {
5979 ALOGW("Max Input number %u already opened for this profile %s",
5980 profile->maxOpenCount, profile->getTagName().c_str());
5981 continue;
5982 }
5983
Eric Laurentfe231122017-11-17 17:48:06 -08005984 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005985 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005986 status_t status = desc->open(nullptr,
5987 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005988 AUDIO_SOURCE_MIC,
5989 AUDIO_INPUT_FLAG_NONE,
5990 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005991
Eric Laurentcf2c0212014-07-25 16:20:43 -07005992 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005993 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005994 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005995 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005996 mpClientInterface->setParameters(input, String8(param));
5997 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005998 }
François Gaffie11d30102018-11-02 16:09:09 +01005999 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006000 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006001 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006002 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006003 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006004 }
6005
Eric Laurent0dd51852019-04-19 18:18:58 -07006006 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006007 addInput(input, desc);
6008 }
6009 } // endif input != 0
6010
Eric Laurentcf2c0212014-07-25 16:20:43 -07006011 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006012 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006013 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006014 profiles.removeAt(profile_index);
6015 profile_index--;
6016 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006017 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006018 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006019 }
Eric Laurentd4692962014-05-05 18:13:44 -07006020 ALOGV("checkInputsForDevice(): adding input %d", input);
6021 }
6022 } // end scan profiles
6023
6024 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006025 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006026 return BAD_VALUE;
6027 }
6028 } else {
6029 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006030 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006031 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006032 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006033 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006034 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006035 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006036 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006037 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6038 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006039 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006040 }
6041 }
6042 }
6043 } // end disconnect
6044
6045 return NO_ERROR;
6046}
6047
6048
Eric Laurente0720872014-03-11 09:30:41 -07006049void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006050{
6051 ALOGV("closeOutput(%d)", output);
6052
François Gaffie1c878552018-11-22 16:53:21 +01006053 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6054 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006055 ALOGW("closeOutput() unknown output %d", output);
6056 return;
6057 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006058 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006059 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006060
Eric Laurente552edb2014-03-10 17:42:56 -07006061 // look for duplicated outputs connected to the output being removed.
6062 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006063 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6064 if (dupOutput->isDuplicated() &&
6065 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6066 sp<SwAudioOutputDescriptor> remainingOutput =
6067 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006068 // As all active tracks on duplicated output will be deleted,
6069 // and as they were also referenced on the other output, the reference
6070 // count for their stream type must be adjusted accordingly on
6071 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006072 const bool wasActive = remainingOutput->isActive();
6073 // Note: no-op on the closing output where all clients has already been set inactive
6074 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006075 // stop() will be a no op if the output is still active but is needed in case all
6076 // active streams refcounts where cleared above
6077 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006078 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006079 }
Eric Laurente552edb2014-03-10 17:42:56 -07006080 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6081 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6082
6083 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006084 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006085 }
6086 }
6087
Eric Laurent05b90f82014-08-27 15:32:29 -07006088 nextAudioPortGeneration();
6089
François Gaffie1c878552018-11-22 16:53:21 +01006090 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006091 if (index >= 0) {
6092 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006093 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6094 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006095 mAudioPatches.removeItemsAt(index);
6096 mpClientInterface->onAudioPatchListUpdate();
6097 }
6098
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006099 if (closingOutputWasActive) {
6100 closingOutput->stop();
6101 }
François Gaffie1c878552018-11-22 16:53:21 +01006102 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006103
François Gaffie53615e22015-03-19 09:24:12 +01006104 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006105 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006106 if (closingOutput == mSpatializerOutput) {
6107 mSpatializerOutput.clear();
6108 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006109
6110 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6111 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006112 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006113 bool directOutputOpen = false;
6114 for (size_t i = 0; i < mOutputs.size(); i++) {
6115 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6116 directOutputOpen = true;
6117 break;
6118 }
6119 }
6120 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006121 ALOGV("no direct outputs open, reset MSD patches");
6122 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6123 // how output devices for patching are resolved. Avoid by caching and reusing the
6124 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6125 // devices to patch to. This may be complicated by the fact that devices may become
6126 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006127 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006128 }
6129 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006130}
6131
6132void AudioPolicyManager::closeInput(audio_io_handle_t input)
6133{
6134 ALOGV("closeInput(%d)", input);
6135
6136 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6137 if (inputDesc == NULL) {
6138 ALOGW("closeInput() unknown input %d", input);
6139 return;
6140 }
6141
Eric Laurent6a94d692014-05-20 11:18:06 -07006142 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006143
François Gaffie11d30102018-11-02 16:09:09 +01006144 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006145 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006146 if (index >= 0) {
6147 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006148 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6149 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006150 mAudioPatches.removeItemsAt(index);
6151 mpClientInterface->onAudioPatchListUpdate();
6152 }
6153
Eric Laurentfe231122017-11-17 17:48:06 -08006154 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006155 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006156
François Gaffie11d30102018-11-02 16:09:09 +01006157 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6158 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006159 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006160 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006161 }
Eric Laurente552edb2014-03-10 17:42:56 -07006162}
6163
François Gaffie11d30102018-11-02 16:09:09 +01006164SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6165 const DeviceVector &devices,
6166 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006167{
6168 SortedVector<audio_io_handle_t> outputs;
6169
François Gaffie11d30102018-11-02 16:09:09 +01006170 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006171 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006172 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006173 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006174 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006175 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006176 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006177 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006178 outputs.add(openOutputs.keyAt(i));
6179 }
6180 }
6181 return outputs;
6182}
6183
Mikhail Naganov37977152018-07-11 15:54:44 -07006184void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6185{
6186 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6187 // output is suspended before any tracks are moved to it
6188 checkA2dpSuspend();
6189 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006190 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006191 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006192 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006193 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006194 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6195 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6196 // configuration changes will ultimately be rerouted correctly. We can still avoid
6197 // unnecessary rerouting by caching and reusing the arguments to
6198 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6199 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006200 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006201 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006202 // an event that changed routing likely occurred, inform upper layers
6203 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006204}
6205
François Gaffiec005e562018-11-06 15:04:49 +01006206bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6207 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006208{
François Gaffiec005e562018-11-06 15:04:49 +01006209 return mEngine->getProductStrategyForAttributes(lAttr) ==
6210 mEngine->getProductStrategyForAttributes(rAttr);
6211}
6212
Francois Gaffieff1eb522020-05-06 18:37:04 +02006213void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6214{
6215 for (size_t i = 0; i < mAudioSources.size(); i++) {
6216 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6217 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006218 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006219 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006220 connectAudioSource(sourceDesc);
6221 }
6222 }
6223}
6224
6225void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6226{
6227 for (size_t i = 0; i < mAudioSources.size(); i++) {
6228 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6229 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6230 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6231 disconnectAudioSource(sourceDesc);
6232 }
6233 }
6234}
6235
François Gaffiec005e562018-11-06 15:04:49 +01006236void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6237{
6238 auto psId = mEngine->getProductStrategyForAttributes(attr);
6239
6240 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6241 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006242
François Gaffie11d30102018-11-02 16:09:09 +01006243 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6244 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006245
Eric Laurentc209fe42020-06-05 18:11:23 -07006246 uint32_t maxLatency = 0;
6247 bool invalidate = false;
6248 // take into account dynamic audio policies related changes: if a client is now associated
6249 // to a different policy mix than at creation time, invalidate corresponding stream
6250 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6251 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6252 if (desc->isDuplicated()) {
6253 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006254 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006255 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6256 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6257 continue;
6258 }
6259 sp<AudioPolicyMix> primaryMix;
6260 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
6261 client->flags(), primaryMix, nullptr);
6262 if (status != OK) {
6263 continue;
6264 }
yucliuf4de36d2020-09-14 14:57:56 -07006265 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006266 invalidate = true;
6267 if (desc->isStrategyActive(psId)) {
6268 maxLatency = desc->latency();
6269 }
6270 break;
6271 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006272 }
6273 }
6274
Eric Laurentc209fe42020-06-05 18:11:23 -07006275 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006276 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6277 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006278 for (audio_io_handle_t srcOut : srcOutputs) {
6279 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006280 if (desc == nullptr) continue;
6281
6282 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006283 maxLatency = desc->latency();
6284 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006285
6286 if (invalidate) continue;
6287
6288 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006289 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006290 // a client on a non direct outputs has necessarily a linear PCM format
6291 // so we can call selectOutput() safely
6292 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6293 client->flags(),
6294 client->config().format,
6295 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006296 client->config().sample_rate,
6297 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006298 if (newOutput != srcOut) {
6299 invalidate = true;
6300 break;
6301 }
6302 } else {
6303 sp<IOProfile> profile = getProfileForOutput(newDevices,
6304 client->config().sample_rate,
6305 client->config().format,
6306 client->config().channel_mask,
6307 client->flags(),
6308 true /* directOnly */);
6309 if (profile != desc->mProfile) {
6310 invalidate = true;
6311 break;
6312 }
6313 }
6314 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006315 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006316
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006317 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006318 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006319 std::to_string(srcOutputs[0]).c_str(),
6320 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006321 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006322 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006323 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006324 if (desc == nullptr) continue;
6325
6326 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006327 setStrategyMute(psId, true, desc);
6328 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006329 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006330 }
François Gaffiec005e562018-11-06 15:04:49 +01006331 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006332 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006333 connectAudioSource(source);
6334 }
Eric Laurente552edb2014-03-10 17:42:56 -07006335 }
6336
François Gaffiec005e562018-11-06 15:04:49 +01006337 // Move effects associated to this stream from previous output to new output
6338 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006339 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006340 }
François Gaffiec005e562018-11-06 15:04:49 +01006341 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006342 if (invalidate) {
6343 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6344 mpClientInterface->invalidateStream(stream);
6345 }
jiabin49256852022-03-09 11:21:35 -08006346 for (audio_io_handle_t srcOut : srcOutputs) {
6347 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6348 if (desc == nullptr) continue;
6349
6350 desc->setTracksInvalidatedStatusByStrategy(psId);
6351 }
Eric Laurente552edb2014-03-10 17:42:56 -07006352 }
6353 }
6354}
6355
Eric Laurente0720872014-03-11 09:30:41 -07006356void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006357{
François Gaffiec005e562018-11-06 15:04:49 +01006358 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6359 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6360 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006361 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006362 }
Eric Laurente552edb2014-03-10 17:42:56 -07006363}
6364
Kevin Rocard153f92d2018-12-18 18:33:28 -08006365void AudioPolicyManager::checkSecondaryOutputs() {
6366 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006367 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006368 for (size_t i = 0; i < mOutputs.size(); i++) {
6369 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6370 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006371 sp<AudioPolicyMix> primaryMix;
6372 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006373 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006374 client->flags(), primaryMix, &secondaryMixes);
6375 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6376 for (auto &secondaryMix : secondaryMixes) {
6377 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6378 if (outputDesc != nullptr &&
6379 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6380 secondaryDescs.push_back(outputDesc);
6381 }
6382 }
6383
jiabin10a03f12021-05-07 23:46:28 +00006384 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006385 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006386 } else if (!std::equal(
6387 client->getSecondaryOutputs().begin(),
6388 client->getSecondaryOutputs().end(),
6389 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006390 if (!audio_is_linear_pcm(client->config().format)) {
6391 // If the format is not PCM, the tracks should be invalidated to get correct
6392 // behavior when the secondary output is changed.
6393 streamsToInvalidate.insert(client->stream());
6394 } else {
6395 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6396 std::vector<audio_io_handle_t> secondaryOutputIds;
6397 for (const auto &secondaryDesc: secondaryDescs) {
6398 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6399 weakSecondaryDescs.push_back(secondaryDesc);
6400 }
6401 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6402 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006403 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006404 }
6405 }
6406 }
jiabin10a03f12021-05-07 23:46:28 +00006407 if (!trackSecondaryOutputs.empty()) {
6408 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6409 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006410 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006411 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006412 mpClientInterface->invalidateStream(stream);
6413 }
6414}
6415
Eric Laurent2517af32020-11-25 15:31:27 +01006416bool AudioPolicyManager::isScoRequestedForComm() const {
6417 AudioDeviceTypeAddrVector devices;
6418 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6419 for (const auto &device : devices) {
6420 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6421 return true;
6422 }
6423 }
6424 return false;
6425}
6426
Eric Laurente0720872014-03-11 09:30:41 -07006427void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006428{
François Gaffie53615e22015-03-19 09:24:12 +01006429 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006430 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006431 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006432 return;
6433 }
6434
Eric Laurent3a4311c2014-03-17 12:00:47 -07006435 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006436 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6437 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006438 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006439
6440 // if suspended, restore A2DP output if:
6441 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006442 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006443 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006444 //
Eric Laurentf732e072016-08-03 19:30:28 -07006445 // if not suspended, suspend A2DP output if:
6446 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006447 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006448 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006449 //
6450 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006451 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006452 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006453 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006454 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006455
6456 mpClientInterface->restoreOutput(a2dpOutput);
6457 mA2dpSuspended = false;
6458 }
6459 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006460 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006461 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006462 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006463 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006464
6465 mpClientInterface->suspendOutput(a2dpOutput);
6466 mA2dpSuspended = true;
6467 }
6468 }
6469}
6470
François Gaffie11d30102018-11-02 16:09:09 +01006471DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6472 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006473{
François Gaffie11d30102018-11-02 16:09:09 +01006474 DeviceVector devices;
6475
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006476 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006477 if (index >= 0) {
6478 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006479 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006480 ALOGV("%s device %s forced by patch %d", __func__,
6481 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6482 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006483 }
6484 }
6485
Dean Wheatley514b4312020-06-17 21:45:00 +10006486 // Do not retrieve engine device for outputs through MSD
6487 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6488 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6489 return outputDesc->devices();
6490 }
6491
Eric Laurent97ac8712018-07-27 18:59:02 -07006492 // Honor explicit routing requests only if no client using default routing is active on this
6493 // input: a specific app can not force routing for other apps by setting a preferred device.
6494 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006495 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006496 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006497 if (device != nullptr) {
6498 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006499 }
6500
François Gaffiea807ef92018-11-05 10:44:33 +01006501 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6502 // of setForceUse / Default Bus device here
6503 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6504 if (device != nullptr) {
6505 return DeviceVector(device);
6506 }
6507
François Gaffiec005e562018-11-06 15:04:49 +01006508 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6509 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6510 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306511 auto hasStreamActive = [&](auto stream) {
6512 return hasStream(streams, stream) && isStreamActive(stream, 0);
6513 };
Eric Laurent484e9272018-06-07 17:29:23 -07006514
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306515 auto doGetOutputDevicesForVoice = [&]() {
6516 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006517 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306518 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006519 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6520 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306521 };
6522
6523 // With low-latency playing on speaker, music on WFD, when the first low-latency
6524 // output is stopped, getNewOutputDevices checks for a product strategy
6525 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006526 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306527 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6528 // stream is associated to the output descriptor.
6529 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6530 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6531 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6532 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006533 // Retrieval of devices for voice DL is done on primary output profile, cannot
6534 // check the route (would force modifying configuration file for this profile)
6535 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6536 break;
6537 }
Eric Laurente552edb2014-03-10 17:42:56 -07006538 }
François Gaffiec005e562018-11-06 15:04:49 +01006539 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006540 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006541}
6542
François Gaffie11d30102018-11-02 16:09:09 +01006543sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6544 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006545{
François Gaffie11d30102018-11-02 16:09:09 +01006546 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006547
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006548 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006549 if (index >= 0) {
6550 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006551 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006552 ALOGV("getNewInputDevice() device %s forced by patch %d",
6553 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6554 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006555 }
6556 }
6557
Eric Laurent97ac8712018-07-27 18:59:02 -07006558 // Honor explicit routing requests only if no client using default routing is active on this
6559 // input: a specific app can not force routing for other apps by setting a preferred device.
6560 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006561 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6562 if (device != nullptr) {
6563 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006564 }
6565
Eric Laurentdc95a252018-04-12 12:46:56 -07006566 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006567 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006568 audio_attributes_t attributes;
6569 uid_t uid;
6570 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6571 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006572 attributes = topClient->attributes();
6573 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006574 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006575 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6576 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006577 }
6578
Francois Gaffie716e1432019-01-14 16:58:59 +01006579 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6580 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006581 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006582 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006583 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006584 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006585
Eric Laurente552edb2014-03-10 17:42:56 -07006586 return device;
6587}
6588
Eric Laurent794fde22016-03-11 09:50:45 -08006589bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6590 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006591 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006592}
6593
Dorin Drimusf2196d82022-01-03 12:11:18 +01006594// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006595status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006596 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006597 if (devices == nullptr) {
6598 return BAD_VALUE;
6599 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006600
6601 // Devices are determined in the following precedence:
6602 //
6603 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6604 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6605 //
6606 // If no such dynamic policy then
6607 // 2) Devices containing an active client using setPreferredDevice
6608 // with same strategy as the attributes.
6609 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6610 //
6611 // If no corresponding active client with setPreferredDevice then
6612 // 3) Devices associated with the strategy determined by the attributes
6613 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6614 //
6615 // See related getOutputForAttrInt().
6616
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006617 // check dynamic policies but only for primary descriptors (secondary not used for audible
6618 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006619 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006620 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Andy Hung6d23c0f2022-02-16 09:37:15 -08006621 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr /* secondaryMixes */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006622 if (status != OK) {
6623 return status;
6624 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006625
6626 DeviceVector curDevices;
6627 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6628 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6629 // as they are unaffected by device/stream volume
6630 // (per SwAudioOutputDescriptor::isFixedVolume()).
6631 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6632 ) {
6633 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6634 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6635 curDevices.add(deviceDesc);
6636 } else {
6637 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6638 // which selects setPreferredDevice if active. This means forVolume call
6639 // will take an active setPreferredDevice, if such exists.
6640
6641 curDevices = mEngine->getOutputDevicesForAttributes(
6642 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006643 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006644
6645 if (forVolume) {
6646 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6647 // for single volume control in AudioService (such relationship should exist if
6648 // SPEAKER_SAFE is present).
6649 //
6650 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6651 DeviceVector speakerSafeDevices =
6652 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6653 if (!speakerSafeDevices.isEmpty()) {
6654 curDevices.merge(
6655 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6656 curDevices.remove(speakerSafeDevices);
6657 }
6658 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006659 for (const auto& device : curDevices) {
6660 devices->push_back(device->getDeviceTypeAddr());
6661 }
6662 return NO_ERROR;
6663}
6664
Eric Laurente0720872014-03-11 09:30:41 -07006665void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006666 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006667 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006668 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006669 updateDevicesAndOutputs();
6670 break;
6671 default:
6672 break;
6673 }
6674}
6675
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006676uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006677
6678 // skip beacon mute management if a dedicated TTS output is available
6679 if (mTtsOutputAvailable) {
6680 return 0;
6681 }
6682
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006683 switch(event) {
6684 case STARTING_OUTPUT:
6685 mBeaconMuteRefCount++;
6686 break;
6687 case STOPPING_OUTPUT:
6688 if (mBeaconMuteRefCount > 0) {
6689 mBeaconMuteRefCount--;
6690 }
6691 break;
6692 case STARTING_BEACON:
6693 mBeaconPlayingRefCount++;
6694 break;
6695 case STOPPING_BEACON:
6696 if (mBeaconPlayingRefCount > 0) {
6697 mBeaconPlayingRefCount--;
6698 }
6699 break;
6700 }
6701
6702 if (mBeaconMuteRefCount > 0) {
6703 // any playback causes beacon to be muted
6704 return setBeaconMute(true);
6705 } else {
6706 // no other playback: unmute when beacon starts playing, mute when it stops
6707 return setBeaconMute(mBeaconPlayingRefCount == 0);
6708 }
6709}
6710
6711uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6712 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6713 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6714 // keep track of muted state to avoid repeating mute/unmute operations
6715 if (mBeaconMuted != mute) {
6716 // mute/unmute AUDIO_STREAM_TTS on all outputs
6717 ALOGV("\t muting %d", mute);
6718 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006719 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6720 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6721 ALOGV("\t no tts volume source available");
6722 return 0;
6723 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006724 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006725 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006726 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006727 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006728 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006729 maxLatency = latency;
6730 }
6731 }
6732 mBeaconMuted = mute;
6733 return maxLatency;
6734 }
6735 return 0;
6736}
6737
Eric Laurente0720872014-03-11 09:30:41 -07006738void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006739{
François Gaffiec005e562018-11-06 15:04:49 +01006740 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006741 mPreviousOutputs = mOutputs;
6742}
6743
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006744uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006745 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006746 uint32_t delayMs)
6747{
6748 // mute/unmute strategies using an incompatible device combination
6749 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6750 // if unmuting, unmute only after the specified delay
6751 if (outputDesc->isDuplicated()) {
6752 return 0;
6753 }
6754
6755 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006756 DeviceVector devices = outputDesc->devices();
6757 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006758
François Gaffiec005e562018-11-06 15:04:49 +01006759 auto productStrategies = mEngine->getOrderedProductStrategies();
6760 for (const auto &productStrategy : productStrategies) {
6761 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6762 DeviceVector curDevices =
6763 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6764 curDevices = curDevices.filter(outputDesc->supportedDevices());
6765 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006766 bool doMute = false;
6767
François Gaffiec005e562018-11-06 15:04:49 +01006768 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006769 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006770 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6771 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006772 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006773 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006774 }
Eric Laurent99401132014-05-07 19:48:15 -07006775 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006776 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006777 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006778 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006779 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006780 continue;
6781 }
François Gaffiec005e562018-11-06 15:04:49 +01006782 ALOGVV("%s() %s (curDevice %s)", __func__,
6783 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6784 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6785 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006786 if (mute) {
6787 // FIXME: should not need to double latency if volume could be applied
6788 // immediately by the audioflinger mixer. We must account for the delay
6789 // between now and the next time the audioflinger thread for this output
6790 // will process a buffer (which corresponds to one buffer size,
6791 // usually 1/2 or 1/4 of the latency).
6792 if (muteWaitMs < desc->latency() * 2) {
6793 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006794 }
6795 }
6796 }
6797 }
6798 }
6799 }
6800
Eric Laurent99401132014-05-07 19:48:15 -07006801 // temporary mute output if device selection changes to avoid volume bursts due to
6802 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006803 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006804 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006805
Eric Laurentdc462862016-07-19 12:29:53 -07006806 if (muteWaitMs < tempMuteWaitMs) {
6807 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006808 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006809
6810 // If recommended duration is defined, replace temporary mute duration to avoid
6811 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6812 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6813 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6814 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6815 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6816
François Gaffieaaac0fd2018-11-22 17:56:39 +01006817 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6818 // make sure that we do not start the temporary mute period too early in case of
6819 // delayed device change
6820 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6821 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006822 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006823 }
6824 }
6825
Eric Laurente552edb2014-03-10 17:42:56 -07006826 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6827 if (muteWaitMs > delayMs) {
6828 muteWaitMs -= delayMs;
6829 usleep(muteWaitMs * 1000);
6830 return muteWaitMs;
6831 }
6832 return 0;
6833}
6834
François Gaffie11d30102018-11-02 16:09:09 +01006835uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6836 const DeviceVector &devices,
6837 bool force,
6838 int delayMs,
6839 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006840 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006841{
François Gaffie11d30102018-11-02 16:09:09 +01006842 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006843 uint32_t muteWaitMs;
6844
6845 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006846 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6847 nullptr /* patchHandle */, requiresMuteCheck);
6848 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6849 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006850 return muteWaitMs;
6851 }
Eric Laurente552edb2014-03-10 17:42:56 -07006852
6853 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006854 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006855 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006856 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006857
François Gaffie11d30102018-11-02 16:09:09 +01006858 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6859
6860 if (!filteredDevices.isEmpty()) {
6861 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006862 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006863
6864 // if the outputs are not materially active, there is no need to mute.
6865 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006866 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006867 } else {
6868 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6869 muteWaitMs = 0;
6870 }
Eric Laurente552edb2014-03-10 17:42:56 -07006871
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006872 bool outputRouted = outputDesc->isRouted();
6873
Eric Laurent79ea9582020-06-11 18:49:24 -07006874 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6875 // output profile or if new device is not supported AND previous device(s) is(are) still
6876 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006877 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006878 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6879 // restore previous device after evaluating strategy mute state
6880 outputDesc->setDevices(prevDevices);
6881 return muteWaitMs;
6882 }
6883
Eric Laurente552edb2014-03-10 17:42:56 -07006884 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006885 // the requested device is AUDIO_DEVICE_NONE
6886 // OR the requested device is the same as current device
6887 // AND force is not specified
6888 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006889 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006890 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01006891 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6892 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006893 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6894 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6895 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6896 }
Eric Laurente552edb2014-03-10 17:42:56 -07006897 return muteWaitMs;
6898 }
6899
François Gaffie11d30102018-11-02 16:09:09 +01006900 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006901
Eric Laurente552edb2014-03-10 17:42:56 -07006902 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006903 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006904 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006905 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006906 PatchBuilder patchBuilder;
6907 patchBuilder.addSource(outputDesc);
6908 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6909 for (const auto &filteredDevice : filteredDevices) {
6910 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006911 }
6912
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006913 // Add half reported latency to delayMs when muteWaitMs is null in order
6914 // to avoid disordered sequence of muting volume and changing devices.
6915 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6916 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006917 }
Eric Laurente552edb2014-03-10 17:42:56 -07006918
6919 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006920 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006921
6922 return muteWaitMs;
6923}
6924
Eric Laurentc75307b2015-03-17 15:29:32 -07006925status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006926 int delayMs,
6927 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006928{
Eric Laurent6a94d692014-05-20 11:18:06 -07006929 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006930 if (patchHandle == nullptr && !outputDesc->isRouted()) {
6931 return INVALID_OPERATION;
6932 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006933 if (patchHandle) {
6934 index = mAudioPatches.indexOfKey(*patchHandle);
6935 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006936 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006937 }
6938 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006939 return INVALID_OPERATION;
6940 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006941 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006942 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006943 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006944 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006945 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006946 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006947 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006948 return status;
6949}
6950
6951status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006952 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006953 bool force,
6954 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006955{
6956 status_t status = NO_ERROR;
6957
Eric Laurent1f2f2232014-06-02 12:01:23 -07006958 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006959 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6960 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006961
François Gaffie11d30102018-11-02 16:09:09 +01006962 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006963 PatchBuilder patchBuilder;
6964 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006965 // AUDIO_SOURCE_HOTWORD is for internal use only:
6966 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006967 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6968 auto result = usecase;
6969 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6970 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6971 }
6972 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006973 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006974 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006975 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006976 }
6977 }
6978 return status;
6979}
6980
Eric Laurent6a94d692014-05-20 11:18:06 -07006981status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6982 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006983{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006984 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006985 ssize_t index;
6986 if (patchHandle) {
6987 index = mAudioPatches.indexOfKey(*patchHandle);
6988 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006989 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006990 }
6991 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006992 return INVALID_OPERATION;
6993 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006994 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006995 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006996 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006997 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006998 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006999 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007000 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007001 return status;
7002}
7003
François Gaffie11d30102018-11-02 16:09:09 +01007004sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007005 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007006 audio_format_t& format,
7007 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007008 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007009{
7010 // Choose an input profile based on the requested capture parameters: select the first available
7011 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007012 //
7013 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7014 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007015
Glenn Kasten730b9262018-03-29 15:01:26 -07007016 sp<IOProfile> firstInexact;
7017 uint32_t updatedSamplingRate = 0;
7018 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7019 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007020 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007021 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007022 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007023 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007024 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007025 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007026 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007027 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007028 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007029 &channelMask /*updatedChannelMask*/,
7030 // FIXME ugly cast
7031 (audio_output_flags_t) flags,
7032 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007033 return profile;
7034 }
François Gaffie11d30102018-11-02 16:09:09 +01007035 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007036 samplingRate,
7037 &updatedSamplingRate,
7038 format,
7039 &updatedFormat,
7040 channelMask,
7041 &updatedChannelMask,
7042 // FIXME ugly cast
7043 (audio_output_flags_t) flags,
7044 false /*exactMatchRequiredForInputFlags*/)) {
7045 firstInexact = profile;
7046 }
7047
Eric Laurente552edb2014-03-10 17:42:56 -07007048 }
7049 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007050 if (firstInexact != nullptr) {
7051 samplingRate = updatedSamplingRate;
7052 format = updatedFormat;
7053 channelMask = updatedChannelMask;
7054 return firstInexact;
7055 }
Eric Laurente552edb2014-03-10 17:42:56 -07007056 return NULL;
7057}
7058
François Gaffieaaac0fd2018-11-22 17:56:39 +01007059float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7060 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007061 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007062 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007063{
jiabin9a3361e2019-10-01 09:38:30 -07007064 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007065
7066 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7067 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7068 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7069 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007070 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7071 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7072 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7073 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7074 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007075
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007076 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007077 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7078 mOutputs.isActive(ringVolumeSrc, 0)) {
7079 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007080 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007081 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007082 }
7083
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007084 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007085 if ((volumeSource != callVolumeSrc && (isInCall() ||
7086 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007087 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007088 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7089 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007090 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7091 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7092 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007093 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007094 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007095 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007096 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007097 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007098 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007099 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7100 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7101 // programmatically muted.
7102 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7103 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7104 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007105 bool exemptFromCapping =
7106 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7107 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007108 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7109 volumeSource, volumeDb);
7110 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007111 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7112 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7113 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007114 }
7115 }
Eric Laurente552edb2014-03-10 17:42:56 -07007116 // if a headset is connected, apply the following rules to ring tones and notifications
7117 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007118 // - always attenuate notifications volume by 6dB
7119 // - attenuate ring tones volume by 6dB unless music is not playing and
7120 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007121 // - if music is playing, always limit the volume to current music volume,
7122 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007123 if (!Intersection(deviceTypes,
7124 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7125 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007126 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7127 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007128 ((volumeSource == alarmVolumeSrc ||
7129 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007130 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7131 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7132 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007133 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7134 curves.canBeMuted()) {
7135
Eric Laurente552edb2014-03-10 17:42:56 -07007136 // when the phone is ringing we must consider that music could have been paused just before
7137 // by the music application and behave as if music was active if the last music track was
7138 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007139 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007140 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007141 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007142 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007143 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7144 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007145 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007146 float musicVolDb = computeVolume(musicCurves,
7147 musicVolumeSrc,
7148 musicCurves.getVolumeIndex(musicDevice),
7149 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007150 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7151 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7152 if (volumeDb > minVolDb) {
7153 volumeDb = minVolDb;
7154 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007155 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007156 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7157 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7158 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007159 // on A2DP, also ensure notification volume is not too low compared to media when
7160 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007161 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007162 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007163 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7164 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007165 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7166 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007167 }
7168 }
jiabin9a3361e2019-10-01 09:38:30 -07007169 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007170 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007171 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007172 }
7173 }
7174
François Gaffie43c73442018-11-08 08:21:55 +01007175 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007176}
7177
Eric Laurent3839bc02018-07-10 18:33:34 -07007178int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007179 VolumeSource fromVolumeSource,
7180 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007181{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007182 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007183 return srcIndex;
7184 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007185 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7186 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007187 float minSrc = (float)srcCurves.getVolumeIndexMin();
7188 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7189 float minDst = (float)dstCurves.getVolumeIndexMin();
7190 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007191
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007192 // preserve mute request or correct range
7193 if (srcIndex < minSrc) {
7194 if (srcIndex == 0) {
7195 return 0;
7196 }
7197 srcIndex = minSrc;
7198 } else if (srcIndex > maxSrc) {
7199 srcIndex = maxSrc;
7200 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007201 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7202}
7203
François Gaffieaaac0fd2018-11-22 17:56:39 +01007204status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7205 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007206 int index,
7207 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007208 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007209 int delayMs,
7210 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007211{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007212 // do not change actual attributes volume if the attributes is muted
7213 if (outputDesc->isMuted(volumeSource)) {
7214 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7215 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007216 return NO_ERROR;
7217 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007218 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7219 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7220 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7221 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007222
Eric Laurent2517af32020-11-25 15:31:27 +01007223 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07007224 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007225 // if sco and call follow same curves, bypass forceUseForComm
7226 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007227 ((isVoiceVolSrc && isScoRequested) ||
7228 (isBtScoVolSrc && !isScoRequested))) {
7229 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
7230 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07007231 // Do not return an error here as AudioService will always set both voice call
7232 // and bluetooth SCO volumes due to stream aliasing.
7233 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007234 }
jiabin9a3361e2019-10-01 09:38:30 -07007235 if (deviceTypes.empty()) {
7236 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007237 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007238
jiabin9a3361e2019-10-01 09:38:30 -07007239 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7240 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007241 // Force VoIP volume to max for bluetooth SCO device except if muted
7242 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007243 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007244 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007245 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007246 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007247 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007248 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007249
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007250 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007251 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007252 // 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 +01007253 if (isVoiceVolSrc) {
7254 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007255 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007256 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007257 }
Eric Laurent18fba842016-03-31 14:41:26 -07007258 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007259 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7260 mLastVoiceVolume = voiceVolume;
7261 }
7262 }
Eric Laurente552edb2014-03-10 17:42:56 -07007263 return NO_ERROR;
7264}
7265
Eric Laurentc75307b2015-03-17 15:29:32 -07007266void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007267 const DeviceTypeSet& deviceTypes,
7268 int delayMs,
7269 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007270{
jiabincd510522020-01-22 09:40:55 -08007271 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007272 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7273 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7274 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007275 curves.getVolumeIndex(deviceTypes),
7276 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007277 }
7278}
7279
François Gaffiec005e562018-11-06 15:04:49 +01007280void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7281 bool on,
7282 const sp<AudioOutputDescriptor>& outputDesc,
7283 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007284 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007285{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007286 std::vector<VolumeSource> sourcesToMute;
7287 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7288 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7289 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007290 VolumeSource source = toVolumeSource(attributes, false);
7291 if ((source != VOLUME_SOURCE_NONE) &&
7292 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7293 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007294 sourcesToMute.push_back(source);
7295 }
Eric Laurente552edb2014-03-10 17:42:56 -07007296 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007297 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007298 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007299 }
7300
Eric Laurente552edb2014-03-10 17:42:56 -07007301}
7302
François Gaffieaaac0fd2018-11-22 17:56:39 +01007303void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7304 bool on,
7305 const sp<AudioOutputDescriptor>& outputDesc,
7306 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007307 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007308{
jiabin9a3361e2019-10-01 09:38:30 -07007309 if (deviceTypes.empty()) {
7310 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007311 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007312 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007313 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007314 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007315 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007316 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007317 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7318 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007319 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007320 }
7321 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007322 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7323 // ignored
7324 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007325 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007326 if (!outputDesc->isMuted(volumeSource)) {
7327 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007328 return;
7329 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007330 if (outputDesc->decMuteCount(volumeSource) == 0) {
7331 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007332 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007333 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007334 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007335 delayMs);
7336 }
7337 }
7338}
7339
François Gaffie53615e22015-03-19 09:24:12 +01007340bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7341{
François Gaffiec005e562018-11-06 15:04:49 +01007342 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007343 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7344 return true;
7345 }
7346
7347 // has known usage?
7348 switch (paa->usage) {
7349 case AUDIO_USAGE_UNKNOWN:
7350 case AUDIO_USAGE_MEDIA:
7351 case AUDIO_USAGE_VOICE_COMMUNICATION:
7352 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7353 case AUDIO_USAGE_ALARM:
7354 case AUDIO_USAGE_NOTIFICATION:
7355 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7356 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7357 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7358 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7359 case AUDIO_USAGE_NOTIFICATION_EVENT:
7360 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7361 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7362 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7363 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007364 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007365 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007366 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007367 case AUDIO_USAGE_EMERGENCY:
7368 case AUDIO_USAGE_SAFETY:
7369 case AUDIO_USAGE_VEHICLE_STATUS:
7370 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007371 break;
7372 default:
7373 return false;
7374 }
7375 return true;
7376}
7377
François Gaffie2110e042015-03-24 08:41:51 +01007378audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7379{
7380 return mEngine->getForceUse(usage);
7381}
7382
7383bool AudioPolicyManager::isInCall()
7384{
7385 return isStateInCall(mEngine->getPhoneState());
7386}
7387
7388bool AudioPolicyManager::isStateInCall(int state)
7389{
7390 return is_state_in_call(state);
7391}
7392
Eric Laurent74b71512019-11-06 17:21:57 -08007393bool AudioPolicyManager::isCallAudioAccessible()
7394{
7395 audio_mode_t mode = mEngine->getPhoneState();
7396 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007397 || (mode == AUDIO_MODE_CALL_SCREEN)
7398 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007399}
7400
Eric Laurentd60560a2015-04-10 11:31:20 -07007401void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7402{
7403 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007404 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007405 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007406 sourceDesc->sinkDevice()->equals(deviceDesc))
7407 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007408 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007409 }
7410 }
7411
7412 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7413 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7414 bool release = false;
7415 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7416 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7417 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7418 source->ext.device.type == deviceDesc->type()) {
7419 release = true;
7420 }
7421 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007422 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007423 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7424 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7425 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007426 sink->ext.device.type == deviceDesc->type() &&
7427 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7428 || strncmp(sink->ext.device.address, address,
7429 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007430 release = true;
7431 }
7432 }
7433 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007434 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7435 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007436 }
7437 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007438
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007439 mInputs.clearSessionRoutesForDevice(deviceDesc);
7440
Francois Gaffie716e1432019-01-14 16:58:59 +01007441 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007442}
7443
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007444void AudioPolicyManager::modifySurroundFormats(
7445 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007446 std::unordered_set<audio_format_t> enforcedSurround(
7447 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007448 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7449 for (const auto& pair : mConfig.getSurroundFormats()) {
7450 allSurround.insert(pair.first);
7451 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7452 }
Phil Burk09bc4612016-02-24 15:58:15 -08007453
7454 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7455 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007456 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007457 // This is the resulting set of formats depending on the surround mode:
7458 // 'all surround' = allSurround
7459 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7460 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7461 // 'manual surround' = mManualSurroundFormats
7462 // AUTO: formats v 'enforced surround'
7463 // ALWAYS: formats v 'all surround' v 'enforced surround'
7464 // NEVER: formats ^ 'non-surround'
7465 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007466
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007467 std::unordered_set<audio_format_t> formatSet;
7468 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7469 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007470 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007471 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007472 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007473 formatSet.insert(*formatIter);
7474 }
7475 }
7476 } else {
7477 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7478 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007479 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007480
jiabin81772902018-04-02 17:52:27 -07007481 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007482 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007483 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7484 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7485 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007486 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007487 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7488 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7489 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007490 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007491 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007492 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007493 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007494 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007495 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007496}
7497
jiabin06e4bab2019-07-29 10:13:34 -07007498void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7499 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007500 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7501 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7502
7503 // If NEVER, then remove support for channelMasks > stereo.
7504 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007505 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7506 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007507 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007508 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007509 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007510 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007511 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007512 }
7513 }
jiabin81772902018-04-02 17:52:27 -07007514 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7515 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7516 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007517 bool supports5dot1 = false;
7518 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007519 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007520 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7521 supports5dot1 = true;
7522 break;
7523 }
7524 }
7525 // If not then add 5.1 support.
7526 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007527 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007528 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007529 }
Phil Burk09bc4612016-02-24 15:58:15 -08007530 }
7531}
7532
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007533void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007534 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007535 AudioProfileVector &profiles)
7536{
7537 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007538 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007539
François Gaffie112b0af2015-11-19 16:13:25 +01007540 // Format MUST be checked first to update the list of AudioProfile
7541 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007542 reply = mpClientInterface->getParameters(
7543 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007544 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007545 AudioParameter repliedParameters(reply);
7546 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007547 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007548 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7549 return;
7550 }
Phil Burk09bc4612016-02-24 15:58:15 -08007551 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007552 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007553 if (device == AUDIO_DEVICE_OUT_HDMI
7554 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007555 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007556 }
jiabin3e277cc2019-09-10 14:27:34 -07007557 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007558 }
François Gaffie112b0af2015-11-19 16:13:25 +01007559
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007560 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007561 ChannelMaskSet channelMasks;
7562 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007563 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007564 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007565
7566 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007567 reply = mpClientInterface->getParameters(
7568 ioHandle,
7569 requestedParameters.toString() + ";" +
7570 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007571 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007572 AudioParameter repliedParameters(reply);
7573 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007574 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007575 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007576 }
7577 }
7578 if (profiles.hasDynamicChannelsFor(format)) {
7579 reply = mpClientInterface->getParameters(ioHandle,
7580 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007581 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007582 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007583 AudioParameter repliedParameters(reply);
7584 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007585 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007586 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007587 if (device == AUDIO_DEVICE_OUT_HDMI
7588 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007589 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007590 }
François Gaffie112b0af2015-11-19 16:13:25 +01007591 }
7592 }
jiabin3e277cc2019-09-10 14:27:34 -07007593 addDynamicAudioProfileAndSort(
7594 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007595 }
7596}
Eric Laurentd60560a2015-04-10 11:31:20 -07007597
Mikhail Naganovdc769682018-05-04 15:34:08 -07007598status_t AudioPolicyManager::installPatch(const char *caller,
7599 audio_patch_handle_t *patchHandle,
7600 AudioIODescriptorInterface *ioDescriptor,
7601 const struct audio_patch *patch,
7602 int delayMs)
7603{
7604 ssize_t index = mAudioPatches.indexOfKey(
7605 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7606 *patchHandle : ioDescriptor->getPatchHandle());
7607 sp<AudioPatch> patchDesc;
7608 status_t status = installPatch(
7609 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7610 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007611 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007612 }
7613 return status;
7614}
7615
7616status_t AudioPolicyManager::installPatch(const char *caller,
7617 ssize_t index,
7618 audio_patch_handle_t *patchHandle,
7619 const struct audio_patch *patch,
7620 int delayMs,
7621 uid_t uid,
7622 sp<AudioPatch> *patchDescPtr)
7623{
7624 sp<AudioPatch> patchDesc;
7625 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7626 if (index >= 0) {
7627 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007628 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007629 }
7630
7631 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7632 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7633 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7634 if (status == NO_ERROR) {
7635 if (index < 0) {
7636 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007637 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007638 } else {
7639 patchDesc->mPatch = *patch;
7640 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007641 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007642 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007643 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007644 }
7645 nextAudioPortGeneration();
7646 mpClientInterface->onAudioPatchListUpdate();
7647 }
7648 if (patchDescPtr) *patchDescPtr = patchDesc;
7649 return status;
7650}
7651
jiabinbce0c1d2020-10-05 11:20:18 -07007652bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7653{
7654 const TrackClientVector activeClients = output->getActiveClients();
7655 if (activeClients.empty()) {
7656 return true;
7657 }
7658 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7659 if (index < 0) {
7660 ALOGE("%s, no audio patch found while there are active clients on output %d",
7661 __func__, output->getId());
7662 return false;
7663 }
7664 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7665 DeviceVector routedDevices;
7666 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7667 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7668 patchDesc->mPatch.sinks[i].id);
7669 if (device == nullptr) {
7670 ALOGE("%s, no audio device found with id(%d)",
7671 __func__, patchDesc->mPatch.sinks[i].id);
7672 return false;
7673 }
7674 routedDevices.add(device);
7675 }
7676 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007677 if (client->isInvalid()) {
7678 // No need to take care about invalidated clients.
7679 continue;
7680 }
jiabinbce0c1d2020-10-05 11:20:18 -07007681 sp<DeviceDescriptor> preferredDevice =
7682 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7683 if (mEngine->getOutputDevicesForAttributes(
7684 client->attributes(), preferredDevice, false) == routedDevices) {
7685 return false;
7686 }
7687 }
7688 return true;
7689}
7690
7691sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007692 const sp<IOProfile>& profile, const DeviceVector& devices,
7693 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007694{
7695 for (const auto& device : devices) {
7696 // TODO: This should be checking if the profile supports the device combo.
7697 if (!profile->supportsDevice(device)) {
7698 return nullptr;
7699 }
7700 }
7701 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7702 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007703 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007704 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7705 if (status != NO_ERROR) {
7706 return nullptr;
7707 }
7708
7709 // Here is where the out_set_parameters() for card & device gets called
7710 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7711 const audio_devices_t deviceType = device->type();
7712 const String8 &address = String8(device->address().c_str());
7713 if (!address.isEmpty()) {
7714 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7715 mpClientInterface->setParameters(output, String8(param));
7716 free(param);
7717 }
7718 updateAudioProfiles(device, output, profile->getAudioProfiles());
7719 if (!profile->hasValidAudioProfile()) {
7720 ALOGW("%s() missing param", __func__);
7721 desc->close();
7722 return nullptr;
7723 } else if (profile->hasDynamicAudioProfile()) {
7724 desc->close();
7725 output = AUDIO_IO_HANDLE_NONE;
7726 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7727 profile->pickAudioProfile(
7728 config.sample_rate, config.channel_mask, config.format);
7729 config.offload_info.sample_rate = config.sample_rate;
7730 config.offload_info.channel_mask = config.channel_mask;
7731 config.offload_info.format = config.format;
7732
Eric Laurentb4f42a92022-01-17 17:37:31 +01007733 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007734 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7735 if (status != NO_ERROR) {
7736 return nullptr;
7737 }
7738 }
7739
7740 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007741
jiabinbce0c1d2020-10-05 11:20:18 -07007742 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7743 sp<AudioPolicyMix> policyMix;
7744 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7745 policyMix->setOutput(desc);
7746 desc->mPolicyMix = policyMix;
7747 } else {
7748 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7749 address.string());
7750 }
7751
Eric Laurentb4f42a92022-01-17 17:37:31 +01007752 } else if (hasPrimaryOutput() && profile->getModule()
7753 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7754 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7755 // no duplicated output for:
7756 // - direct outputs
7757 // - outputs used by dynamic policy mixes
7758 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007759 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7760
7761 //TODO: configure audio effect output stage here
7762
7763 // open a duplicating output thread for the new output and the primary output
7764 sp<SwAudioOutputDescriptor> dupOutputDesc =
7765 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7766 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7767 if (status == NO_ERROR) {
7768 // add duplicated output descriptor
7769 addOutput(duplicatedOutput, dupOutputDesc);
7770 } else {
7771 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7772 mPrimaryOutput->mIoHandle, output);
7773 desc->close();
7774 removeOutput(output);
7775 nextAudioPortGeneration();
7776 return nullptr;
7777 }
7778 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007779 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7780 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7781 mPrimaryOutput = desc;
7782 }
jiabinbce0c1d2020-10-05 11:20:18 -07007783 return desc;
7784}
7785
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007786} // namespace android