blob: a97ca71450393ad18058e5eb217711eb89865f85 [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 Laurent96d1dda2022-03-14 17:14:19 +0100193
194 bool wasLeUnicastActive = isLeUnicastActive();
195
Eric Laurente552edb2014-03-10 17:42:56 -0700196 switch (state)
197 {
198 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800199 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700200 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100201 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700202 return INVALID_OPERATION;
203 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800204 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700205 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700206
Eric Laurente552edb2014-03-10 17:42:56 -0700207 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200208 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700209 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700210 }
211
François Gaffie44481e72016-04-20 07:49:57 +0200212 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
213 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100214 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200215
François Gaffie11d30102018-11-02 16:09:09 +0100216 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
217 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200218
Francois Gaffie716e1432019-01-14 16:58:59 +0100219 mHwModules.cleanUpForDevice(device);
220
François Gaffie11d30102018-11-02 16:09:09 +0100221 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700222 return INVALID_OPERATION;
223 }
François Gaffie2110e042015-03-24 08:41:51 +0100224
jiabin1c4794b2020-05-05 10:08:05 -0700225 // Populate encapsulation information when a output device is connected.
226 device->setEncapsulationInfoFromHal(mpClientInterface);
227
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700228 // outputs should never be empty here
229 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
230 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100231 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800232
Eric Laurent3ae5f312015-02-03 17:12:08 -0800233 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700234 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700235 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100237 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700238 return INVALID_OPERATION;
239 }
240
François Gaffie11d30102018-11-02 16:09:09 +0100241 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700242
Paul McLeane743a472015-01-28 11:07:31 -0800243 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100244 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700245
Eric Laurente552edb2014-03-10 17:42:56 -0700246 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100247 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700248
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100249 mOutputs.clearSessionRoutesForDevice(device);
250
François Gaffie11d30102018-11-02 16:09:09 +0100251 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100252
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800253 // Reset active device codec
254 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
255
Kriti Dangef6be8f2020-11-05 11:58:19 +0100256 // remove device from mReportedFormatsMap cache
257 mReportedFormatsMap.erase(device);
258
Eric Laurente552edb2014-03-10 17:42:56 -0700259 } break;
260
261 default:
François Gaffie11d30102018-11-02 16:09:09 +0100262 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700263 return BAD_VALUE;
264 }
265
Eric Laurent736a1022019-03-27 18:28:46 -0700266 // Propagate device availability to Engine
267 setEngineDeviceConnectionState(device, state);
268
Eric Laurentae970022019-01-29 14:25:04 -0800269 // No need to evaluate playback routing when connecting a remote submix
270 // output device used by a dynamic policy of type recorder as no
271 // playback use case is affected.
272 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700273 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800274 for (audio_io_handle_t output : outputs) {
275 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800276 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
277 if (policyMix != nullptr
278 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700279 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800280 doCheckForDeviceAndOutputChanges = false;
281 break;
282 }
283 }
284 }
285
286 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700287 // outputs must be closed after checkOutputForAllStrategies() is executed
288 if (!outputs.isEmpty()) {
289 for (audio_io_handle_t output : outputs) {
290 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100291 // close unused outputs after device disconnection or direct outputs that have
292 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200293 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
294 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurent39095982021-08-24 18:29:27 +0200295 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200296 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 closeOutput(output);
298 }
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
301 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700302 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700303 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800304 };
305
306 if (doCheckForDeviceAndOutputChanges) {
307 checkForDeviceAndOutputChanges(checkCloseOutputs);
308 } else {
309 checkCloseOutputs();
310 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100311 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700312 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100313 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700314 const DeviceVector activeMediaDevices =
315 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700316 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700317 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530318 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
319 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100320 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700321 // do not force device change on duplicated output because if device is 0, it will
322 // also force a device 0 for the two outputs it is duplicated to which may override
323 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100324 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100325 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700326 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 // always force when disconnecting (a non-duplicated device)
328 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100329 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700330 }
jiabinbce0c1d2020-10-05 11:20:18 -0700331 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000332 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700333 desc->supportsDevicesForPlayback(activeMediaDevices)) {
334 // Reopen the output to query the dynamic profiles when there is not active
335 // clients or all active clients will be rerouted. Otherwise, set the flag
336 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
337 // can be reopened to query dynamic profiles when all clients are inactive.
338 if (areAllActiveTracksRerouted(desc)) {
339 outputsToReopen.push_back(mOutputs.keyAt(i));
340 } else {
341 desc->mPendingReopenToQueryProfiles = true;
342 }
343 }
344 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
345 // Clear the flag that previously set for re-querying profiles.
346 desc->mPendingReopenToQueryProfiles = false;
347 }
348 }
349 for (const auto& output : outputsToReopen) {
350 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
351 closeOutput(output);
352 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700353 }
354
Eric Laurentd60560a2015-04-10 11:31:20 -0700355 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100356 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700357 }
358
Eric Laurent96d1dda2022-03-14 17:14:19 +0100359 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
360
Eric Laurent72aa32f2014-05-30 18:51:48 -0700361 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700362 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700363 } // end if is output device
364
Eric Laurente552edb2014-03-10 17:42:56 -0700365 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700366 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100367 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700368 switch (state)
369 {
370 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700371 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700372 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100373 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700374 return INVALID_OPERATION;
375 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700376
377 if (mAvailableInputDevices.add(device) < 0) {
378 return NO_MEMORY;
379 }
380
François Gaffie44481e72016-04-20 07:49:57 +0200381 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
382 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100383 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200384
Eric Laurent0dd51852019-04-19 18:18:58 -0700385 if (checkInputsForDevice(device, state) != NO_ERROR) {
386 mAvailableInputDevices.remove(device);
387
François Gaffie11d30102018-11-02 16:09:09 +0100388 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100389
390 mHwModules.cleanUpForDevice(device);
391
Eric Laurentd4692962014-05-05 18:13:44 -0700392 return INVALID_OPERATION;
393 }
394
Eric Laurentd4692962014-05-05 18:13:44 -0700395 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700396
397 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700398 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700399 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100400 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700401 return INVALID_OPERATION;
402 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700403
François Gaffie11d30102018-11-02 16:09:09 +0100404 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700405
406 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100407 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700408
François Gaffie11d30102018-11-02 16:09:09 +0100409 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700410
411 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100412
413 // remove device from mReportedFormatsMap cache
414 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700415 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700416
417 default:
François Gaffie11d30102018-11-02 16:09:09 +0100418 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700419 return BAD_VALUE;
420 }
421
Eric Laurent736a1022019-03-27 18:28:46 -0700422 // Propagate device availability to Engine
423 setEngineDeviceConnectionState(device, state);
424
Eric Laurent0dd51852019-04-19 18:18:58 -0700425 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700426 // As the input device list can impact the output device selection, update
427 // getDeviceForStrategy() cache
428 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700429
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100430 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200431 // Reconnect Audio Source
432 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
433 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
434 checkAudioSourceForAttributes(attributes);
435 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700436 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100437 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700438 }
439
Eric Laurentb52c1522014-05-20 11:27:36 -0700440 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700441 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700442 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700443
François Gaffie11d30102018-11-02 16:09:09 +0100444 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700445 return BAD_VALUE;
446}
447
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100448status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
449 const char* device_name,
450 media::AudioPort* aidlPort) {
451 DeviceDescriptorBase devDescr(device, device_address);
452 devDescr.setName(device_name);
453 return devDescr.writeToParcelable(aidlPort);
454}
455
Eric Laurent736a1022019-03-27 18:28:46 -0700456void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
457 audio_policy_dev_state_t state) {
458
459 // the Engine does not have to know about remote submix devices used by dynamic audio policies
460 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
461 return;
462 }
463 mEngine->setDeviceConnectionState(device, state);
464}
465
466
Eric Laurente0720872014-03-11 09:30:41 -0700467audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100468 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700469{
Eric Laurent634b7142016-04-20 13:48:02 -0700470 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800471 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
472 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700473 (strlen(device_address) != 0)/*matchAddress*/);
474
475 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100476 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700477 device, device_address);
478 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
479 }
François Gaffie53615e22015-03-19 09:24:12 +0100480
Eric Laurent3a4311c2014-03-17 12:00:47 -0700481 DeviceVector *deviceVector;
482
Eric Laurente552edb2014-03-10 17:42:56 -0700483 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700484 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700485 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700486 deviceVector = &mAvailableInputDevices;
487 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100488 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700489 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700490 }
Eric Laurent634b7142016-04-20 13:48:02 -0700491
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800492 return (deviceVector->getDevice(
493 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700494 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800495}
496
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800497status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
498 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800499 const char *device_name,
500 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501{
502 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700503 String8 reply;
504 AudioParameter param;
505 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800506
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800507 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
508 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800509
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800510 // connect/disconnect only 1 device at a time
511 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
512
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700514 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800515 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516 // Nothing to do: device is not connected
517 return NO_ERROR;
518 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700521 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 // configure codecs.
523 // Handle two specific cases by sending a set parameter to
524 // configure A2DP codecs. No need to toggle device state.
525 // Case 1: A2DP active device switches from primary to primary
526 // module
527 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200528 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700529 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800530 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
531 if (availablePrimaryOutputDevices().contains(devDesc) &&
532 (module != 0 && module->getHandle() == primaryHandle)) {
533 reply = mpClientInterface->getParameters(
534 AUDIO_IO_HANDLE_NONE,
535 String8(AudioParameter::keyReconfigA2dpSupported));
536 AudioParameter repliedParameters(reply);
537 repliedParameters.getInt(
538 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
539 if (isReconfigA2dpSupported) {
540 const String8 key(AudioParameter::keyReconfigA2dp);
541 param.add(key, String8("true"));
542 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
543 devDesc->setEncodedFormat(encodedFormat);
544 return NO_ERROR;
545 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700546 }
547 }
cnx421bd2dcc42020-07-11 14:58:44 +0800548 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
549 for (size_t i = 0; i < mOutputs.size(); i++) {
550 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
551 // mute media strategies and delay device switch by the largest
552 // This avoid sending the music tail into the earpiece or headset.
553 setStrategyMute(musicStrategy, true, desc);
554 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
555 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
556 nullptr, true /*fromCache*/).types());
557 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800558 // Toggle the device state: UNAVAILABLE -> AVAILABLE
559 // This will force reading again the device configuration
560 status = setDeviceConnectionState(device,
561 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800562 device_address, device_name,
563 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800564 if (status != NO_ERROR) {
565 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
566 status);
567 return status;
568 }
569
570 status = setDeviceConnectionState(device,
571 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800572 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800573 if (status != NO_ERROR) {
574 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
575 status);
576 return status;
577 }
578
579 return NO_ERROR;
580}
581
Pattydd807582021-11-04 21:01:03 +0800582status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
583 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800584{
Pattydd807582021-11-04 21:01:03 +0800585 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800586 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800587 std::unordered_set<audio_format_t> formatSet;
588 sp<HwModule> primaryModule =
589 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700590 if (primaryModule == nullptr) {
591 ALOGE("%s() unable to get primary module", __func__);
592 return NO_INIT;
593 }
Pattydd807582021-11-04 21:01:03 +0800594
595 DeviceTypeSet audioDeviceSet;
596
597 switch(device) {
598 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
599 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
600 break;
601 case AUDIO_DEVICE_OUT_BLE_HEADSET:
602 audioDeviceSet = getAudioDeviceOutAllBleSet();
603 break;
604 default:
605 ALOGE("%s() device type 0x%08x not supported", __func__, device);
606 return BAD_VALUE;
607 }
608
jiabin9a3361e2019-10-01 09:38:30 -0700609 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800610 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800611 for (const auto& device : declaredDevices) {
612 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800613 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800614 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800615 return status;
616}
617
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100618DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
619{
620 DeviceVector rxSinkdevices{};
621 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
622 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
623 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
624 auto rxSinkDevice = rxSinkdevices.itemAt(0);
625 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
626 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
627 // retrieve Rx Source device descriptor
628 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
629 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
630
631 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
632 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
633 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
634 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
635 return DeviceVector(rxSinkDevice);
636 }
637 }
638 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
639 // the device returned is not necessarily reachable via this output
640 // (filter later by setOutputDevices())
641 return getNewOutputDevices(mPrimaryOutput, fromCache);
642}
643
644status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
645{
646 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
647 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
648 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
649 }
650 return INVALID_OPERATION;
651}
652
653status_t AudioPolicyManager::updateCallRoutingInternal(
654 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700655{
656 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100657 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700658 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700659 if(!hasPrimaryOutput() ||
660 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100661 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700662 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100663 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100664
Francois Gaffie716e1432019-01-14 16:58:59 +0100665 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100666 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100667 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100668
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100669 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100670 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671
Francois Gaffie601801d2021-06-22 13:27:39 +0200672 disconnectTelephonyAudioSource(mCallRxSourceClient);
673 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674
François Gaffie9eb18552018-11-05 10:33:26 +0100675 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700676 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100677 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700678 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100679 // retrieve Rx Source and Tx Sink device descriptors
680 sp<DeviceDescriptor> rxSourceDevice =
681 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
682 String8(),
683 AUDIO_FORMAT_DEFAULT);
684 sp<DeviceDescriptor> txSinkDevice =
685 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
686 String8(),
687 AUDIO_FORMAT_DEFAULT);
688
689 // RX and TX Telephony device are declared by Primary Audio HAL
690 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
691 (telephonyRxModule->getHalVersionMajor() >= 3)) {
692 if (rxSourceDevice == 0 || txSinkDevice == 0) {
693 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100694 ALOGE("%s() no telephony Tx and/or RX device", __func__);
695 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100696 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100697 // createAudioPatchInternal now supports both HW / SW bridging
698 createRxPatch = true;
699 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100700 } else {
701 // If the RX device is on the primary HW module, then use legacy routing method for
702 // voice calls via setOutputDevice() on primary output.
703 // Otherwise, create two audio patches for TX and RX path.
704 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
705 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700706 // If the TX device is also on the primary HW module, setOutputDevice() will take care
707 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100708 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
709 (txSinkDevice != 0);
710 }
711 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
712 // Otherwise, create two audio patches for TX and RX path.
713 if (!createRxPatch) {
714 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700715 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200716 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800717 // If the TX device is on the primary HW module but RX device is
718 // on other HW module, SinkMetaData of telephony input should handle it
719 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700720 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700721 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100722 // terminate active capture if on the same HW module as the call TX source device
723 // FIXME: would be better to refine to only inputs whose profile connects to the
724 // call TX device but this information is not in the audio patch and logic here must be
725 // symmetric to the one in startInput()
726 for (const auto& activeDesc : mInputs.getActiveInputs()) {
727 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
728 closeActiveClients(activeDesc);
729 }
730 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200731 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800732 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100733 if (waitMs != nullptr) {
734 *waitMs = muteWaitMs;
735 }
736 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800737}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700738
Mikhail Naganov100f0122018-11-29 11:22:16 -0800739bool AudioPolicyManager::isDeviceOfModule(
740 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
741 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
742 if (module != 0) {
743 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
744 .indexOf(devDesc) != NAME_NOT_FOUND
745 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
746 .indexOf(devDesc) != NAME_NOT_FOUND;
747 }
748 return false;
749}
750
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200751void AudioPolicyManager::connectTelephonyRxAudioSource()
752{
Francois Gaffie601801d2021-06-22 13:27:39 +0200753 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200754 const struct audio_port_config source = {
755 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
756 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
757 };
758 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200759 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
760 ALOGE_IF(mCallRxSourceClient == nullptr,
761 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200762}
763
Francois Gaffie601801d2021-06-22 13:27:39 +0200764void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200765{
Francois Gaffie601801d2021-06-22 13:27:39 +0200766 if (clientDesc == nullptr) {
767 return;
768 }
769 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
770 "%s error stopping audio source", __func__);
771 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200772}
773
774void AudioPolicyManager::connectTelephonyTxAudioSource(
775 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
776 uint32_t delayMs)
777{
Francois Gaffie601801d2021-06-22 13:27:39 +0200778 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200779 if (srcDevice == nullptr || sinkDevice == nullptr) {
780 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
781 return;
782 }
783 PatchBuilder patchBuilder;
784 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
785 ALOGV("%s between source %s and sink %s", __func__,
786 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200787 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200788 const audio_attributes_t aa = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
789 struct audio_port_config source = {};
790 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200791 mCallTxSourceClient = new InternalSourceClientDescriptor(
792 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200793 mCommunnicationStrategy, toVolumeSource(aa));
794 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
795 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200796 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
797 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200798 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
799 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200800 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200801 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200802}
803
Eric Laurente0720872014-03-11 09:30:41 -0700804void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700805{
806 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100807 // store previous phone state for management of sonification strategy below
808 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100809 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100810
811 if (mEngine->setPhoneState(state) != NO_ERROR) {
812 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700813 return;
814 }
François Gaffie2110e042015-03-24 08:41:51 +0100815 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700816 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700817 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700818 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800819 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700820 }
821
François Gaffie2110e042015-03-24 08:41:51 +0100822 /**
823 * Switching to or from incall state or switching between telephony and VoIP lead to force
824 * routing command.
825 */
Eric Laurent74b71512019-11-06 17:21:57 -0800826 bool force = ((isStateInCall(oldState) != isStateInCall(state))
827 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700828
829 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700830 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700831
Eric Laurente552edb2014-03-10 17:42:56 -0700832 int delayMs = 0;
833 if (isStateInCall(state)) {
834 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100835 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
836 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700837 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700838 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700839 // mute media and sonification strategies and delay device switch by the largest
840 // latency of any output where either strategy is active.
841 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100842 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
843 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
844 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700845 (delayMs < (int)desc->latency()*2)) {
846 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700847 }
François Gaffiec005e562018-11-06 15:04:49 +0100848 setStrategyMute(musicStrategy, true, desc);
849 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
850 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
851 nullptr, true /*fromCache*/).types());
852 setStrategyMute(sonificationStrategy, true, desc);
853 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
854 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
855 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700856 }
857 }
858
Eric Laurent87ffa392015-05-22 10:32:38 -0700859 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700860 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100861 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700862 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100863 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
864 // force routing command to audio hardware when ending call
865 // even if no device change is needed
866 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
867 rxDevices = mPrimaryOutput->devices();
868 }
869 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200870 disconnectTelephonyAudioSource(mCallRxSourceClient);
871 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100872 }
François Gaffie11d30102018-11-02 16:09:09 +0100873 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700874 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700875 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700876
877 // reevaluate routing on all outputs in case tracks have been started during the call
878 for (size_t i = 0; i < mOutputs.size(); i++) {
879 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100880 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200881 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
882 bool forceRouting = !newDevices.isEmpty();
883 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
884 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700885 }
886 }
887
Eric Laurent96d1dda2022-03-14 17:14:19 +0100888 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
889
Eric Laurente552edb2014-03-10 17:42:56 -0700890 if (isStateInCall(state)) {
891 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700892 // force reevaluating accessibility routing when call starts
893 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700894 }
895
896 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100897 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
898 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700899}
900
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700901audio_mode_t AudioPolicyManager::getPhoneState() {
902 return mEngine->getPhoneState();
903}
904
Eric Laurente0720872014-03-11 09:30:41 -0700905void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100906 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700907{
François Gaffie2110e042015-03-24 08:41:51 +0100908 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700909 if (config == mEngine->getForceUse(usage)) {
910 return;
911 }
Eric Laurente552edb2014-03-10 17:42:56 -0700912
François Gaffie2110e042015-03-24 08:41:51 +0100913 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
914 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
915 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700916 }
François Gaffie2110e042015-03-24 08:41:51 +0100917 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
918 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
919 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700920
921 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700922 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800923
Eric Laurent22fcda22019-05-17 16:28:47 -0700924 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
925 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
926 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
927 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
928 }
929
Eric Laurentdc462862016-07-19 12:29:53 -0700930 //FIXME: workaround for truncated touch sounds
931 // to be removed when the problem is handled by system UI
932 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700933 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
934 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
935 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700936
937 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100938 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700939}
940
Eric Laurente0720872014-03-11 09:30:41 -0700941void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700942{
943 ALOGV("setSystemProperty() property %s, value %s", property, value);
944}
945
Dorin Drimusecc9f422022-03-09 17:57:40 +0100946// Find an MSD output profile compatible with the parameters passed.
947// When "directOnly" is set, restrict search to profiles for direct outputs.
948sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
949 const DeviceVector& devices,
950 uint32_t samplingRate,
951 audio_format_t format,
952 audio_channel_mask_t channelMask,
953 audio_output_flags_t flags,
954 bool directOnly)
955{
956 flags = getRelevantFlags(flags, directOnly);
957
958 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
959 if (msdModule != nullptr) {
960 // for the msd module check if there are patches to the output devices
961 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
962 HwModuleCollection modules;
963 modules.add(msdModule);
964 return searchCompatibleProfileHwModules(
965 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
966 flags, directOnly);
967 }
968 }
969 return nullptr;
970}
971
Michael Chana94fbb22018-04-24 14:31:19 +1000972// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
973// search to profiles for direct outputs.
974sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100975 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000976 uint32_t samplingRate,
977 audio_format_t format,
978 audio_channel_mask_t channelMask,
979 audio_output_flags_t flags,
980 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700981{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100982 flags = getRelevantFlags(flags, directOnly);
983
984 return searchCompatibleProfileHwModules(
985 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
986}
987
988audio_output_flags_t AudioPolicyManager::getRelevantFlags (
989 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000990 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100991 // only retain flags that will drive the direct output profile selection
992 // if explicitly requested
993 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000994 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100995 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
996 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +1000997 }
Dorin Drimusecc9f422022-03-09 17:57:40 +0100998 return flags;
999}
Eric Laurent861a6282015-05-18 15:40:16 -07001000
Dorin Drimusecc9f422022-03-09 17:57:40 +01001001sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1002 const HwModuleCollection& hwModules,
1003 const DeviceVector& devices,
1004 uint32_t samplingRate,
1005 audio_format_t format,
1006 audio_channel_mask_t channelMask,
1007 audio_output_flags_t flags,
1008 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001009 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001010 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001011 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001012 if (!curProfile->isCompatibleProfile(devices,
1013 samplingRate, NULL /*updatedSamplingRate*/,
1014 format, NULL /*updatedFormat*/,
1015 channelMask, NULL /*updatedChannelMask*/,
1016 flags)) {
1017 continue;
1018 }
1019 // reject profiles not corresponding to a device currently available
1020 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1021 continue;
1022 }
1023 // reject profiles if connected device does not support codec
1024 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1025 continue;
1026 }
1027 if (!directOnly) {
1028 return curProfile;
1029 }
1030
1031 // when searching for direct outputs, if several profiles are compatible, give priority
1032 // to one with offload capability
1033 if (profile != 0 &&
1034 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001035 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 }
1037 profile = curProfile;
1038 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1039 break;
1040 }
Eric Laurente552edb2014-03-10 17:42:56 -07001041 }
1042 }
Eric Laurent861a6282015-05-18 15:40:16 -07001043 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001044}
1045
Eric Laurentfa0f6742021-08-17 18:39:44 +02001046sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001047 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001048{
1049 for (const auto& hwModule : mHwModules) {
1050 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001051 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001052 continue;
1053 }
1054 // reject profiles not corresponding to a device currently available
1055 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1056 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1057 continue;
1058 }
1059 if (!devices.empty()) {
1060 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1061 != devices.size()) {
1062 continue;
1063 }
1064 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001065 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1066 return curProfile;
1067 }
1068 }
1069 return nullptr;
1070}
1071
Eric Laurentf4e63452017-11-06 19:31:46 +00001072audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001073{
François Gaffiec005e562018-11-06 15:04:49 +01001074 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001075
1076 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1077 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1078 // format, flags, etc. This may result in some discrepancy for functions that utilize
1079 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1080 // and AudioSystem::getOutputSamplingRate().
1081
François Gaffie11d30102018-11-02 16:09:09 +01001082 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001083 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001084
François Gaffie11d30102018-11-02 16:09:09 +01001085 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1086 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001087 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001088}
1089
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001090status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1091 const audio_attributes_t *srcAttr,
1092 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001093{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001094 if (srcAttr != NULL) {
1095 if (!isValidAttributes(srcAttr)) {
1096 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1097 __func__,
1098 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1099 srcAttr->tags);
1100 return BAD_VALUE;
1101 }
1102 *dstAttr = *srcAttr;
1103 } else {
1104 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1105 ALOGE("%s: invalid stream type", __func__);
1106 return BAD_VALUE;
1107 }
François Gaffiec005e562018-11-06 15:04:49 +01001108 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001109 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001110
1111 // Only honor audibility enforced when required. The client will be
1112 // forced to reconnect if the forced usage changes.
1113 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001114 dstAttr->flags = static_cast<audio_flags_mask_t>(
1115 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001116 }
1117
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001118 return NO_ERROR;
1119}
1120
Kevin Rocard153f92d2018-12-18 18:33:28 -08001121status_t AudioPolicyManager::getOutputForAttrInt(
1122 audio_attributes_t *resultAttr,
1123 audio_io_handle_t *output,
1124 audio_session_t session,
1125 const audio_attributes_t *attr,
1126 audio_stream_type_t *stream,
1127 uid_t uid,
1128 const audio_config_t *config,
1129 audio_output_flags_t *flags,
1130 audio_port_handle_t *selectedDeviceId,
1131 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001132 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001133 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001134{
François Gaffiec005e562018-11-06 15:04:49 +01001135 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001136 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001137 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001138 const sp<DeviceDescriptor> requestedDevice =
1139 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1140
Eric Laurent8a1095a2019-11-08 14:44:16 -08001141 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001142 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1143 if (status != NO_ERROR) {
1144 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001145 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001146 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001147 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001148 }
François Gaffiec005e562018-11-06 15:04:49 +01001149 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001150
François Gaffiec005e562018-11-06 15:04:49 +01001151 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1152 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001153
Kevin Rocard153f92d2018-12-18 18:33:28 -08001154 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1155 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1156 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001157 sp<AudioPolicyMix> primaryMix;
1158 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001159 if (status != OK) {
1160 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001161 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001162
Kevin Rocard153f92d2018-12-18 18:33:28 -08001163 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001164 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001165
1166 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001167 if ((usePrimaryOutputFromPolicyMixes
1168 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001169 && !audio_is_linear_pcm(config->format)) {
1170 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001171 return BAD_VALUE;
1172 }
1173 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001174 sp<DeviceDescriptor> deviceDesc =
1175 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1176 primaryMix->mDeviceAddress,
1177 AUDIO_FORMAT_DEFAULT);
1178 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001179 if (deviceDesc != nullptr
1180 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001181 audio_io_handle_t newOutput;
1182 status = openDirectOutput(
1183 *stream, session, config,
1184 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1185 DeviceVector(deviceDesc), &newOutput);
1186 if (status != NO_ERROR) {
1187 policyDesc = nullptr;
1188 } else {
1189 policyDesc = mOutputs.valueFor(newOutput);
1190 primaryMix->setOutput(policyDesc);
1191 }
1192 }
1193 if (policyDesc != nullptr) {
1194 policyDesc->mPolicyMix = primaryMix;
1195 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001196 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001197
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001198 ALOGV("getOutputForAttr() returns output %d", *output);
1199 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1200 *outputType = API_OUT_MIX_PLAYBACK;
1201 } else {
1202 *outputType = API_OUTPUT_LEGACY;
1203 }
1204 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001205 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001206 }
François Gaffiec005e562018-11-06 15:04:49 +01001207 // Virtual sources must always be dynamicaly or explicitly routed
1208 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1209 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1210 return BAD_VALUE;
1211 }
1212 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1213 // in order to let the choice of the order to future vendor engine
1214 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001215
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001216 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001217 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001218 }
1219
Nadav Barb2f18162018-07-18 13:01:53 +03001220 // Set incall music only if device was explicitly set, and fallback to the device which is
1221 // chosen by the engine if not.
1222 // FIXME: provide a more generic approach which is not device specific and move this back
1223 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001224 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001225 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001226 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001227 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001228 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001229 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001230 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001231 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001232 }
1233 }
1234
François Gaffiec005e562018-11-06 15:04:49 +01001235 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1236 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1237 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001238
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001239 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001240 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001241 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001242 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001243 ALOGV("%s() Using MSD devices %s instead of devices %s",
1244 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001245 } else {
1246 *output = AUDIO_IO_HANDLE_NONE;
1247 }
1248 }
1249 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001250 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001251 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001252 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001253 if (*output == AUDIO_IO_HANDLE_NONE) {
1254 return INVALID_OPERATION;
1255 }
Paul McLeanaa981192015-03-21 09:55:15 -07001256
François Gaffiec005e562018-11-06 15:04:49 +01001257 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001258 for (auto &outputDevice : outputDevices) {
1259 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1260 *selectedDeviceId = outputDevice->getId();
1261 break;
1262 }
1263 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001264
Eric Laurent8a1095a2019-11-08 14:44:16 -08001265 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1266 *outputType = API_OUTPUT_TELEPHONY_TX;
1267 } else {
1268 *outputType = API_OUTPUT_LEGACY;
1269 }
1270
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001271 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1272
1273 return NO_ERROR;
1274}
1275
1276status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1277 audio_io_handle_t *output,
1278 audio_session_t session,
1279 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001280 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001281 const audio_config_t *config,
1282 audio_output_flags_t *flags,
1283 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001284 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001285 std::vector<audio_io_handle_t> *secondaryOutputs,
1286 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001287{
1288 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1289 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1290 return INVALID_OPERATION;
1291 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001292 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001293 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001294 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001295 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001296 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001297 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001298 const sp<DeviceDescriptor> requestedDevice =
1299 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1300
1301 // Prevent from storing invalid requested device id in clients
1302 const audio_port_handle_t sanitizedRequestedPortId =
1303 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1304 *selectedDeviceId = sanitizedRequestedPortId;
1305
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001306 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001307 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001308 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001309 if (status != NO_ERROR) {
1310 return status;
1311 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001312 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001313 if (secondaryOutputs != nullptr) {
1314 for (auto &secondaryMix : secondaryMixes) {
1315 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1316 if (outputDesc != nullptr &&
1317 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1318 secondaryOutputs->push_back(outputDesc->mIoHandle);
1319 weakSecondaryOutputDescs.push_back(outputDesc);
1320 }
1321 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001322 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001323
Eric Laurent8fc147b2018-07-22 19:13:55 -07001324 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001325 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001326 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001327 };
jiabin4ef93452019-09-10 14:29:54 -07001328 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001329
Eric Laurentc209fe42020-06-05 18:11:23 -07001330 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001331 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001332 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001333 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001334 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001335 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001336 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001337 std::move(weakSecondaryOutputDescs),
1338 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001339 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001340
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001341 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1342 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001343
Eric Laurente83b55d2014-11-14 10:06:21 -08001344 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001345}
1346
Eric Laurentc529cf62020-04-17 18:19:10 -07001347status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1348 audio_session_t session,
1349 const audio_config_t *config,
1350 audio_output_flags_t flags,
1351 const DeviceVector &devices,
1352 audio_io_handle_t *output) {
1353
1354 *output = AUDIO_IO_HANDLE_NONE;
1355
1356 // skip direct output selection if the request can obviously be attached to a mixed output
1357 // and not explicitly requested
1358 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1359 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1360 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1361 return NAME_NOT_FOUND;
1362 }
1363
1364 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1365 // This prevents creating an offloaded track and tearing it down immediately after start
1366 // when audioflinger detects there is an active non offloadable effect.
1367 // FIXME: We should check the audio session here but we do not have it in this context.
1368 // This may prevent offloading in rare situations where effects are left active by apps
1369 // in the background.
1370 sp<IOProfile> profile;
1371 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1372 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1373 profile = getProfileForOutput(
1374 devices, config->sample_rate, config->format, config->channel_mask,
1375 flags, true /* directOnly */);
1376 }
1377
1378 if (profile == nullptr) {
1379 return NAME_NOT_FOUND;
1380 }
1381
1382 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1383 for (size_t i = 0; i < mOutputs.size(); i++) {
1384 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1385 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1386 // reuse direct output if currently open by the same client
1387 // and configured with same parameters
1388 if ((config->sample_rate == desc->getSamplingRate()) &&
1389 (config->format == desc->getFormat()) &&
1390 (config->channel_mask == desc->getChannelMask()) &&
1391 (session == desc->mDirectClientSession)) {
1392 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001393 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001394 mOutputs.keyAt(i), session);
1395 *output = mOutputs.keyAt(i);
1396 return NO_ERROR;
1397 }
1398 }
1399 }
1400
1401 if (!profile->canOpenNewIo()) {
1402 return NAME_NOT_FOUND;
1403 }
1404
1405 sp<SwAudioOutputDescriptor> outputDesc =
1406 new SwAudioOutputDescriptor(profile, mpClientInterface);
1407
Michael Chan6fb34492020-12-08 15:44:49 +11001408 // An MSD patch may be using the only output stream that can service this request. Release
1409 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001410 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001411
Eric Laurentf1f22e72021-07-13 14:04:14 +02001412 status_t status =
1413 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001414
1415 // only accept an output with the requested parameters
1416 if (status != NO_ERROR ||
1417 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1418 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1419 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1420 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1421 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1422 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1423 config->channel_mask, outputDesc->getChannelMask());
1424 if (*output != AUDIO_IO_HANDLE_NONE) {
1425 outputDesc->close();
1426 }
1427 // fall back to mixer output if possible when the direct output could not be open
1428 if (audio_is_linear_pcm(config->format) &&
1429 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1430 return NAME_NOT_FOUND;
1431 }
1432 *output = AUDIO_IO_HANDLE_NONE;
1433 return BAD_VALUE;
1434 }
1435 outputDesc->mDirectOpenCount = 1;
1436 outputDesc->mDirectClientSession = session;
1437
1438 addOutput(*output, outputDesc);
1439 mPreviousOutputs = mOutputs;
1440 ALOGV("%s returns new direct output %d", __func__, *output);
1441 mpClientInterface->onAudioPortListUpdate();
1442 return NO_ERROR;
1443}
1444
François Gaffie11d30102018-11-02 16:09:09 +01001445audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1446 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001447 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001448 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001449 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001450 audio_output_flags_t *flags,
1451 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001452{
Andy Hungc88b0642018-04-27 15:42:35 -07001453 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001454
jiabine375d412019-02-26 12:54:53 -08001455 // Discard haptic channel mask when forcing muting haptic channels.
1456 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001457 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1458 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001459
Eric Laurente552edb2014-03-10 17:42:56 -07001460 // open a direct output if required by specified parameters
1461 //force direct flag if offload flag is set: offloading implies a direct output stream
1462 // and all common behaviors are driven by checking only the direct flag
1463 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001464 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1465 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001466 }
Nadav Bar766fb022018-01-07 12:18:03 +02001467 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1468 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001469 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001470
1471 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1472
Eric Laurente83b55d2014-11-14 10:06:21 -08001473 // only allow deep buffering for music stream type
1474 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001475 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001476 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001477 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001478 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1479 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001480 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001481 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001482 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001483 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001484 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001485 audio_is_linear_pcm(config->format) &&
1486 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001487 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001488 AUDIO_OUTPUT_FLAG_DIRECT);
1489 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001490 }
Eric Laurente552edb2014-03-10 17:42:56 -07001491
Carter Hsua3abb402021-10-26 11:11:20 +08001492 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1493 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1494 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1495 }
1496
Eric Laurentfa0f6742021-08-17 18:39:44 +02001497 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001498 && canBeSpatializedInt(attr, config,
1499 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02001500 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001501 }
1502
Eric Laurentc529cf62020-04-17 18:19:10 -07001503 audio_config_t directConfig = *config;
1504 directConfig.channel_mask = channelMask;
1505 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1506 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001507 return output;
1508 }
1509
Eric Laurent14cbfca2016-03-17 09:42:16 -07001510 // A request for HW A/V sync cannot fallback to a mixed output because time
1511 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001512 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001513 return AUDIO_IO_HANDLE_NONE;
1514 }
1515
Eric Laurente552edb2014-03-10 17:42:56 -07001516 // ignoring channel mask due to downmix capability in mixer
1517
1518 // open a non direct output
1519
1520 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001521 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001522 // get which output is suitable for the specified stream. The actual
1523 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001524 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001525
Eric Laurent8838a382014-09-08 16:44:28 -07001526 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001527 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001528 output = selectOutput(
1529 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001530 }
François Gaffie11d30102018-11-02 16:09:09 +01001531 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001532 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001533 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001534
Eric Laurente552edb2014-03-10 17:42:56 -07001535 return output;
1536}
1537
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001538sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001539 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1540 mAvailableInputDevices);
1541 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1542}
1543
1544DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1545 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1546 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001547}
1548
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001549const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001550 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001551 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1552 if (msdModule != 0) {
1553 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1554 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1555 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1556 const struct audio_port_config *source = &patch->mPatch.sources[j];
1557 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1558 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001559 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001560 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001561 }
1562 }
1563 }
1564 return msdPatches;
1565}
1566
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001567bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1568 ssize_t index = mAudioPatches.indexOfKey(handle);
1569 if (index < 0) {
1570 return false;
1571 }
1572 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1573 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1574 if (msdModule == nullptr) {
1575 return false;
1576 }
1577 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1578 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1579 return true;
1580 }
1581 index = getMsdOutputPatches().indexOfKey(handle);
1582 if (index < 0) {
1583 return false;
1584 }
1585 return true;
1586}
1587
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001588status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1589 const InputProfileCollection &inputProfiles,
1590 const OutputProfileCollection &outputProfiles,
1591 const sp<DeviceDescriptor> &sourceDevice,
1592 const sp<DeviceDescriptor> &sinkDevice,
1593 AudioProfileVector& sourceProfiles,
1594 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001595 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001596 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001597 return NO_INIT;
1598 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001599 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001600 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001601 return NO_INIT;
1602 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001603 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001604 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1605 inProfile->supportsDevice(sourceDevice)) {
1606 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001607 }
1608 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001609 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001610 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001611 outProfile->supportsDevice(sinkDevice)) {
1612 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001613 }
1614 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001615 return NO_ERROR;
1616}
1617
1618status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1619 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1620 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1621{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001623 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1624 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1625 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001626 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001627 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1628 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001629 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001630 }
1631 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1632 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1633 sinkConfig->format = bestSinkConfig.format;
1634 // For encoded streams force direct flag to prevent downstream mixing.
1635 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1636 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001637 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1638 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001639 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001640 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1641 // raw and IEC61937 framed streams.
1642 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1643 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1644 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001645 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1646 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1647 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1648 sourceConfig->format = bestSinkConfig.format;
1649 // Copy input stream directly without any processing (e.g. resampling).
1650 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1651 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1652 if (hwAvSync) {
1653 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1654 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1655 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1656 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1657 }
1658 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1659 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1660 sinkConfig->config_mask |= config_mask;
1661 sourceConfig->config_mask |= config_mask;
1662 return NO_ERROR;
1663}
1664
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001665PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1666 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001667{
1668 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001669 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1670 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1671 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1672 if (deviceModule == nullptr) {
1673 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1674 return patchBuilder;
1675 }
1676 const InputProfileCollection inputProfiles = msdIsSource ?
1677 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1678 const OutputProfileCollection outputProfiles = msdIsSource ?
1679 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1680
1681 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1682 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1683 device : getMsdAudioOutDevices().itemAt(0);
1684 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1685
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001686 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1687 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001688 AudioProfileVector sourceProfiles;
1689 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001690 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1691 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001692 for (auto hwAvSync : { true, false }) {
1693 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1694 sourceProfiles, sinkProfiles) != NO_ERROR) {
1695 continue;
1696 }
1697 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1698 &sinkConfig) == NO_ERROR) {
1699 // Found a matching config. Re-create PatchBuilder with this config.
1700 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1701 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001702 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001703 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001704 " supporting PCM format conversion.", __func__);
1705 return patchBuilder;
1706}
1707
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001708status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001709 DeviceVector devices;
1710 if (outputDevices != nullptr && outputDevices->size() > 0) {
1711 devices.add(*outputDevices);
1712 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001713 // Use media strategy for unspecified output device. This should only
1714 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1715 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001716 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001717 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001718 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001719 }
Michael Chan6fb34492020-12-08 15:44:49 +11001720 std::vector<PatchBuilder> patchesToCreate;
1721 for (auto i = 0u; i < devices.size(); ++i) {
1722 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001723 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001724 }
1725 // Retain only the MSD patches associated with outputDevices request.
1726 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001727 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001728 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1729 auto retainedPatch = false;
1730 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1731 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1732 patchesToRemove.removeItemsAt(i);
1733 retainedPatch = true;
1734 break;
1735 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001736 }
Michael Chan6fb34492020-12-08 15:44:49 +11001737 if (retainedPatch) {
1738 it = patchesToCreate.erase(it);
1739 continue;
1740 }
1741 ++it;
1742 }
1743 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1744 return NO_ERROR;
1745 }
1746 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1747 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001748 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001749 }
Michael Chan6fb34492020-12-08 15:44:49 +11001750 status_t status = NO_ERROR;
1751 for (const auto &p : patchesToCreate) {
1752 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1753 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1754 char message[256];
1755 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1756 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1757 currStatus == NO_ERROR ? "Success" : "Error",
1758 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1759 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1760 if (currStatus == NO_ERROR) {
1761 ALOGD("%s", message);
1762 } else {
1763 ALOGE("%s", message);
1764 if (status == NO_ERROR) {
1765 status = currStatus;
1766 }
1767 }
1768 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001769 return status;
1770}
1771
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001772void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1773 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001774 for (size_t i = 0; i < msdPatches.size(); i++) {
1775 const auto& patch = msdPatches[i];
1776 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1777 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1778 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1779 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1780 releaseAudioPatch(patch->getHandle(), mUidCached);
1781 break;
1782 }
1783 }
1784 }
1785}
1786
Dorin Drimus94d94412022-02-02 09:05:02 +01001787bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1788 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1789 AudioPatchCollection msdPatches = getMsdOutputPatches();
1790 for (size_t i = 0; i < msdPatches.size(); i++) {
1791 const auto& patch = msdPatches[i];
1792 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1793 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1794 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1795 const auto& foundDevice = devicesToCheck.getDevice(
1796 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1797 if (foundDevice != nullptr) {
1798 devicesToCheck.remove(foundDevice);
1799 if (devicesToCheck.isEmpty()) {
1800 return true;
1801 }
1802 }
1803 }
1804 }
1805 }
1806 return false;
1807}
1808
Eric Laurente0720872014-03-11 09:30:41 -07001809audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001810 audio_output_flags_t flags,
1811 audio_format_t format,
1812 audio_channel_mask_t channelMask,
1813 uint32_t samplingRate,
1814 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001815{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001816 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1817 "%s called with format %#x", __func__, format);
1818
jiabinebb6af42020-06-09 17:31:17 -07001819 // Return the output that haptic-generating attached to when 1) session id is specified,
1820 // 2) haptic-generating effect exists for given session id and 3) the output that
1821 // haptic-generating effect attached to is in given outputs.
1822 if (sessionId != AUDIO_SESSION_NONE) {
1823 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1824 sessionId, FX_IID_HAPTICGENERATOR);
1825 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1826 return hapticGeneratingOutput;
1827 }
1828 }
1829
Eric Laurent16c66dd2019-05-01 17:54:10 -07001830 // Flags disqualifying an output: the match must happen before calling selectOutput()
1831 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1832 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1833
1834 // Flags expressing a functional request: must be honored in priority over
1835 // other criteria
1836 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1837 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001838 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1839 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001840 // Flags expressing a performance request: have lower priority than serving
1841 // requested sampling rate or channel mask
1842 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1843 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1844 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1845
1846 const audio_output_flags_t functionalFlags =
1847 (audio_output_flags_t)(flags & kFunctionalFlags);
1848 const audio_output_flags_t performanceFlags =
1849 (audio_output_flags_t)(flags & kPerformanceFlags);
1850
1851 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1852
Eric Laurente552edb2014-03-10 17:42:56 -07001853 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001854 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001855 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001856 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001857 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001858 // with tiebreak preferring the minimum number of extra functional flags
1859 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001860 // 3: the output supporting the exact channel mask
1861 // 4: the output with a higher channel count than requested
1862 // 5: the output with a higher sampling rate than requested
1863 // 6: the output with the highest number of requested performance flags
1864 // 7: the output with the bit depth the closest to the requested one
1865 // 8: the primary output
1866 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001867
Eric Laurent16c66dd2019-05-01 17:54:10 -07001868 // matching criteria values in priority order for best matching output so far
1869 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001870
Eric Laurent16c66dd2019-05-01 17:54:10 -07001871 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1872 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1873 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001874
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001875 for (audio_io_handle_t output : outputs) {
1876 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001877 // matching criteria values in priority order for current output
1878 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001879
Eric Laurent16c66dd2019-05-01 17:54:10 -07001880 if (outputDesc->isDuplicated()) {
1881 continue;
1882 }
1883 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1884 continue;
1885 }
Eric Laurent8838a382014-09-08 16:44:28 -07001886
Eric Laurent16c66dd2019-05-01 17:54:10 -07001887 // If haptic channel is specified, use the haptic output if present.
1888 // When using haptic output, same audio format and sample rate are required.
1889 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001890 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001891 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1892 continue;
1893 }
1894 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001895 && format == outputDesc->getFormat()
1896 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001897 currentMatchCriteria[0] = outputHapticChannelCount;
1898 }
1899
1900 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001901 const int matchingFunctionalFlags =
1902 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1903 const int totalFunctionalFlags =
1904 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1905 // Prefer matching functional flags, but subtract unnecessary functional flags.
1906 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001907
1908 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001909 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1910 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001911 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1912 channelCount <= outputChannelCount) {
1913 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001914 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1915 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001916 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001917 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001918 currentMatchCriteria[3] = outputChannelCount;
1919 }
1920
1921 // sampling rate match
1922 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001923 samplingRate <= outputDesc->getSamplingRate()) {
1924 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001925 }
1926
1927 // performance flags match
1928 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1929
1930 // format match
1931 if (format != AUDIO_FORMAT_INVALID) {
1932 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001933 PolicyAudioPort::kFormatDistanceMax -
1934 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001935 }
1936
1937 // primary output match
1938 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1939
1940 // compare match criteria by priority then value
1941 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1942 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1943 bestMatchCriteria = currentMatchCriteria;
1944 bestOutput = output;
1945
1946 std::stringstream result;
1947 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1948 std::ostream_iterator<int>(result, " "));
1949 ALOGV("%s new bestOutput %d criteria %s",
1950 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001951 }
1952 }
1953
Eric Laurent16c66dd2019-05-01 17:54:10 -07001954 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001955}
1956
Eric Laurent8fc147b2018-07-22 19:13:55 -07001957status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001958{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001959 ALOGV("%s portId %d", __FUNCTION__, portId);
1960
1961 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1962 if (outputDesc == 0) {
1963 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001964 return BAD_VALUE;
1965 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001966 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001967
Eric Laurent8fc147b2018-07-22 19:13:55 -07001968 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001969 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001970
Eric Laurent733ce942017-12-07 12:18:25 -08001971 status_t status = outputDesc->start();
1972 if (status != NO_ERROR) {
1973 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001974 }
1975
Eric Laurent97ac8712018-07-27 18:59:02 -07001976 uint32_t delayMs;
1977 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001978
1979 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001980 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001981 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001982 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001983 if (delayMs != 0) {
1984 usleep(delayMs * 1000);
1985 }
1986
1987 return status;
1988}
1989
Eric Laurent96d1dda2022-03-14 17:14:19 +01001990bool AudioPolicyManager::isLeUnicastActive() const {
1991 if (isInCall()) {
1992 return true;
1993 }
1994 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
1995}
1996
1997bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
1998 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
1999 return false;
2000 }
2001 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2002 ALOGV("%s active %d", __func__, active);
2003 return active;
2004}
2005
Eric Laurent97ac8712018-07-27 18:59:02 -07002006status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2007 const sp<TrackClientDescriptor>& client,
2008 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002009{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002010 // cannot start playback of STREAM_TTS if any other output is being used
2011 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002012
2013 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002014 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002015 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002016 auto clientStrategy = client->strategy();
2017 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002018 if (stream == AUDIO_STREAM_TTS) {
2019 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002020 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002021 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002022 return INVALID_OPERATION;
2023 } else {
2024 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2025 }
2026 } else {
2027 // some playback other than beacon starts
2028 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2029 }
2030
Eric Laurent77305a62016-07-25 16:39:22 -07002031 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002032 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002033 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002034
François Gaffie11d30102018-11-02 16:09:09 +01002035 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002036 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002037 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002038 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002039 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002040 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002041 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002042 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002043 } else {
2044 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002045 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002046 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2047 AUDIO_FORMAT_DEFAULT);
2048 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2049 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002050 }
2051
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002052 // requiresMuteCheck is false when we can bypass mute strategy.
2053 // It covers a common case when there is no materially active audio
2054 // and muting would result in unnecessary delay and dropped audio.
2055 const uint32_t outputLatencyMs = outputDesc->latency();
2056 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002057 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002058
Eric Laurente552edb2014-03-10 17:42:56 -07002059 // increment usage count for this stream on the requested output:
2060 // NOTE that the usage count is the same for duplicated output and hardware output which is
2061 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002062 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002063
2064 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002065 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2066 client->isPreferredDeviceForExclusiveUse()) {
2067 // Preferred device may be exclusive, use only if no other active clients on this output
2068 devices = DeviceVector(
2069 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2070 } else {
2071 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2072 }
François Gaffie11d30102018-11-02 16:09:09 +01002073 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002074 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002075 }
2076 }
Eric Laurente552edb2014-03-10 17:42:56 -07002077
François Gaffiec005e562018-11-06 15:04:49 +01002078 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002079 selectOutputForMusicEffects();
2080 }
2081
François Gaffie1c878552018-11-22 16:53:21 +01002082 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002083 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002084 if (devices.isEmpty()) {
2085 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002086 }
François Gaffiec005e562018-11-06 15:04:49 +01002087 bool shouldWait =
2088 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2089 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2090 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002091 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002092 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002093 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002094 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002095 // An output has a shared device if
2096 // - managed by the same hw module
2097 // - supports the currently selected device
2098 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002099 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002100
Eric Laurent77305a62016-07-25 16:39:22 -07002101 // force a device change if any other output is:
2102 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002103 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002104 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002105 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002106 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002107 // change the device currently selected by the other output.
2108 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002109 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002110 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002111 force = true;
2112 }
2113 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002114 // a notification so that audio focus effect can propagate, or that a mute/unmute
2115 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002116 const uint32_t latencyMs = desc->latency();
2117 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2118
2119 if (shouldWait && isActive && (waitMs < latencyMs)) {
2120 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002121 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002122
2123 // Require mute check if another output is on a shared device
2124 // and currently active to have proper drain and avoid pops.
2125 // Note restoring AudioTracks onto this output needs to invoke
2126 // a volume ramp if there is no mute.
2127 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002128 }
2129 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002130
2131 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002132 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002133
Eric Laurente552edb2014-03-10 17:42:56 -07002134 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002135 auto &curves = getVolumeCurves(client->attributes());
2136 checkAndSetVolume(curves, client->volumeSource(),
2137 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002138 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002139 outputDesc->devices().types(), 0 /*delay*/,
2140 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002141
2142 // update the outputs if starting an output with a stream that can affect notification
2143 // routing
2144 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002145
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002146 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002147 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002148 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2149 }
Eric Laurentdc462862016-07-19 12:29:53 -07002150
2151 if (waitMs > muteWaitMs) {
2152 *delayMs = waitMs - muteWaitMs;
2153 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002154
2155 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2156 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2157 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2158 // change occurs after the MixerThread starts and causes a stream volume
2159 // glitch.
2160 //
2161 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002162 }
Eric Laurentdc462862016-07-19 12:29:53 -07002163
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002164 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002165 mEngine->getForceUse(
2166 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002167 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002168 }
2169
Eric Laurent97ac8712018-07-27 18:59:02 -07002170 // Automatically enable the remote submix input when output is started on a re routing mix
2171 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002172 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2173 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002174 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2175 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2176 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002177 "remote-submix",
2178 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002179 }
2180
Eric Laurent96d1dda2022-03-14 17:14:19 +01002181 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2182
Eric Laurente552edb2014-03-10 17:42:56 -07002183 return NO_ERROR;
2184}
2185
Eric Laurent96d1dda2022-03-14 17:14:19 +01002186void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2187 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2188 bool isUnicastActive = isLeUnicastActive();
2189
2190 if (wasUnicastActive != isUnicastActive) {
2191 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2192 for (size_t i = 0; i < mOutputs.size(); i++) {
2193 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2194 if (desc != ignoredOutput && desc->isActive()
2195 && ((isUnicastActive &&
2196 !desc->devices().
2197 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2198 || (wasUnicastActive &&
2199 !desc->devices().getDevicesFromTypes(
2200 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2201 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2202 bool force = desc->devices() != newDevices;
2203 setOutputDevices(desc, newDevices, force, delayMs);
2204 // re-apply device specific volume if not done by setOutputDevice()
2205 if (!force) {
2206 applyStreamVolumes(desc, newDevices.types(), delayMs);
2207 }
2208 }
2209 }
2210 }
2211}
2212
Eric Laurent8fc147b2018-07-22 19:13:55 -07002213status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002214{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002215 ALOGV("%s portId %d", __FUNCTION__, portId);
2216
2217 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2218 if (outputDesc == 0) {
2219 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002220 return BAD_VALUE;
2221 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002222 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002223
Eric Laurent97ac8712018-07-27 18:59:02 -07002224 ALOGV("stopOutput() output %d, stream %d, session %d",
2225 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002226
Eric Laurent97ac8712018-07-27 18:59:02 -07002227 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002228
Eric Laurent733ce942017-12-07 12:18:25 -08002229 if (status == NO_ERROR ) {
2230 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002231 }
2232 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002233}
2234
Eric Laurent97ac8712018-07-27 18:59:02 -07002235status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2236 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002237{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002238 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002239 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002240 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002241 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002242
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002243 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2244
François Gaffie1c878552018-11-22 16:53:21 +01002245 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2246 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002247 // Automatically disable the remote submix input when output is stopped on a
2248 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002249 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002250 if (isSingleDeviceType(
2251 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002252 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002253 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002254 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2255 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002256 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002257 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002258 }
2259 }
2260 bool forceDeviceUpdate = false;
2261 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002262 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002263 forceDeviceUpdate = true;
2264 }
2265
Eric Laurente552edb2014-03-10 17:42:56 -07002266 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002267 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002268
Eric Laurente552edb2014-03-10 17:42:56 -07002269 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002270 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002271 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002272 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002273
2274 // If the routing does not change, if an output is routed on a device using HwGain
2275 // (aka setAudioPortConfig) and there are still active clients following different
2276 // volume group(s), force reapply volume
2277 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2278 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2279
Eric Laurente552edb2014-03-10 17:42:56 -07002280 // delay the device switch by twice the latency because stopOutput() is executed when
2281 // the track stop() command is received and at that time the audio track buffer can
2282 // still contain data that needs to be drained. The latency only covers the audio HAL
2283 // and kernel buffers. Also the latency does not always include additional delay in the
2284 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002285 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2286 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002287
2288 // force restoring the device selection on other active outputs if it differs from the
2289 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002290 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002291 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002292 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002293 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002294 desc->isActive() &&
2295 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002296 (newDevices != desc->devices())) {
2297 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2298 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002299
François Gaffie11d30102018-11-02 16:09:09 +01002300 setOutputDevices(desc, newDevices2, force, delayMs);
2301
Eric Laurent57de36c2016-09-28 16:59:11 -07002302 // re-apply device specific volume if not done by setOutputDevice()
2303 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002304 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002305 }
Eric Laurente552edb2014-03-10 17:42:56 -07002306 }
2307 }
2308 // update the outputs if stopping one with a stream that can affect notification routing
2309 handleNotificationRoutingForStream(stream);
2310 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002311
2312 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2313 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002314 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002315 }
2316
François Gaffiec005e562018-11-06 15:04:49 +01002317 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002318 selectOutputForMusicEffects();
2319 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002320
2321 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2322
Eric Laurente552edb2014-03-10 17:42:56 -07002323 return NO_ERROR;
2324 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002325 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002326 return INVALID_OPERATION;
2327 }
2328}
2329
jiabinbce0c1d2020-10-05 11:20:18 -07002330bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002331{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002332 ALOGV("%s portId %d", __FUNCTION__, portId);
2333
2334 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2335 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002336 // If an output descriptor is closed due to a device routing change,
2337 // then there are race conditions with releaseOutput from tracks
2338 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2339 // destroyed shortly thereafter.
2340 //
2341 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002342 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002343 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002344 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002345
2346 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002347
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302348 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2349 if (outputDesc->isClientActive(client)) {
2350 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2351 stopOutput(portId);
2352 }
2353
Eric Laurent8fc147b2018-07-22 19:13:55 -07002354 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2355 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002356 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002357 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002358 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002359 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002360 if (--outputDesc->mDirectOpenCount == 0) {
2361 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002362 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002363 }
2364 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302365
Andy Hung39efb7a2018-09-26 15:39:28 -07002366 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002367 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2368 // The output is pending reopened to query dynamic profiles and
2369 // there is no active clients
2370 closeOutput(outputDesc->mIoHandle);
2371 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2372 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2373 if (newOutputDesc == nullptr) {
2374 ALOGE("%s failed to open output", __func__);
2375 }
2376 return true;
2377 }
2378 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002379}
2380
Eric Laurentcaf7f482014-11-25 17:50:47 -08002381status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2382 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002383 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002384 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002385 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002386 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002387 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002388 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002389 input_type_t *inputType,
2390 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002391{
François Gaffiec005e562018-11-06 15:04:49 +01002392 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002393 "flags %#x attributes=%s requested device ID %d",
2394 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2395 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002396
Eric Laurentad2e7b92017-09-14 20:06:42 -07002397 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002398 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002399 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002400 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002401 sp<AudioInputDescriptor> inputDesc;
2402 sp<RecordClientDescriptor> clientDesc;
2403 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002404 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002405 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002406
2407 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2408 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2409 return INVALID_OPERATION;
2410 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002411
Francois Gaffie716e1432019-01-14 16:58:59 +01002412 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2413 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002414 }
2415
Paul McLean466dc8e2015-04-17 13:15:36 -06002416 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002417 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002418 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002419
Eric Laurentad2e7b92017-09-14 20:06:42 -07002420 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2421 // possible
2422 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2423 *input != AUDIO_IO_HANDLE_NONE) {
2424 ssize_t index = mInputs.indexOfKey(*input);
2425 if (index < 0) {
2426 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2427 status = BAD_VALUE;
2428 goto error;
2429 }
2430 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002431 RecordClientVector clients = inputDesc->getClientsForSession(session);
2432 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002433 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2434 status = BAD_VALUE;
2435 goto error;
2436 }
2437 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2438 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002439 // corresponds to a new client and is only permitted from the same UID.
2440 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002441 if (clients.size() > 1) {
2442 for (const auto& client : clients) {
2443 // The client map is ordered by key values (portId) and portIds are allocated
2444 // incrementaly. So the first client in this list is the one opened by audio flinger
2445 // when the mmap stream is created and should be ignored as it does not correspond
2446 // to an actual client
2447 if (client == *clients.cbegin()) {
2448 continue;
2449 }
2450 if (uid != client->uid() && !client->isSilenced()) {
2451 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2452 uid, client->portId(), client->uid());
2453 status = INVALID_OPERATION;
2454 goto error;
2455 }
Eric Laurent331679c2018-04-16 17:03:16 -07002456 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002457 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002458 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002459 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002460
Eric Laurentfecbceb2021-02-09 14:46:43 +01002461 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002462 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002463 }
2464
2465 *input = AUDIO_IO_HANDLE_NONE;
2466 *inputType = API_INPUT_INVALID;
2467
Francois Gaffie716e1432019-01-14 16:58:59 +01002468 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2469 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2470 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002471 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002472 ALOGW("%s could not find input mix for attr %s",
2473 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002474 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002475 }
jiabinc1de2df2019-05-07 14:26:40 -07002476 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2477 String8(attr->tags + strlen("addr=")),
2478 AUDIO_FORMAT_DEFAULT);
2479 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002480 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002481 __func__, attributes.source, attributes.tags);
2482 status = BAD_VALUE;
2483 goto error;
2484 }
2485
Kevin Rocard25f9b052019-02-27 15:08:54 -08002486 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2487 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2488 } else {
2489 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2490 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002491 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002492 if (explicitRoutingDevice != nullptr) {
2493 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002494 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002495 // Prevent from storing invalid requested device id in clients
2496 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002497 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002498 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2499 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002500 }
François Gaffie11d30102018-11-02 16:09:09 +01002501 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002502 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002503 status = BAD_VALUE;
2504 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002505 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002506 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2507 *inputType = API_INPUT_MIX_CAPTURE;
2508 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002509 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2510 // there is an external policy, but this input is attached to a mix of recorders,
2511 // meaning it receives audio injected into the framework, so the recorder doesn't
2512 // know about it and is therefore considered "legacy"
2513 *inputType = API_INPUT_LEGACY;
2514 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002515 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002516 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002517 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002518 } else {
2519 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002520 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002521
Eric Laurent599c7582015-12-07 18:05:55 -08002522 }
2523
François Gaffiec005e562018-11-06 15:04:49 +01002524 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002525 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002526 status = INVALID_OPERATION;
2527 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002528 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002529
Eric Laurent8f42ea12018-08-08 09:08:25 -07002530exit:
2531
François Gaffiec005e562018-11-06 15:04:49 +01002532 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2533 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002534
Francois Gaffie716e1432019-01-14 16:58:59 +01002535 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002536 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002537 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002538
Mikhail Naganov2996f672019-04-18 12:29:59 -07002539 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002540 requestedDeviceId, attributes.source, flags,
2541 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002542 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002543 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002544
2545 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2546 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002547
Eric Laurent599c7582015-12-07 18:05:55 -08002548 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002549
2550error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002551 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002552}
2553
2554
François Gaffie11d30102018-11-02 16:09:09 +01002555audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002556 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002557 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002558 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002559 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002560 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002561{
2562 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002563 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002564 bool isSoundTrigger = false;
2565
François Gaffiec005e562018-11-06 15:04:49 +01002566 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002567 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2568 if (index >= 0) {
2569 input = mSoundTriggerSessions.valueFor(session);
2570 isSoundTrigger = true;
2571 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2572 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2573 } else {
2574 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002575 }
François Gaffiec005e562018-11-06 15:04:49 +01002576 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002577 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002578 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002579 }
2580
Carter Hsua3abb402021-10-26 11:11:20 +08002581 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2582 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2583 }
2584
Andy Hungf129b032015-04-07 13:45:50 -07002585 // find a compatible input profile (not necessarily identical in parameters)
2586 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002587 // sampling rate and flags may be updated by getInputProfile
2588 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2589 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002590 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002591 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002592 audio_input_flags_t profileFlags = flags;
2593 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002594 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002595 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002596 profileFlags);
2597 if (profile != 0) {
2598 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002599 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2600 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002601 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002602 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2603 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002604 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002605 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002606 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002607 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002608 }
Eric Laurente552edb2014-03-10 17:42:56 -07002609 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002610 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002611 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002612 if (samplingRate == 0) {
2613 samplingRate = profileSamplingRate;
2614 }
Eric Laurente552edb2014-03-10 17:42:56 -07002615
Eric Laurent322b4d22015-04-03 15:57:54 -07002616 if (profile->getModuleHandle() == 0) {
2617 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002618 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002619 }
2620
Eric Laurentec376dc2021-04-08 20:41:22 +02002621 // Reuse an already opened input if a client with the same session ID already exists
2622 // on that input
2623 for (size_t i = 0; i < mInputs.size(); i++) {
2624 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2625 if (desc->mProfile != profile) {
2626 continue;
2627 }
2628 RecordClientVector clients = desc->clientsList();
2629 for (const auto &client : clients) {
2630 if (session == client->session()) {
2631 return desc->mIoHandle;
2632 }
2633 }
2634 }
2635
Eric Laurent3974e3b2017-12-07 17:58:43 -08002636 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002637 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002638 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002639 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002640 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002641 continue;
2642 }
2643 // if sound trigger, reuse input if used by other sound trigger on same session
2644 // else
2645 // reuse input if active client app is not in IDLE state
2646 //
2647 RecordClientVector clients = desc->clientsList();
2648 bool doClose = false;
2649 for (const auto& client : clients) {
2650 if (isSoundTrigger != client->isSoundTrigger()) {
2651 continue;
2652 }
2653 if (client->isSoundTrigger()) {
2654 if (session == client->session()) {
2655 return desc->mIoHandle;
2656 }
2657 continue;
2658 }
2659 if (client->active() && client->appState() != APP_STATE_IDLE) {
2660 return desc->mIoHandle;
2661 }
2662 doClose = true;
2663 }
2664 if (doClose) {
2665 closeInput(desc->mIoHandle);
2666 } else {
2667 i++;
2668 }
2669 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002670 }
2671
Eric Laurentfe231122017-11-17 17:48:06 -08002672 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002673
Eric Laurentfe231122017-11-17 17:48:06 -08002674 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2675 lConfig.sample_rate = profileSamplingRate;
2676 lConfig.channel_mask = profileChannelMask;
2677 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002678
François Gaffie11d30102018-11-02 16:09:09 +01002679 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002680
2681 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002682 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002683 (profileSamplingRate != lConfig.sample_rate) ||
2684 !audio_formats_match(profileFormat, lConfig.format) ||
2685 (profileChannelMask != lConfig.channel_mask)) {
2686 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002687 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002688 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002689 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002690 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002691 }
Eric Laurent599c7582015-12-07 18:05:55 -08002692 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002693 }
2694
Eric Laurentc722f302014-12-10 11:21:49 -08002695 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002696
Eric Laurent599c7582015-12-07 18:05:55 -08002697 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002698 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002699
Eric Laurent599c7582015-12-07 18:05:55 -08002700 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002701}
2702
Eric Laurent4eb58f12018-12-07 16:41:02 -08002703status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002704{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002705 ALOGV("%s portId %d", __FUNCTION__, portId);
2706
2707 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2708 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002709 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002710 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002711 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002712 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002713 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002714 if (client->active()) {
2715 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2716 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002717 }
2718
Eric Laurent8f42ea12018-08-08 09:08:25 -07002719 audio_session_t session = client->session();
2720
Eric Laurent4eb58f12018-12-07 16:41:02 -08002721 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002722
Eric Laurent4eb58f12018-12-07 16:41:02 -08002723 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002724
Eric Laurent4eb58f12018-12-07 16:41:02 -08002725 status_t status = inputDesc->start();
2726 if (status != NO_ERROR) {
2727 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002728 }
Eric Laurente552edb2014-03-10 17:42:56 -07002729
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002730 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002731 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002732 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002733
Eric Laurent8f42ea12018-08-08 09:08:25 -07002734 // indicate active capture to sound trigger service if starting capture from a mic on
2735 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002736 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002737 if (device != nullptr) {
2738 status = setInputDevice(input, device, true /* force */);
2739 } else {
2740 ALOGW("%s no new input device can be found for descriptor %d",
2741 __FUNCTION__, inputDesc->getId());
2742 status = BAD_VALUE;
2743 }
Eric Laurente552edb2014-03-10 17:42:56 -07002744
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002745 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002746 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002747 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002748 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002749 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2750 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002751 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002752 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002753
François Gaffie11d30102018-11-02 16:09:09 +01002754 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2755 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002756 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002757 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002758 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002759
Eric Laurent8f42ea12018-08-08 09:08:25 -07002760 // automatically enable the remote submix output when input is started if not
2761 // used by a policy mix of type MIX_TYPE_RECORDERS
2762 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002763 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002764 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002765 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002766 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002767 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2768 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002769 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002770 if (address != "") {
2771 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2772 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002773 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002774 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002775 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002776 } else if (status != NO_ERROR) {
2777 // Restore client activity state.
2778 inputDesc->setClientActive(client, false);
2779 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002780 }
2781
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002782 ALOGV("%s input %d source = %d status = %d exit",
2783 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002784
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002785 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002786}
2787
Eric Laurent8fc147b2018-07-22 19:13:55 -07002788status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002789{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002790 ALOGV("%s portId %d", __FUNCTION__, portId);
2791
2792 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2793 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002794 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002795 return BAD_VALUE;
2796 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002797 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002798 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002799 if (!client->active()) {
2800 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002801 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002802 }
Carter Hsue6139d52021-07-08 10:30:20 +08002803 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002804 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002805
Eric Laurent8f42ea12018-08-08 09:08:25 -07002806 inputDesc->stop();
2807 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002808 auto current_source = inputDesc->source();
2809 setInputDevice(input, getNewInputDevice(inputDesc),
2810 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002811 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002812 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002813 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002814 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002815 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2816 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002817 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002818 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002819
2820 // automatically disable the remote submix output when input is stopped if not
2821 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002822 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002823 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002824 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002825 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002826 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2827 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002828 }
2829 if (address != "") {
2830 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2831 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002832 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002833 }
2834 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002835 resetInputDevice(input);
2836
2837 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2838 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002839 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2840 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002841 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002842 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002843 }
2844 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002845 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002846 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002847}
2848
Eric Laurent8fc147b2018-07-22 19:13:55 -07002849void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002850{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002851 ALOGV("%s portId %d", __FUNCTION__, portId);
2852
2853 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2854 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002856 return;
2857 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002858 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002859 audio_io_handle_t input = inputDesc->mIoHandle;
2860
Eric Laurent8f42ea12018-08-08 09:08:25 -07002861 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002862
Andy Hung39efb7a2018-09-26 15:39:28 -07002863 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002864
Andy Hung39efb7a2018-09-26 15:39:28 -07002865 if (inputDesc->getClientCount() > 0) {
2866 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002867 return;
2868 }
2869
Eric Laurent05b90f82014-08-27 15:32:29 -07002870 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002871 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002872 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002873}
2874
Eric Laurent8f42ea12018-08-08 09:08:25 -07002875void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002876{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002877 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002878
2879 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002880 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002881 }
2882}
2883
Eric Laurent8f42ea12018-08-08 09:08:25 -07002884void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2885{
2886 stopInput(portId);
2887 releaseInput(portId);
2888}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002889
Eric Laurent0dd51852019-04-19 18:18:58 -07002890void AudioPolicyManager::checkCloseInputs() {
2891 // After connecting or disconnecting an input device, close input if:
2892 // - it has no client (was just opened to check profile) OR
2893 // - none of its supported devices are connected anymore OR
2894 // - one of its clients cannot be routed to one of its supported
2895 // devices anymore. Otherwise update device selection
2896 std::vector<audio_io_handle_t> inputsToClose;
2897 for (size_t i = 0; i < mInputs.size(); i++) {
2898 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2899 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002900 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002901 inputsToClose.push_back(mInputs.keyAt(i));
2902 } else {
2903 bool close = false;
2904 for (const auto& client : input->clientsList()) {
2905 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002906 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002907 if (!input->supportedDevices().contains(device)) {
2908 close = true;
2909 break;
2910 }
2911 }
2912 if (close) {
2913 inputsToClose.push_back(mInputs.keyAt(i));
2914 } else {
2915 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2916 }
2917 }
2918 }
2919
2920 for (const audio_io_handle_t handle : inputsToClose) {
2921 ALOGV("%s closing input %d", __func__, handle);
2922 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002923 }
Eric Laurentd4692962014-05-05 18:13:44 -07002924}
2925
François Gaffie251c7f02018-11-07 10:41:08 +01002926void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002927{
2928 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002929 if (indexMin < 0 || indexMax < 0) {
2930 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2931 return;
2932 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002933 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002934
2935 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002936 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2937 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002938 continue;
2939 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002940 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002941 }
Eric Laurente552edb2014-03-10 17:42:56 -07002942}
2943
Eric Laurente0720872014-03-11 09:30:41 -07002944status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002945 int index,
2946 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002947{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002948 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002949 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2950 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2951 return NO_ERROR;
2952 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002953 ALOGV("%s: stream %s attributes=%s", __func__,
2954 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002955 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002956}
2957
Eric Laurente0720872014-03-11 09:30:41 -07002958status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002959 int *index,
2960 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002961{
François Gaffiec005e562018-11-06 15:04:49 +01002962 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2963 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002964 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002965 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002966 deviceTypes = mEngine->getOutputDevicesForStream(
2967 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002968 }
jiabin9a3361e2019-10-01 09:38:30 -07002969 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002970}
2971
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002972status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002973 int index,
2974 audio_devices_t device)
2975{
2976 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002977 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2978 if (group == VOLUME_GROUP_NONE) {
2979 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002980 return BAD_VALUE;
2981 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002982 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002983 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002984 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002985 VolumeSource vs = toVolumeSource(group);
2986 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2987
2988 status = setVolumeCurveIndex(index, device, curves);
2989 if (status != NO_ERROR) {
2990 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2991 return status;
2992 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002993
jiabin9a3361e2019-10-01 09:38:30 -07002994 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002995 auto curCurvAttrs = curves.getAttributes();
2996 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2997 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002998 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002999 } else if (!curves.getStreamTypes().empty()) {
3000 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003001 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003002 } else {
3003 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3004 return BAD_VALUE;
3005 }
jiabin9a3361e2019-10-01 09:38:30 -07003006 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3007 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003008
François Gaffiecfe17322018-11-07 13:41:29 +01003009 // update volume on all outputs and streams matching the following:
3010 // - The requested stream (or a stream matching for volume control) is active on the output
3011 // - The device (or devices) selected by the engine for this stream includes
3012 // the requested device
3013 // - For non default requested device, currently selected device on the output is either the
3014 // requested device or one of the devices selected by the engine for this stream
3015 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3016 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003017 for (size_t i = 0; i < mOutputs.size(); i++) {
3018 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003019 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003020
jiabin9a3361e2019-10-01 09:38:30 -07003021 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3022 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003023 }
François Gaffieed91f582020-01-31 10:35:37 +01003024 if (!(desc->isActive(vs) || isInCall())) {
3025 continue;
3026 }
3027 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3028 curDevices.find(device) == curDevices.end()) {
3029 continue;
3030 }
3031 bool applyVolume = false;
3032 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3033 curSrcDevices.insert(device);
3034 applyVolume = (curSrcDevices.find(
3035 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3036 } else {
3037 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3038 }
3039 if (!applyVolume) {
3040 continue; // next output
3041 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003042 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3043 // If a higher priority strategy is active, and the output is routed to a device with a
3044 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003045 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003046 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003047 // If the volume source is active with higher priority source, ensure at least Sw Muted
3048 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003049 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3050 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3051 false /*preferredDevice*/);
3052 if (activeClients.empty()) {
3053 continue;
3054 }
3055 bool isPreempted = false;
3056 bool isHigherPriority = productStrategy < strategy;
3057 for (const auto &client : activeClients) {
3058 if (isHigherPriority && (client->volumeSource() != vs)) {
3059 ALOGV("%s: Strategy=%d (\nrequester:\n"
3060 " group %d, volumeGroup=%d attributes=%s)\n"
3061 " higher priority source active:\n"
3062 " volumeGroup=%d attributes=%s) \n"
3063 " on output %zu, bailing out", __func__, productStrategy,
3064 group, group, toString(attributes).c_str(),
3065 client->volumeSource(), toString(client->attributes()).c_str(), i);
3066 applyVolume = false;
3067 isPreempted = true;
3068 break;
3069 }
3070 // However, continue for loop to ensure no higher prio clients running on output
3071 if (client->volumeSource() == vs) {
3072 applyVolume = true;
3073 }
3074 }
3075 if (isPreempted || applyVolume) {
3076 break;
3077 }
3078 }
3079 if (!applyVolume) {
3080 continue; // next output
3081 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003082 }
François Gaffieed91f582020-01-31 10:35:37 +01003083 //FIXME: workaround for truncated touch sounds
3084 // delayed volume change for system stream to be removed when the problem is
3085 // handled by system UI
3086 status_t volStatus = checkAndSetVolume(
3087 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003088 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003089 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3090 if (volStatus != NO_ERROR) {
3091 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003092 }
3093 }
François Gaffiecfe17322018-11-07 13:41:29 +01003094 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3095 return status;
3096}
3097
François Gaffieaaac0fd2018-11-22 17:56:39 +01003098status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003099 audio_devices_t device,
3100 IVolumeCurves &volumeCurves)
3101{
3102 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3103 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003104 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3105 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003106 (index > volumeCurves.getVolumeIndexMax())) {
3107 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3108 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3109 return BAD_VALUE;
3110 }
3111 if (!audio_is_output_device(device)) {
3112 return BAD_VALUE;
3113 }
3114
3115 // Force max volume if stream cannot be muted
3116 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3117
François Gaffieaaac0fd2018-11-22 17:56:39 +01003118 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003119 volumeCurves.addCurrentVolumeIndex(device, index);
3120 return NO_ERROR;
3121}
3122
3123status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3124 int &index,
3125 audio_devices_t device)
3126{
3127 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3128 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003129 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003130 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003131 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3132 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003133 }
jiabin9a3361e2019-10-01 09:38:30 -07003134 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003135}
3136
3137status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3138 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003139 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003140{
jiabin9a3361e2019-10-01 09:38:30 -07003141 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003142 return BAD_VALUE;
3143 }
jiabin9a3361e2019-10-01 09:38:30 -07003144 index = curves.getVolumeIndex(deviceTypes);
3145 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003146 return NO_ERROR;
3147}
3148
3149status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3150 int &index)
3151{
3152 index = getVolumeCurves(attr).getVolumeIndexMin();
3153 return NO_ERROR;
3154}
3155
3156status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3157 int &index)
3158{
3159 index = getVolumeCurves(attr).getVolumeIndexMax();
3160 return NO_ERROR;
3161}
3162
Eric Laurent36829f92017-04-07 19:04:42 -07003163audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003164{
3165 // select one output among several suitable for global effects.
3166 // The priority is as follows:
3167 // 1: An offloaded output. If the effect ends up not being offloadable,
3168 // AudioFlinger will invalidate the track and the offloaded output
3169 // will be closed causing the effect to be moved to a PCM output.
3170 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003171 // 3: The primary output
3172 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003173
François Gaffiec005e562018-11-06 15:04:49 +01003174 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3175 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003176 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003177
Eric Laurent36829f92017-04-07 19:04:42 -07003178 if (outputs.size() == 0) {
3179 return AUDIO_IO_HANDLE_NONE;
3180 }
Eric Laurente552edb2014-03-10 17:42:56 -07003181
Eric Laurent36829f92017-04-07 19:04:42 -07003182 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3183 bool activeOnly = true;
3184
3185 while (output == AUDIO_IO_HANDLE_NONE) {
3186 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3187 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3188 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3189
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003190 for (audio_io_handle_t output : outputs) {
3191 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003192 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003193 continue;
3194 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003195 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3196 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003197 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003198 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003199 }
3200 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003201 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003202 }
3203 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003204 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003205 }
3206 }
3207 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3208 output = outputOffloaded;
3209 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3210 output = outputDeepBuffer;
3211 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3212 output = outputPrimary;
3213 } else {
3214 output = outputs[0];
3215 }
3216 activeOnly = false;
3217 }
3218
3219 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003220 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003221 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3222 mMusicEffectOutput = output;
3223 }
3224
3225 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003226 return output;
3227}
3228
Eric Laurent36829f92017-04-07 19:04:42 -07003229audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3230{
3231 return selectOutputForMusicEffects();
3232}
3233
Eric Laurente0720872014-03-11 09:30:41 -07003234status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003235 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003236 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003237 int session,
3238 int id)
3239{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003240 if (session != AUDIO_SESSION_DEVICE) {
3241 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003242 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003243 index = mInputs.indexOfKey(io);
3244 if (index < 0) {
3245 ALOGW("registerEffect() unknown io %d", io);
3246 return INVALID_OPERATION;
3247 }
Eric Laurente552edb2014-03-10 17:42:56 -07003248 }
3249 }
François Gaffiec005e562018-11-06 15:04:49 +01003250 return mEffects.registerEffect(desc, io, session, id,
3251 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3252 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003253}
3254
Eric Laurentc241b0d2018-11-28 09:08:49 -08003255status_t AudioPolicyManager::unregisterEffect(int id)
3256{
3257 if (mEffects.getEffect(id) == nullptr) {
3258 return INVALID_OPERATION;
3259 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003260 if (mEffects.isEffectEnabled(id)) {
3261 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3262 setEffectEnabled(id, false);
3263 }
3264 return mEffects.unregisterEffect(id);
3265}
3266
3267status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3268{
3269 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3270 if (effect == nullptr) {
3271 return INVALID_OPERATION;
3272 }
3273
3274 status_t status = mEffects.setEffectEnabled(id, enabled);
3275 if (status == NO_ERROR) {
3276 mInputs.trackEffectEnabled(effect, enabled);
3277 }
3278 return status;
3279}
3280
Eric Laurent6c796322019-04-09 14:13:17 -07003281
3282status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3283{
3284 mEffects.moveEffects(ids, io);
3285 return NO_ERROR;
3286}
3287
Eric Laurentc75307b2015-03-17 15:29:32 -07003288bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3289{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003290 auto vs = toVolumeSource(stream, false);
3291 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003292}
3293
3294bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3295{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003296 auto vs = toVolumeSource(stream, false);
3297 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003298}
3299
Eric Laurente0720872014-03-11 09:30:41 -07003300bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003301{
3302 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003303 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003304 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003305 return true;
3306 }
3307 }
3308 return false;
3309}
3310
Eric Laurent275e8e92014-11-30 15:14:47 -08003311// Register a list of custom mixes with their attributes and format.
3312// When a mix is registered, corresponding input and output profiles are
3313// added to the remote submix hw module. The profile contains only the
3314// parameters (sampling rate, format...) specified by the mix.
3315// The corresponding input remote submix device is also connected.
3316//
3317// When a remote submix device is connected, the address is checked to select the
3318// appropriate profile and the corresponding input or output stream is opened.
3319//
3320// When capture starts, getInputForAttr() will:
3321// - 1 look for a mix matching the address passed in attribtutes tags if any
3322// - 2 if none found, getDeviceForInputSource() will:
3323// - 2.1 look for a mix matching the attributes source
3324// - 2.2 if none found, default to device selection by policy rules
3325// At this time, the corresponding output remote submix device is also connected
3326// and active playback use cases can be transferred to this mix if needed when reconnecting
3327// after AudioTracks are invalidated
3328//
3329// When playback starts, getOutputForAttr() will:
3330// - 1 look for a mix matching the address passed in attribtutes tags if any
3331// - 2 if none found, look for a mix matching the attributes usage
3332// - 3 if none found, default to device and output selection by policy rules.
3333
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003334status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003335{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003336 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3337 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003338 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003339 sp<HwModule> rSubmixModule;
3340 // examine each mix's route type
3341 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003342 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003343 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3344 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3345 ALOGE("Unsupported Policy Mix %zu of %zu: "
3346 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3347 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003348 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003349 break;
3350 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003351 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3352 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003353 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003354 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3355 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003356 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003357 rSubmixModule = mHwModules.getModuleFromName(
3358 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3359 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003360 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003361 i);
3362 res = INVALID_OPERATION;
3363 break;
3364 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003365 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003366
Eric Laurent97ac8712018-07-27 18:59:02 -07003367 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003368 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003369 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003370 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003371 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3372 } else {
3373 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3374 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003375 }
François Gaffie036e1e92015-03-19 10:16:24 +01003376
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003377 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003378 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003379 res = INVALID_OPERATION;
3380 break;
3381 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003382 audio_config_t outputConfig = mix.mFormat;
3383 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003384 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3385 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003386 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3387 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003388 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003389 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003390 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003391 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003392
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003393 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003394 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3395 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3396 ALOGE("Failed to set remote submix device available, type %u, address %s",
3397 mix.mDeviceType, address.string());
3398 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003399 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003400 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3401 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003402 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003403 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003404 i, mixes.size(), type, address.string());
3405
3406 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3407 mix.mDeviceType, mix.mDeviceAddress,
3408 String8(), AUDIO_FORMAT_DEFAULT);
3409 if (device == nullptr) {
3410 res = INVALID_OPERATION;
3411 break;
3412 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003413
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003414 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003415 // First try to find an already opened output supporting the device
3416 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003417 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003418
Eric Laurentc529cf62020-04-17 18:19:10 -07003419 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003420 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003421 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3422 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003423 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003424 } else {
3425 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003426 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003427 }
3428 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003429 // If no output found, try to find a direct output profile supporting the device
3430 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3431 sp<HwModule> module = mHwModules[i];
3432 for (size_t j = 0;
3433 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3434 j++) {
3435 sp<IOProfile> profile = module->getOutputProfiles()[j];
3436 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3437 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3438 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3439 address.string());
3440 res = INVALID_OPERATION;
3441 } else {
3442 foundOutput = true;
3443 }
3444 }
3445 }
3446 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003447 if (res != NO_ERROR) {
3448 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003449 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003450 res = INVALID_OPERATION;
3451 break;
3452 } else if (!foundOutput) {
3453 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003454 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003455 res = INVALID_OPERATION;
3456 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003457 } else {
3458 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003459 }
Eric Laurentc722f302014-12-10 11:21:49 -08003460 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003461 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003462 if (res != NO_ERROR) {
3463 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003464 } else if (checkOutputs) {
3465 checkForDeviceAndOutputChanges();
3466 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003467 }
3468 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003469}
3470
3471status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3472{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003473 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003474 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003475 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003476 sp<HwModule> rSubmixModule;
3477 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003478 for (const auto& mix : mixes) {
3479 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003480
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003481 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003482 rSubmixModule = mHwModules.getModuleFromName(
3483 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3484 if (rSubmixModule == 0) {
3485 res = INVALID_OPERATION;
3486 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003487 }
3488 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003489
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003490 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003491
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003492 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003493 res = INVALID_OPERATION;
3494 continue;
3495 }
3496
Kevin Rocard04ed0462019-05-02 17:53:24 -07003497 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3498 if (getDeviceConnectionState(device, address.string()) ==
3499 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3500 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3501 address.string(), "remote-submix",
3502 AUDIO_FORMAT_DEFAULT);
3503 if (res != OK) {
3504 ALOGE("Error making RemoteSubmix device unavailable for mix "
3505 "with type %d, address %s", device, address.string());
3506 }
3507 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003508 }
jiabin5740f082019-08-19 15:08:30 -07003509 rSubmixModule->removeOutputProfile(address.c_str());
3510 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003511
Kevin Rocard153f92d2018-12-18 18:33:28 -08003512 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003513 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003514 res = INVALID_OPERATION;
3515 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003516 } else {
3517 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003518 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003519 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003520 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003521 if (res == NO_ERROR && checkOutputs) {
3522 checkForDeviceAndOutputChanges();
3523 updateCallAndOutputRouting();
3524 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003525 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003526}
3527
Mikhail Naganov100f0122018-11-29 11:22:16 -08003528void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3529{
3530 size_t i = 0;
3531 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3532 for (const auto& fmt : mManualSurroundFormats) {
3533 if (i++ != 0) dst->append(", ");
3534 std::string sfmt;
3535 FormatConverter::toString(fmt, sfmt);
3536 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3537 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3538 }
3539}
3540
Eric Laurentc529cf62020-04-17 18:19:10 -07003541// Returns true if all devices types match the predicate and are supported by one HW module
3542bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003543 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003544 std::function<bool(audio_devices_t)> predicate,
3545 const char *context) {
3546 for (size_t i = 0; i < devices.size(); i++) {
3547 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003548 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003549 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003550 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003551 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003552 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003553 return false;
3554 }
3555 }
3556 return true;
3557}
3558
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003559status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003560 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003561 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003562 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3563 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003564 }
3565 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003566 if (res != NO_ERROR) {
3567 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3568 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003569 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003570
3571 checkForDeviceAndOutputChanges();
3572 updateCallAndOutputRouting();
3573
3574 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003575}
3576
3577status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3578 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003579 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3580 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003581 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003582 __FUNCTION__, uid);
3583 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003584 }
3585
Eric Laurentc529cf62020-04-17 18:19:10 -07003586 checkForDeviceAndOutputChanges();
3587 updateCallAndOutputRouting();
3588
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003589 return res;
3590}
3591
Eric Laurent2517af32020-11-25 15:31:27 +01003592
jiabin0a488932020-08-07 17:32:40 -07003593status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3594 device_role_t role,
3595 const AudioDeviceTypeAddrVector &devices) {
3596 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3597 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003598
Eric Laurentc529cf62020-04-17 18:19:10 -07003599 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003600 return BAD_VALUE;
3601 }
jiabin0a488932020-08-07 17:32:40 -07003602 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003603 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003604 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3605 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003606 return status;
3607 }
3608
3609 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003610
3611 bool forceVolumeReeval = false;
3612 // FIXME: workaround for truncated touch sounds
3613 // to be removed when the problem is handled by system UI
3614 uint32_t delayMs = 0;
3615 if (strategy == mCommunnicationStrategy) {
3616 forceVolumeReeval = true;
3617 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3618 updateInputRouting();
3619 }
3620 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003621
3622 return NO_ERROR;
3623}
3624
3625void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3626{
3627 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003628 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003629 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003630 // Only apply special touch sound delay once
3631 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003632 }
3633 for (size_t i = 0; i < mOutputs.size(); i++) {
3634 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3635 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003636 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3637 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003638 // As done in setDeviceConnectionState, we could also fix default device issue by
3639 // preventing the force re-routing in case of default dev that distinguishes on address.
3640 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003641 bool forceRouting = !newDevices.isEmpty();
3642 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3643 true /*requiresMuteCheck*/,
3644 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003645 // Only apply special touch sound delay once
3646 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003647 }
3648 if (forceVolumeReeval && !newDevices.isEmpty()) {
3649 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3650 }
3651 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003652 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003653}
3654
Eric Laurent2517af32020-11-25 15:31:27 +01003655void AudioPolicyManager::updateInputRouting() {
3656 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303657 // Skip for hotword recording as the input device switch
3658 // is handled within sound trigger HAL
3659 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3660 continue;
3661 }
Eric Laurent2517af32020-11-25 15:31:27 +01003662 auto newDevice = getNewInputDevice(activeDesc);
3663 // Force new input selection if the new device can not be reached via current input
3664 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3665 setInputDevice(activeDesc->mIoHandle, newDevice);
3666 } else {
3667 closeInput(activeDesc->mIoHandle);
3668 }
3669 }
3670}
3671
jiabin0a488932020-08-07 17:32:40 -07003672status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3673 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003674{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003675 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003676
jiabin0a488932020-08-07 17:32:40 -07003677 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003678 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003679 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3680 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003681 return status;
3682 }
3683
3684 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003685
3686 bool forceVolumeReeval = false;
3687 // FIXME: workaround for truncated touch sounds
3688 // to be removed when the problem is handled by system UI
3689 uint32_t delayMs = 0;
3690 if (strategy == mCommunnicationStrategy) {
3691 forceVolumeReeval = true;
3692 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3693 updateInputRouting();
3694 }
3695 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003696
3697 return NO_ERROR;
3698}
3699
jiabin0a488932020-08-07 17:32:40 -07003700status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3701 device_role_t role,
3702 AudioDeviceTypeAddrVector &devices) {
3703 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003704}
3705
Jiabin Huang3b98d322020-09-03 17:54:16 +00003706status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3707 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3708 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3709 dumpAudioDeviceTypeAddrVector(devices).c_str());
3710
Mikhail Naganov55773032020-10-01 15:08:13 -07003711 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003712 return BAD_VALUE;
3713 }
3714 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3715 ALOGW_IF(status != NO_ERROR,
3716 "Engine could not set preferred devices %s for audio source %d role %d",
3717 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3718
3719 return status;
3720}
3721
3722status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3723 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3724 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3725 dumpAudioDeviceTypeAddrVector(devices).c_str());
3726
Mikhail Naganov55773032020-10-01 15:08:13 -07003727 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003728 return BAD_VALUE;
3729 }
3730 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3731 ALOGW_IF(status != NO_ERROR,
3732 "Engine could not add preferred devices %s for audio source %d role %d",
3733 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3734
Eric Laurent2517af32020-11-25 15:31:27 +01003735 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003736 return status;
3737}
3738
3739status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3740 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3741{
3742 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3743 dumpAudioDeviceTypeAddrVector(devices).c_str());
3744
Mikhail Naganov55773032020-10-01 15:08:13 -07003745 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003746 return BAD_VALUE;
3747 }
3748
3749 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3750 audioSource, role, devices);
3751 ALOGW_IF(status != NO_ERROR,
3752 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3753
Eric Laurent2517af32020-11-25 15:31:27 +01003754 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003755 return status;
3756}
3757
3758status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3759 device_role_t role) {
3760 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3761
3762 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3763 ALOGW_IF(status != NO_ERROR,
3764 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3765
Eric Laurent2517af32020-11-25 15:31:27 +01003766 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003767 return status;
3768}
3769
3770status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3771 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3772 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3773}
3774
Oscar Azucena90e77632019-11-27 17:12:28 -08003775status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003776 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003777 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003778 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3779 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003780 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003781 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3782 if (status != NO_ERROR) {
3783 ALOGE("%s() could not set device affinity for userId %d",
3784 __FUNCTION__, userId);
3785 return status;
3786 }
3787
3788 // reevaluate outputs for all devices
3789 checkForDeviceAndOutputChanges();
3790 updateCallAndOutputRouting();
3791
3792 return NO_ERROR;
3793}
3794
3795status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003796 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003797 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3798 if (status != NO_ERROR) {
3799 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3800 __FUNCTION__, userId);
3801 return status;
3802 }
3803
3804 // reevaluate outputs for all devices
3805 checkForDeviceAndOutputChanges();
3806 updateCallAndOutputRouting();
3807
3808 return NO_ERROR;
3809}
3810
Andy Hungc29d82b2018-10-05 12:23:17 -07003811void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003812{
Andy Hungc29d82b2018-10-05 12:23:17 -07003813 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003814 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003815 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003816 std::string stateLiteral;
3817 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003818 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003819 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3820 "communications", "media", "record", "dock", "system",
3821 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3822 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3823 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003824 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3825 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3826 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3827 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3828 dst->append(" (MANUAL: ");
3829 dumpManualSurroundFormats(dst);
3830 dst->append(")");
3831 }
3832 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003833 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003834 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3835 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003836 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003837 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003838
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003839 dst->append("\n");
3840 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3841 dst->append("\n");
3842 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003843 mHwModulesAll.dump(dst);
3844 mOutputs.dump(dst);
3845 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003846 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003847 mAudioPatches.dump(dst);
3848 mPolicyMixes.dump(dst);
3849 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003850
Kevin Rocardb99cc752019-03-21 20:52:24 -07003851 dst->appendFormat(" AllowedCapturePolicies:\n");
3852 for (auto& policy : mAllowedCapturePolicies) {
3853 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3854 }
3855
François Gaffiec005e562018-11-06 15:04:49 +01003856 dst->appendFormat("\nPolicy Engine dump:\n");
3857 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003858}
3859
3860status_t AudioPolicyManager::dump(int fd)
3861{
3862 String8 result;
3863 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003864 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003865 return NO_ERROR;
3866}
3867
Kevin Rocardb99cc752019-03-21 20:52:24 -07003868status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3869{
3870 mAllowedCapturePolicies[uid] = capturePolicy;
3871 return NO_ERROR;
3872}
3873
Eric Laurente552edb2014-03-10 17:42:56 -07003874// This function checks for the parameters which can be offloaded.
3875// This can be enhanced depending on the capability of the DSP and policy
3876// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003877audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003878{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003879 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003880 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003881 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003882 offloadInfo.format,
3883 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3884 offloadInfo.has_video);
3885
jiabin2b9d5a12021-12-10 01:06:29 +00003886 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003887 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003888 }
3889
3890 // See if there is a profile to support this.
3891 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003892 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003893 offloadInfo.sample_rate,
3894 offloadInfo.format,
3895 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003896 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3897 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003898 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3899 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3900 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003901 if (profile == nullptr) {
3902 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3903 }
3904 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3905 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3906 }
3907 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003908}
3909
Michael Chana94fbb22018-04-24 14:31:19 +10003910bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3911 const audio_attributes_t& attributes) {
3912 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003913 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003914 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3915 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003916 config.sample_rate,
3917 config.format,
3918 config.channel_mask,
3919 output_flags,
3920 true /* directOnly */);
3921 ALOGV("%s() profile %sfound with name: %s, "
3922 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3923 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003924 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003925 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003926
3927 // also try the MSD module if compatible profile not found
3928 if (profile == nullptr) {
3929 profile = getMsdProfileForOutput(outputDevices,
3930 config.sample_rate,
3931 config.format,
3932 config.channel_mask,
3933 output_flags,
3934 true /* directOnly */);
3935 ALOGV("%s() MSD profile %sfound with name: %s, "
3936 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3937 __FUNCTION__, profile != 0 ? "" : "NOT ",
3938 (profile != 0 ? profile->getTagName().c_str() : "null"),
3939 config.sample_rate, config.format, config.channel_mask, output_flags);
3940 }
3941 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003942}
3943
jiabin2b9d5a12021-12-10 01:06:29 +00003944bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3945 bool durationIgnored) {
3946 if (mMasterMono) {
3947 return false; // no offloading if mono is set.
3948 }
3949
3950 // Check if offload has been disabled
3951 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3952 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3953 return false;
3954 }
3955
3956 // Check if stream type is music, then only allow offload as of now.
3957 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3958 {
3959 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3960 return false;
3961 }
3962
3963 //TODO: enable audio offloading with video when ready
3964 const bool allowOffloadWithVideo =
3965 property_get_bool("audio.offload.video", false /* default_value */);
3966 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3967 ALOGV("%s: has_video == true, returning false", __func__);
3968 return false;
3969 }
3970
3971 //If duration is less than minimum value defined in property, return false
3972 const int min_duration_secs = property_get_int32(
3973 "audio.offload.min.duration.secs", -1 /* default_value */);
3974 if (!durationIgnored) {
3975 if (min_duration_secs >= 0) {
3976 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3977 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3978 __func__, min_duration_secs);
3979 return false;
3980 }
3981 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3982 ALOGV("%s: Offload denied by duration < default min(=%u)",
3983 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3984 return false;
3985 }
3986 }
3987
3988 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3989 // creating an offloaded track and tearing it down immediately after start when audioflinger
3990 // detects there is an active non offloadable effect.
3991 // FIXME: We should check the audio session here but we do not have it in this context.
3992 // This may prevent offloading in rare situations where effects are left active by apps
3993 // in the background.
3994 if (mEffects.isNonOffloadableEffectEnabled()) {
3995 return false;
3996 }
3997
3998 return true;
3999}
4000
4001audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4002 const audio_config_t *config) {
4003 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4004 offloadInfo.format = config->format;
4005 offloadInfo.sample_rate = config->sample_rate;
4006 offloadInfo.channel_mask = config->channel_mask;
4007 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4008 offloadInfo.has_video = false;
4009 offloadInfo.is_streaming = false;
4010 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4011
4012 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4013 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4014 audio_flags_to_audio_output_flags(attr->flags, &flags);
4015 // only retain flags that will drive compressed offload or passthrough
4016 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4017 if (offloadPossible) {
4018 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4019 }
4020 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4021
jiabinc8f7dfc2022-01-06 18:42:08 +00004022 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004023 for (const auto& hwModule : mHwModules) {
4024 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004025 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004026 config->sample_rate, nullptr /*updatedSamplingRate*/,
4027 config->format, nullptr /*updatedFormat*/,
4028 config->channel_mask, nullptr /*updatedChannelMask*/,
4029 flags)) {
4030 continue;
4031 }
4032 // reject profiles not corresponding to a device currently available
4033 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4034 continue;
4035 }
4036 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4037 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004038 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004039 != AUDIO_DIRECT_NOT_SUPPORTED) {
4040 // Already reports offload gapless supported. No need to report offload support.
4041 continue;
4042 }
4043 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4044 != AUDIO_OUTPUT_FLAG_NONE) {
4045 // If offload gapless is reported, no need to report offload support.
4046 directMode = (audio_direct_mode_t) ((directMode &
4047 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4048 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4049 } else {
4050 directMode = (audio_direct_mode_t)(directMode |AUDIO_DIRECT_OFFLOAD_SUPPORTED);
4051 }
4052 } else {
4053 directMode = (audio_direct_mode_t) (directMode |
4054 AUDIO_DIRECT_BITSTREAM_SUPPORTED);
4055 }
4056 }
4057 }
4058 return directMode;
4059}
4060
Dorin Drimusf2196d82022-01-03 12:11:18 +01004061status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4062 AudioProfileVector& audioProfilesVector) {
4063 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004064 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004065 if (status != OK) {
4066 return status;
4067 }
4068 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4069 if (devices.empty()) {
4070 return OK; // no output devices for the attributes
4071 }
4072
4073 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004074 // the MSD module checks for different conditions
4075 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4076 continue;
4077 }
4078 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4079 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004080 continue;
4081 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004082 // allow only profiles that support all the available and routed devices
4083 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004084 != devices.size()) {
4085 continue;
4086 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004087 audioProfilesVector.addAllValidProfiles(
4088 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004089 }
4090 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004091
4092 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4093 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4094 if (msdModule != nullptr) {
4095 if (msdHasPatchesToAllDevices(devices)) {
4096 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4097 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4098 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4099 continue;
4100 }
4101 audioProfilesVector.addAllValidProfiles(
4102 outputProfile->asAudioPort()->getAudioProfiles());
4103 }
4104 } else {
4105 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4106 }
4107 }
4108
Dorin Drimusf2196d82022-01-03 12:11:18 +01004109 return NO_ERROR;
4110}
4111
Eric Laurent6a94d692014-05-20 11:18:06 -07004112status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4113 audio_port_type_t type,
4114 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004115 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004116 unsigned int *generation)
4117{
jiabin19cdba52020-11-24 11:28:58 -08004118 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4119 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004120 return BAD_VALUE;
4121 }
4122 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004123 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004124 *num_ports = 0;
4125 }
4126
4127 size_t portsWritten = 0;
4128 size_t portsMax = *num_ports;
4129 *num_ports = 0;
4130 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004131 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4132 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004133 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004134 for (const auto& dev : mAvailableOutputDevices) {
4135 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004136 continue;
4137 }
4138 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004139 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004140 }
4141 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004142 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004143 }
4144 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004145 for (const auto& dev : mAvailableInputDevices) {
4146 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004147 continue;
4148 }
4149 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004150 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004151 }
4152 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004153 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004154 }
4155 }
4156 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4157 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4158 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4159 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4160 }
4161 *num_ports += mInputs.size();
4162 }
4163 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004164 size_t numOutputs = 0;
4165 for (size_t i = 0; i < mOutputs.size(); i++) {
4166 if (!mOutputs[i]->isDuplicated()) {
4167 numOutputs++;
4168 if (portsWritten < portsMax) {
4169 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4170 }
4171 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004172 }
Eric Laurent84c70242014-06-23 08:46:27 -07004173 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004174 }
4175 }
4176 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004177 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004178 return NO_ERROR;
4179}
4180
jiabin19cdba52020-11-24 11:28:58 -08004181status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004182{
Eric Laurent99fcae42018-05-17 16:59:18 -07004183 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4184 return BAD_VALUE;
4185 }
4186 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4187 if (dev != 0) {
4188 dev->toAudioPort(port);
4189 return NO_ERROR;
4190 }
4191 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4192 if (dev != 0) {
4193 dev->toAudioPort(port);
4194 return NO_ERROR;
4195 }
4196 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4197 if (out != 0) {
4198 out->toAudioPort(port);
4199 return NO_ERROR;
4200 }
4201 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4202 if (in != 0) {
4203 in->toAudioPort(port);
4204 return NO_ERROR;
4205 }
4206 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004207}
4208
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004209status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4210 audio_patch_handle_t *handle,
4211 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004212{
François Gaffieafd4cea2019-11-18 15:50:22 +01004213 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004214 if (handle == NULL || patch == NULL) {
4215 return BAD_VALUE;
4216 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004217 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004218 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004219 return BAD_VALUE;
4220 }
4221 // only one source per audio patch supported for now
4222 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004223 return INVALID_OPERATION;
4224 }
Eric Laurent874c42872014-08-08 15:13:39 -07004225 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004226 return INVALID_OPERATION;
4227 }
Eric Laurent874c42872014-08-08 15:13:39 -07004228 for (size_t i = 0; i < patch->num_sinks; i++) {
4229 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4230 return INVALID_OPERATION;
4231 }
4232 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004233
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004234 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4235 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4236 if (srcDevice == nullptr || sinkDevice == nullptr) {
4237 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4238 return BAD_VALUE;
4239 }
4240 ALOGV("%s between source %s and sink %s", __func__,
4241 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4242 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4243 // Default attributes, default volume priority, not to infer with non raw audio patches.
4244 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4245 const struct audio_port_config *source = &patch->sources[0];
4246 sp<SourceClientDescriptor> sourceDesc =
4247 new InternalSourceClientDescriptor(
4248 portId, uid, attributes, *source, srcDevice, sinkDevice,
4249 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4250
4251 status_t status =
4252 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4253
4254 if (status != NO_ERROR) {
4255 return INVALID_OPERATION;
4256 }
4257 mAudioSources.add(portId, sourceDesc);
4258 return NO_ERROR;
4259}
4260
4261status_t AudioPolicyManager::connectAudioSourceToSink(
4262 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4263 const struct audio_patch *patch,
4264 audio_patch_handle_t &handle,
4265 uid_t uid, uint32_t delayMs)
4266{
4267 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4268 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4269 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4270 return INVALID_OPERATION;
4271 }
4272 sourceDesc->connect(handle, sinkDevice);
4273 if (isMsdPatch(handle)) {
4274 return NO_ERROR;
4275 }
4276 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4277 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4278 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4279 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4280 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4281 goto FailurePatchAdded;
4282 }
4283 status = swOutput->start();
4284 if (status != NO_ERROR) {
4285 goto FailureSourceAdded;
4286 }
4287 swOutput->addClient(sourceDesc);
4288 status = startSource(swOutput, sourceDesc, &delayMs);
4289 if (status != NO_ERROR) {
4290 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4291 goto FailureSourceActive;
4292 }
4293 if (delayMs != 0) {
4294 usleep(delayMs * 1000);
4295 }
4296 return NO_ERROR;
4297
4298FailureSourceActive:
4299 swOutput->stop();
4300 releaseOutput(sourceDesc->portId());
4301FailureSourceAdded:
4302 sourceDesc->setSwOutput(nullptr);
4303FailurePatchAdded:
4304 releaseAudioPatchInternal(handle);
4305 return INVALID_OPERATION;
4306}
4307
4308status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4309 audio_patch_handle_t *handle,
4310 uid_t uid, uint32_t delayMs,
4311 const sp<SourceClientDescriptor>& sourceDesc)
4312{
4313 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004314 sp<AudioPatch> patchDesc;
4315 ssize_t index = mAudioPatches.indexOfKey(*handle);
4316
François Gaffieafd4cea2019-11-18 15:50:22 +01004317 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4318 patch->sources[0].role,
4319 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004320#if LOG_NDEBUG == 0
4321 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004322 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4323 patch->sinks[i].role,
4324 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004325 }
4326#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004327
4328 if (index >= 0) {
4329 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004330 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4331 __func__, mUidCached, patchDesc->getUid(), uid);
4332 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004333 return INVALID_OPERATION;
4334 }
4335 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004336 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004337 }
4338
4339 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004340 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004341 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004342 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004343 return BAD_VALUE;
4344 }
Eric Laurent84c70242014-06-23 08:46:27 -07004345 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4346 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004347 if (patchDesc != 0) {
4348 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004349 ALOGV("%s source id differs for patch current id %d new id %d",
4350 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004351 return BAD_VALUE;
4352 }
4353 }
Eric Laurent874c42872014-08-08 15:13:39 -07004354 DeviceVector devices;
4355 for (size_t i = 0; i < patch->num_sinks; i++) {
4356 // Only support mix to devices connection
4357 // TODO add support for mix to mix connection
4358 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004359 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004360 return INVALID_OPERATION;
4361 }
4362 sp<DeviceDescriptor> devDesc =
4363 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4364 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004365 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004366 return BAD_VALUE;
4367 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004368
François Gaffie11d30102018-11-02 16:09:09 +01004369 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004370 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004371 NULL, // updatedSamplingRate
4372 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004373 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004374 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004375 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004376 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004377 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004378 return INVALID_OPERATION;
4379 }
4380 devices.add(devDesc);
4381 }
4382 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004383 return INVALID_OPERATION;
4384 }
Eric Laurent874c42872014-08-08 15:13:39 -07004385
Eric Laurent6a94d692014-05-20 11:18:06 -07004386 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004387 ALOGV("%s setting device %s on output %d",
4388 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004389 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004390 index = mAudioPatches.indexOfKey(*handle);
4391 if (index >= 0) {
4392 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004393 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004394 }
4395 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004396 patchDesc->setUid(uid);
4397 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004398 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004399 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004400 return INVALID_OPERATION;
4401 }
4402 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4403 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4404 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004405 // only one sink supported when connecting an input device to a mix
4406 if (patch->num_sinks > 1) {
4407 return INVALID_OPERATION;
4408 }
François Gaffie53615e22015-03-19 09:24:12 +01004409 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004410 if (inputDesc == NULL) {
4411 return BAD_VALUE;
4412 }
4413 if (patchDesc != 0) {
4414 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4415 return BAD_VALUE;
4416 }
4417 }
François Gaffie11d30102018-11-02 16:09:09 +01004418 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004419 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004420 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004421 return BAD_VALUE;
4422 }
4423
François Gaffie11d30102018-11-02 16:09:09 +01004424 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004425 patch->sinks[0].sample_rate,
4426 NULL, /*updatedSampleRate*/
4427 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004428 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004429 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004430 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004431 // FIXME for the parameter type,
4432 // and the NONE
4433 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004434 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004435 return INVALID_OPERATION;
4436 }
4437 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004438 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004439 device->toString().c_str(), inputDesc->mIoHandle);
4440 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004441 index = mAudioPatches.indexOfKey(*handle);
4442 if (index >= 0) {
4443 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004444 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004445 }
4446 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004447 patchDesc->setUid(uid);
4448 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004449 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004450 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004451 return INVALID_OPERATION;
4452 }
4453 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4454 // device to device connection
4455 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004456 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004457 return BAD_VALUE;
4458 }
4459 }
François Gaffie11d30102018-11-02 16:09:09 +01004460 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004461 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004462 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004463 return BAD_VALUE;
4464 }
Eric Laurent874c42872014-08-08 15:13:39 -07004465
Eric Laurent6a94d692014-05-20 11:18:06 -07004466 //update source and sink with our own data as the data passed in the patch may
4467 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004468 PatchBuilder patchBuilder;
4469 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004470
4471 // if first sink is to MSD, establish single MSD patch
4472 if (getMsdAudioOutDevices().contains(
4473 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4474 ALOGV("%s patching to MSD", __FUNCTION__);
4475 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4476 goto installPatch;
4477 }
4478
François Gaffieafd4cea2019-11-18 15:50:22 +01004479 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4480 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004481
Eric Laurent874c42872014-08-08 15:13:39 -07004482 for (size_t i = 0; i < patch->num_sinks; i++) {
4483 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004484 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004485 return INVALID_OPERATION;
4486 }
François Gaffie11d30102018-11-02 16:09:09 +01004487 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004488 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004489 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004490 return BAD_VALUE;
4491 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004492 audio_port_config sinkPortConfig = {};
4493 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4494 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004495
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004496 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4497 // volume management purpose (tracking activity)
4498 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4499 // in config XML to reach the sink so that is can be declared as available.
4500 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4501 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004502 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004503 // take care of dynamic routing for SwOutput selection,
4504 audio_attributes_t attributes = sourceDesc->attributes();
4505 audio_stream_type_t stream = sourceDesc->stream();
4506 audio_attributes_t resultAttr;
4507 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4508 config.sample_rate = sourceDesc->config().sample_rate;
4509 config.channel_mask = sourceDesc->config().channel_mask;
4510 config.format = sourceDesc->config().format;
4511 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4512 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4513 bool isRequestedDeviceForExclusiveUse = false;
4514 output_type_t outputType;
4515 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4516 &stream, sourceDesc->uid(), &config, &flags,
4517 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4518 nullptr, &outputType);
4519 if (output == AUDIO_IO_HANDLE_NONE) {
4520 ALOGV("%s no output for device %s",
4521 __FUNCTION__, sinkDevice->toString().c_str());
4522 return INVALID_OPERATION;
4523 }
4524 outputDesc = mOutputs.valueFor(output);
4525 if (outputDesc->isDuplicated()) {
4526 ALOGE("%s output is duplicated", __func__);
4527 return INVALID_OPERATION;
4528 }
4529 sourceDesc->setSwOutput(outputDesc);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004530 } else {
4531 // Same for "raw patches" aka created from createAudioPatch API
4532 SortedVector<audio_io_handle_t> outputs =
4533 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4534 // if the sink device is reachable via an opened output stream, request to
4535 // go via this output stream by adding a second source to the patch
4536 // description
4537 output = selectOutput(outputs);
4538 if (output == AUDIO_IO_HANDLE_NONE) {
4539 ALOGE("%s no output available for internal patch sink", __func__);
4540 return INVALID_OPERATION;
4541 }
4542 outputDesc = mOutputs.valueFor(output);
4543 if (outputDesc->isDuplicated()) {
4544 ALOGV("%s output for device %s is duplicated",
4545 __func__, sinkDevice->toString().c_str());
4546 return INVALID_OPERATION;
4547 }
4548 sourceDesc->setSwOutput(outputDesc);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004549 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004550 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004551 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004552 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004553 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004554 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4555 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004556 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4557 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004558 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004559 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004560 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004561 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004562 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004563 return INVALID_OPERATION;
4564 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004565 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004566 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004567 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004568 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004569 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004570 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4571 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4572 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004573 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004574 }
Eric Laurent83b88082014-06-20 18:31:16 -07004575 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004576 }
4577 // TODO: check from routing capabilities in config file and other conflicting patches
4578
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004579installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004580 status_t status = installPatch(
4581 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004582 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004583 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004584 return INVALID_OPERATION;
4585 }
4586 } else {
4587 return BAD_VALUE;
4588 }
4589 } else {
4590 return BAD_VALUE;
4591 }
4592 return NO_ERROR;
4593}
4594
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004595status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004596{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004597 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004598 ssize_t index = mAudioPatches.indexOfKey(handle);
4599
4600 if (index < 0) {
4601 return BAD_VALUE;
4602 }
4603 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004604 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4605 __func__, mUidCached, patchDesc->getUid(), uid);
4606 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004607 return INVALID_OPERATION;
4608 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004609 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4610 for (size_t i = 0; i < mAudioSources.size(); i++) {
4611 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4612 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4613 portId = sourceDesc->portId();
4614 break;
4615 }
4616 }
4617 return portId != AUDIO_PORT_HANDLE_NONE ?
4618 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004619}
Eric Laurent6a94d692014-05-20 11:18:06 -07004620
François Gaffieafd4cea2019-11-18 15:50:22 +01004621status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004622 uint32_t delayMs,
4623 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004624{
4625 ALOGV("%s patch %d", __func__, handle);
4626 if (mAudioPatches.indexOfKey(handle) < 0) {
4627 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4628 return BAD_VALUE;
4629 }
4630 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004631 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004632 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004633 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004634 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004635 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004636 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004637 return BAD_VALUE;
4638 }
4639
François Gaffie11d30102018-11-02 16:09:09 +01004640 setOutputDevices(outputDesc,
4641 getNewOutputDevices(outputDesc, true /*fromCache*/),
4642 true,
4643 0,
4644 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004645 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4646 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004647 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004648 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004649 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004650 return BAD_VALUE;
4651 }
4652 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004653 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004654 true,
4655 NULL);
4656 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004657 status_t status =
4658 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4659 ALOGV("%s patch panel returned %d patchHandle %d",
4660 __func__, status, patchDesc->getAfHandle());
4661 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004662 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004663 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004664 // SW or HW Bridge
4665 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4666 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004667 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004668 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4669 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4670 outputDesc = sourceDesc->swOutput().promote();
4671 }
4672 if (outputDesc == nullptr) {
4673 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4674 // releaseOutput has already called closeOutput in case of direct output
4675 return NO_ERROR;
4676 }
4677 if (!outputDesc->isActive() && !sourceDesc->useSwBridge()) {
4678 resetOutputDevice(outputDesc);
4679 } else {
4680 // Reuse patch handle if still valid / do not force rerouting if still routed
4681 patchHandle = outputDesc->getPatchHandle();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004682 setOutputDevices(outputDesc,
4683 getNewOutputDevices(outputDesc, true /*fromCache*/),
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004684 patchHandle == AUDIO_PATCH_HANDLE_NONE, /*force*/
Francois Gaffie7feb8542020-04-06 17:39:47 +02004685 0,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004686 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Francois Gaffie7feb8542020-04-06 17:39:47 +02004687 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 } else {
4689 return BAD_VALUE;
4690 }
4691 } else {
4692 return BAD_VALUE;
4693 }
4694 return NO_ERROR;
4695}
4696
4697status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4698 struct audio_patch *patches,
4699 unsigned int *generation)
4700{
François Gaffie53615e22015-03-19 09:24:12 +01004701 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004702 return BAD_VALUE;
4703 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004704 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004705 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004706}
4707
Eric Laurente1715a42014-05-20 11:30:42 -07004708status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004709{
Eric Laurente1715a42014-05-20 11:30:42 -07004710 ALOGV("setAudioPortConfig()");
4711
4712 if (config == NULL) {
4713 return BAD_VALUE;
4714 }
4715 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4716 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004717 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4718 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004719 }
4720
Eric Laurenta121f902014-06-03 13:32:54 -07004721 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004722 if (config->type == AUDIO_PORT_TYPE_MIX) {
4723 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004724 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004725 if (outputDesc == NULL) {
4726 return BAD_VALUE;
4727 }
Eric Laurent84c70242014-06-23 08:46:27 -07004728 ALOG_ASSERT(!outputDesc->isDuplicated(),
4729 "setAudioPortConfig() called on duplicated output %d",
4730 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004731 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004732 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004733 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004734 if (inputDesc == NULL) {
4735 return BAD_VALUE;
4736 }
Eric Laurenta121f902014-06-03 13:32:54 -07004737 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004738 } else {
4739 return BAD_VALUE;
4740 }
4741 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4742 sp<DeviceDescriptor> deviceDesc;
4743 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4744 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4745 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4746 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4747 } else {
4748 return BAD_VALUE;
4749 }
4750 if (deviceDesc == NULL) {
4751 return BAD_VALUE;
4752 }
Eric Laurenta121f902014-06-03 13:32:54 -07004753 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004754 } else {
4755 return BAD_VALUE;
4756 }
4757
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004758 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004759 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4760 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004761 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004762 audioPortConfig->toAudioPortConfig(&newConfig, config);
4763 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004764 }
Eric Laurenta121f902014-06-03 13:32:54 -07004765 if (status != NO_ERROR) {
4766 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004767 }
Eric Laurente1715a42014-05-20 11:30:42 -07004768
4769 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004770}
4771
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004772void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4773{
Eric Laurentd60560a2015-04-10 11:31:20 -07004774 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004775 clearAudioPatches(uid);
4776 clearSessionRoutes(uid);
4777}
4778
Eric Laurent6a94d692014-05-20 11:18:06 -07004779void AudioPolicyManager::clearAudioPatches(uid_t uid)
4780{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004781 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004782 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004783 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004784 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004785 }
4786 }
4787}
4788
François Gaffiec005e562018-11-06 15:04:49 +01004789void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004790{
François Gaffiec005e562018-11-06 15:04:49 +01004791 // Take the first attributes following the product strategy as it is used to retrieve the routed
4792 // device. All attributes wihin a strategy follows the same "routing strategy"
4793 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4794 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004795 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004796 for (size_t j = 0; j < mOutputs.size(); j++) {
4797 if (mOutputs.keyAt(j) == ouptutToSkip) {
4798 continue;
4799 }
4800 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004801 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004802 continue;
4803 }
4804 // If the default device for this strategy is on another output mix,
4805 // invalidate all tracks in this strategy to force re connection.
4806 // Otherwise select new device on the output mix.
4807 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004808 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4809 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004810 }
4811 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004812 setOutputDevices(
4813 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004814 }
4815 }
4816}
4817
4818void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4819{
4820 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004821 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004822 for (size_t i = 0; i < mOutputs.size(); i++) {
4823 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004824 for (const auto& client : outputDesc->getClientIterable()) {
4825 if (client->hasPreferredDevice() && client->uid() == uid) {
4826 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004827 auto clientStrategy = client->strategy();
4828 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4829 end(affectedStrategies)) {
4830 continue;
4831 }
4832 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004833 }
4834 }
4835 }
4836 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004837 for (const auto& strategy : affectedStrategies) {
4838 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004839 }
4840
4841 // remove input routes associated with this uid
4842 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004843 for (size_t i = 0; i < mInputs.size(); i++) {
4844 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004845 for (const auto& client : inputDesc->getClientIterable()) {
4846 if (client->hasPreferredDevice() && client->uid() == uid) {
4847 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4848 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004849 }
4850 }
4851 }
4852 // reroute inputs if necessary
4853 SortedVector<audio_io_handle_t> inputsToClose;
4854 for (size_t i = 0; i < mInputs.size(); i++) {
4855 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004856 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004857 inputsToClose.add(inputDesc->mIoHandle);
4858 }
4859 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004860 for (const auto& input : inputsToClose) {
4861 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004862 }
4863}
4864
Eric Laurentd60560a2015-04-10 11:31:20 -07004865void AudioPolicyManager::clearAudioSources(uid_t uid)
4866{
4867 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004868 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4869 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004870 stopAudioSource(mAudioSources.keyAt(i));
4871 }
4872 }
4873}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004874
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004875status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4876 audio_io_handle_t *ioHandle,
4877 audio_devices_t *device)
4878{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004879 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4880 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004881 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004882 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004883
François Gaffiedf372692015-03-19 10:43:27 +01004884 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004885}
4886
Eric Laurentd60560a2015-04-10 11:31:20 -07004887status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004888 const audio_attributes_t *attributes,
4889 audio_port_handle_t *portId,
4890 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004891{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004892 ALOGV("%s", __FUNCTION__);
4893 *portId = AUDIO_PORT_HANDLE_NONE;
4894
4895 if (source == NULL || attributes == NULL || portId == NULL) {
4896 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4897 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004898 return BAD_VALUE;
4899 }
4900
Eric Laurentd60560a2015-04-10 11:31:20 -07004901 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4902 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004903 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4904 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004905 return INVALID_OPERATION;
4906 }
4907
François Gaffie11d30102018-11-02 16:09:09 +01004908 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004909 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004910 String8(source->ext.device.address),
4911 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004912 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004913 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004914 return BAD_VALUE;
4915 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004916
jiabin4ef93452019-09-10 14:29:54 -07004917 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004918
François Gaffieaaac0fd2018-11-22 17:56:39 +01004919 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004920 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004921 mEngine->getStreamTypeForAttributes(*attributes),
4922 mEngine->getProductStrategyForAttributes(*attributes),
4923 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004924
4925 status_t status = connectAudioSource(sourceDesc);
4926 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004927 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004928 }
4929 return status;
4930}
4931
Francois Gaffie601801d2021-06-22 13:27:39 +02004932sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4933 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4934{
4935 ALOGV("%s", __FUNCTION__);
4936 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4937
4938 status_t status = startAudioSource(source, attributes, &portId, uid);
4939 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4940 return mAudioSources.valueFor(portId);
4941}
4942
4943
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004944status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004945{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004946 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004947
4948 // make sure we only have one patch per source.
4949 disconnectAudioSource(sourceDesc);
4950
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004951 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004952 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4953 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4954 sourceDesc->srcDevice()->type(),
4955 String8(sourceDesc->srcDevice()->address().c_str()),
4956 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004957 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004958 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004959 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004960 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004961 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4962 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4963 return INVALID_OPERATION;
4964 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004965 PatchBuilder patchBuilder;
4966 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4967 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01004968
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004969 return connectAudioSourceToSink(
4970 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07004971}
4972
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004973status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004974{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004975 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4976 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004977 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004978 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004979 return BAD_VALUE;
4980 }
4981 status_t status = disconnectAudioSource(sourceDesc);
4982
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004983 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004984 return status;
4985}
4986
Andy Hung2ddee192015-12-18 17:34:44 -08004987status_t AudioPolicyManager::setMasterMono(bool mono)
4988{
4989 if (mMasterMono == mono) {
4990 return NO_ERROR;
4991 }
4992 mMasterMono = mono;
4993 // if enabling mono we close all offloaded devices, which will invalidate the
4994 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4995 // for recreating the new AudioTrack as non-offloaded PCM.
4996 //
4997 // If disabling mono, we leave all tracks as is: we don't know which clients
4998 // and tracks are able to be recreated as offloaded. The next "song" should
4999 // play back offloaded.
5000 if (mMasterMono) {
5001 Vector<audio_io_handle_t> offloaded;
5002 for (size_t i = 0; i < mOutputs.size(); ++i) {
5003 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5004 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5005 offloaded.push(desc->mIoHandle);
5006 }
5007 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005008 for (const auto& handle : offloaded) {
5009 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005010 }
5011 }
5012 // update master mono for all remaining outputs
5013 for (size_t i = 0; i < mOutputs.size(); ++i) {
5014 updateMono(mOutputs.keyAt(i));
5015 }
5016 return NO_ERROR;
5017}
5018
5019status_t AudioPolicyManager::getMasterMono(bool *mono)
5020{
5021 *mono = mMasterMono;
5022 return NO_ERROR;
5023}
5024
Eric Laurentac9cef52017-06-09 15:46:26 -07005025float AudioPolicyManager::getStreamVolumeDB(
5026 audio_stream_type_t stream, int index, audio_devices_t device)
5027{
jiabin9a3361e2019-10-01 09:38:30 -07005028 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005029}
5030
jiabin81772902018-04-02 17:52:27 -07005031status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5032 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005033 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005034{
Kriti Dang6537def2021-03-02 13:46:59 +01005035 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5036 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005037 return BAD_VALUE;
5038 }
Kriti Dang6537def2021-03-02 13:46:59 +01005039 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5040 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005041
5042 size_t formatsWritten = 0;
5043 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005044
Kriti Dang6537def2021-03-02 13:46:59 +01005045 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005046 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5047 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005048 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005049 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005050 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005051 bool formatEnabled = true;
5052 switch (forceUse) {
5053 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005054 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005055 break;
5056 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5057 formatEnabled = false;
5058 break;
5059 default: // AUTO or ALWAYS => true
5060 break;
jiabin81772902018-04-02 17:52:27 -07005061 }
5062 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5063 }
jiabin81772902018-04-02 17:52:27 -07005064 }
5065 return NO_ERROR;
5066}
5067
Kriti Dang6537def2021-03-02 13:46:59 +01005068status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5069 audio_format_t *surroundFormats) {
5070 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5071 return BAD_VALUE;
5072 }
5073 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5074 __func__, *numSurroundFormats, surroundFormats);
5075
5076 size_t formatsWritten = 0;
5077 size_t formatsMax = *numSurroundFormats;
5078 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5079
5080 // Return formats from all device profiles that have already been resolved by
5081 // checkOutputsForDevice().
5082 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5083 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5084 audio_devices_t deviceType = device->type();
5085 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5086 // returns formats reported by HDMI devices.
5087 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5088 continue;
5089 }
5090 // Formats reported by sink devices
5091 std::unordered_set<audio_format_t> formatset;
5092 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5093 formatset.insert(it->second.begin(), it->second.end());
5094 }
5095
5096 // Formats hard-coded in the in policy configuration file (if any).
5097 FormatVector encodedFormats = device->encodedFormats();
5098 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5099 // Filter the formats which are supported by the vendor hardware.
5100 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5101 if (mConfig.getSurroundFormats().count(*it) != 0) {
5102 formats.insert(*it);
5103 } else {
5104 for (const auto& pair : mConfig.getSurroundFormats()) {
5105 if (pair.second.count(*it) != 0) {
5106 formats.insert(pair.first);
5107 break;
5108 }
5109 }
5110 }
5111 }
5112 }
5113 *numSurroundFormats = formats.size();
5114 for (const auto& format: formats) {
5115 if (formatsWritten < formatsMax) {
5116 surroundFormats[formatsWritten++] = format;
5117 }
5118 }
5119 return NO_ERROR;
5120}
5121
jiabin81772902018-04-02 17:52:27 -07005122status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5123{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005124 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005125 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5126 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005127 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005128 return BAD_VALUE;
5129 }
5130
Mikhail Naganov100f0122018-11-29 11:22:16 -08005131 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5132 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005133 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005134 return INVALID_OPERATION;
5135 }
5136
Mikhail Naganov100f0122018-11-29 11:22:16 -08005137 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005138 return NO_ERROR;
5139 }
5140
Mikhail Naganov100f0122018-11-29 11:22:16 -08005141 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005142 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005143 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005144 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005145 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005146 }
5147 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005148 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005149 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005150 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005151 }
5152 }
5153
5154 sp<SwAudioOutputDescriptor> outputDesc;
5155 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005156 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5157 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005158 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5159 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005160 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005161 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005162 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5163 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5164 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005165 name.c_str(),
5166 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005167 if (status != NO_ERROR) {
5168 continue;
5169 }
5170 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5171 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5172 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005173 name.c_str(),
5174 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005175 profileUpdated |= (status == NO_ERROR);
5176 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005177 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005178 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005179 AUDIO_DEVICE_IN_HDMI);
5180 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5181 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005182 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005183 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005184 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5185 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5186 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005187 name.c_str(),
5188 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005189 if (status != NO_ERROR) {
5190 continue;
5191 }
5192 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5193 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5194 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005195 name.c_str(),
5196 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005197 profileUpdated |= (status == NO_ERROR);
5198 }
5199
jiabin81772902018-04-02 17:52:27 -07005200 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005201 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005202 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005203 }
5204
5205 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5206}
5207
Eric Laurent5ada82e2019-08-29 17:53:54 -07005208void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005209{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005210 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005211 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005212 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005213 }
5214}
5215
jiabin6012f912018-11-02 17:06:30 -07005216bool AudioPolicyManager::isHapticPlaybackSupported()
5217{
5218 for (const auto& hwModule : mHwModules) {
5219 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5220 for (const auto &outProfile : outputProfiles) {
5221 struct audio_port audioPort;
5222 outProfile->toAudioPort(&audioPort);
5223 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5224 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5225 return true;
5226 }
5227 }
5228 }
5229 }
5230 return false;
5231}
5232
Carter Hsu325a8eb2022-01-19 19:56:51 +08005233bool AudioPolicyManager::isUltrasoundSupported()
5234{
5235 bool hasUltrasoundOutput = false;
5236 bool hasUltrasoundInput = false;
5237 for (const auto& hwModule : mHwModules) {
5238 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5239 if (!hasUltrasoundOutput) {
5240 for (const auto &outProfile : outputProfiles) {
5241 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5242 hasUltrasoundOutput = true;
5243 break;
5244 }
5245 }
5246 }
5247
5248 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5249 if (!hasUltrasoundInput) {
5250 for (const auto &inputProfile : inputProfiles) {
5251 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5252 hasUltrasoundInput = true;
5253 break;
5254 }
5255 }
5256 }
5257
5258 if (hasUltrasoundOutput && hasUltrasoundInput)
5259 return true;
5260 }
5261 return false;
5262}
5263
Eric Laurent8340e672019-11-06 11:01:08 -08005264bool AudioPolicyManager::isCallScreenModeSupported()
5265{
5266 return getConfig().isCallScreenModeSupported();
5267}
5268
5269
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005270status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005271{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005272 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005273 if (!sourceDesc->isConnected()) {
5274 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5275 return NO_ERROR;
5276 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005277 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5278 if (swOutput != 0) {
5279 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005280 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005281 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005282 }
jiabinbce0c1d2020-10-05 11:20:18 -07005283 if (releaseOutput(sourceDesc->portId())) {
5284 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5285 // no need to release audio patch here but just return NO_ERROR.
5286 return NO_ERROR;
5287 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005288 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005289 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005290 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005291 // close Hwoutput and remove from mHwOutputs
5292 } else {
5293 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5294 }
5295 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005296 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005297 sourceDesc->disconnect();
5298 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005299}
5300
François Gaffiec005e562018-11-06 15:04:49 +01005301sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5302 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005303{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005304 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005305 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005306 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005307 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005308 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5309 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005310 source = sourceDesc;
5311 break;
5312 }
5313 }
5314 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005315}
5316
Eric Laurent39095982021-08-24 18:29:27 +02005317/* static */
5318bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
5319 switch (channels) {
5320 case AUDIO_CHANNEL_OUT_5POINT1:
5321 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
5322 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
5323 case AUDIO_CHANNEL_OUT_7POINT1:
5324 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
5325 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
5326 return true;
5327 default:
5328 return false;
5329 }
5330}
5331
Eric Laurentb4f42a92022-01-17 17:37:31 +01005332bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005333 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005334 const AudioDeviceTypeAddrVector &devices,
5335 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005336{
5337 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5338 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005339 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005340 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005341 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5342 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5343 return false;
5344 }
5345 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5346 return false;
5347 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005348 }
5349
5350 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005351 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5352 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005353 // to the specified devices must exist.
5354 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005355 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005356 if (profile == nullptr) {
5357 return false;
5358 }
5359
5360 // The caller can have the audio config criteria ignored by either passing a null ptr or
5361 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005362 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005363 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005364 // If the spatializer output is already opened, only channel masks included in the
5365 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005366
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005367 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005368 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005369 return false;
5370 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005371 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5372 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005373 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005374 != config->channel_mask) {
5375 return false;
5376 }
5377 }
5378 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005379 return true;
5380}
5381
5382void AudioPolicyManager::checkVirtualizerClientRoutes() {
5383 std::set<audio_stream_type_t> streamsToInvalidate;
5384 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005385 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5386 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005387 audio_attributes_t attr = client->attributes();
5388 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5389 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5390 audio_config_base_t clientConfig = client->config();
5391 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005392 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005393 && canBeSpatializedInt(&attr, &config,
5394 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005395 streamsToInvalidate.insert(client->stream());
5396 }
5397 }
5398 }
5399
5400 for (audio_stream_type_t stream : streamsToInvalidate) {
5401 mpClientInterface->invalidateStream(stream);
5402 }
5403}
5404
Eric Laurentfa0f6742021-08-17 18:39:44 +02005405status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005406 const audio_attributes_t *attr,
5407 audio_io_handle_t *output) {
5408 *output = AUDIO_IO_HANDLE_NONE;
5409
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005410 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5411 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5412 audio_config_t *configPtr = nullptr;
5413 audio_config_t config;
5414 if (mixerConfig != nullptr) {
5415 config = audio_config_initializer(mixerConfig);
5416 configPtr = &config;
5417 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005418 if (!canBeSpatializedInt(
5419 attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02005420 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005421 return BAD_VALUE;
5422 }
5423
5424 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005425 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005426 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005427 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005428 return BAD_VALUE;
5429 }
5430
Eric Laurent39095982021-08-24 18:29:27 +02005431 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
5432 && configPtr != nullptr
5433 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
5434 *output = mSpatializerOutput->mIoHandle;
5435 ALOGV("%s returns current spatializer output %d", __func__, *output);
5436 return NO_ERROR;
5437 }
5438 mSpatializerOutput.clear();
5439 for (size_t i = 0; i < mOutputs.size(); i++) {
5440 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5441 if (!desc->isDuplicated() && desc->mProfile == profile) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005442 ALOGV("%s found output %d for spatializer profile", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005443 mSpatializerOutput = desc;
5444 break;
5445 }
5446 }
5447 if (mSpatializerOutput == nullptr) {
5448 ALOGW("%s no opened spatializer output for profile %s",
5449 __func__, profile->getName().c_str());
5450 return BAD_VALUE;
5451 }
5452
5453 if (configPtr != nullptr
5454 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5455 audio_config_base_t savedMixerConfig = {
5456 .sample_rate = mSpatializerOutput->getSamplingRate(),
5457 .format = mSpatializerOutput->getFormat(),
5458 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5459 };
5460 DeviceVector savedDevices = mSpatializerOutput->devices();
5461
Eric Laurentb4f42a92022-01-17 17:37:31 +01005462 ALOGV("%s reopening spatializer output to match channel mask %#x (current mask %#x)",
5463 __func__, configPtr->channel_mask, mSpatializerOutput->mMixerChannelMask);
Eric Laurent39095982021-08-24 18:29:27 +02005464
Eric Laurentb4f42a92022-01-17 17:37:31 +01005465 closeOutput(mSpatializerOutput->mIoHandle);
5466 //from now on mSpatializerOutput is null
5467
5468 sp<SwAudioOutputDescriptor> desc =
5469 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
5470 if (desc == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005471 // re open the spatializer output with previous channel mask
Eric Laurentb4f42a92022-01-17 17:37:31 +01005472 desc = openOutputWithProfileAndDevice(profile, savedDevices, &savedMixerConfig);
5473 if (desc == nullptr) {
5474 ALOGE("%s failed to restore mSpatializerOutput with previous config", __func__);
Eric Laurent39095982021-08-24 18:29:27 +02005475 } else {
5476 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005477 }
5478 mPreviousOutputs = mOutputs;
5479 mpClientInterface->onAudioPortListUpdate();
5480 *output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005481 ALOGW("%s could not open spatializer output with requested config", __func__);
5482 return BAD_VALUE;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005483 }
Eric Laurent39095982021-08-24 18:29:27 +02005484 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005485 mPreviousOutputs = mOutputs;
5486 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005487 }
5488
5489 checkVirtualizerClientRoutes();
5490
Eric Laurent39095982021-08-24 18:29:27 +02005491 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005492 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005493 return NO_ERROR;
5494}
5495
Eric Laurentfa0f6742021-08-17 18:39:44 +02005496status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5497 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005498 return INVALID_OPERATION;
5499 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005500 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005501 return BAD_VALUE;
5502 }
Eric Laurent39095982021-08-24 18:29:27 +02005503
Eric Laurentfa0f6742021-08-17 18:39:44 +02005504 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005505
5506 checkVirtualizerClientRoutes();
5507
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005508 return NO_ERROR;
5509}
5510
Eric Laurente552edb2014-03-10 17:42:56 -07005511// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005512// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005513// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005514uint32_t AudioPolicyManager::nextAudioPortGeneration()
5515{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005516 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005517}
5518
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005519static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005520 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5521 !audioPolicyXmlConfigFile.empty()) {
5522 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5523 if (ret == NO_ERROR) {
5524 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005525 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005526 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005527 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005528 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005529}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005530
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005531AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5532 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005533 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005534 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005535 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005536 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005537 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005538 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005539 mAudioPortGeneration(1),
5540 mBeaconMuteRefCount(0),
5541 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005542 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005543 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005544 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005545 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005546{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005547}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005548
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005549AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5550 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5551{
5552 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005553}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005554
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005555void AudioPolicyManager::loadConfig() {
5556 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005557 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005558 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005559 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005560}
5561
5562status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005563 {
5564 auto engLib = EngineLibrary::load(
5565 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5566 if (!engLib) {
5567 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5568 return NO_INIT;
5569 }
5570 mEngine = engLib->createEngine();
5571 if (mEngine == nullptr) {
5572 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5573 return NO_INIT;
5574 }
François Gaffie2110e042015-03-24 08:41:51 +01005575 }
5576 mEngine->setObserver(this);
5577 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005578 if (status != NO_ERROR) {
5579 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5580 return status;
5581 }
François Gaffie2110e042015-03-24 08:41:51 +01005582
Eric Laurent1d69c872021-01-11 18:53:01 +01005583 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5584 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5585
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005586 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005587 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005588 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005589
Eric Laurent3a4311c2014-03-17 12:00:47 -07005590 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005591 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5592 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5593 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005594 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005595 }
jiabin9ff780e2018-03-19 18:19:52 -07005596 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005597 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005598 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005599 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005600 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005601 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005602 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005603 }
5604 }
5605 }
Eric Laurente552edb2014-03-10 17:42:56 -07005606
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005607 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005608
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005609 // Silence ALOGV statements
5610 property_set("log.tag." LOG_TAG, "D");
5611
Eric Laurente552edb2014-03-10 17:42:56 -07005612 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005613 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005614}
5615
Eric Laurente0720872014-03-11 09:30:41 -07005616AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005617{
Eric Laurente552edb2014-03-10 17:42:56 -07005618 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005619 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005620 }
5621 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005622 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005623 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005624 mAvailableOutputDevices.clear();
5625 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005626 mOutputs.clear();
5627 mInputs.clear();
5628 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005629 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005630 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005631}
5632
Eric Laurente0720872014-03-11 09:30:41 -07005633status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005634{
Eric Laurent87ffa392015-05-22 10:32:38 -07005635 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005636}
5637
Eric Laurente552edb2014-03-10 17:42:56 -07005638// ---
5639
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005640void AudioPolicyManager::onNewAudioModulesAvailable()
5641{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005642 DeviceVector newDevices;
5643 onNewAudioModulesAvailableInt(&newDevices);
5644 if (!newDevices.empty()) {
5645 nextAudioPortGeneration();
5646 mpClientInterface->onAudioPortListUpdate();
5647 }
5648}
5649
5650void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5651{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005652 for (const auto& hwModule : mHwModulesAll) {
5653 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5654 continue;
5655 }
5656 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5657 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5658 ALOGW("could not open HW module %s", hwModule->getName());
5659 continue;
5660 }
5661 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005662 // open all output streams needed to access attached devices.
5663 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005664 // This also validates mAvailableOutputDevices list
5665 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5666 if (!outProfile->canOpenNewIo()) {
5667 ALOGE("Invalid Output profile max open count %u for profile %s",
5668 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5669 continue;
5670 }
5671 if (!outProfile->hasSupportedDevices()) {
5672 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5673 continue;
5674 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005675 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5676 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005677 mTtsOutputAvailable = true;
5678 }
5679
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005680 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5681 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5682 sp<DeviceDescriptor> supportedDevice = 0;
5683 if (supportedDevices.contains(mDefaultOutputDevice)) {
5684 supportedDevice = mDefaultOutputDevice;
5685 } else {
5686 // choose first device present in profile's SupportedDevices also part of
5687 // mAvailableOutputDevices.
5688 if (availProfileDevices.isEmpty()) {
5689 continue;
5690 }
5691 supportedDevice = availProfileDevices.itemAt(0);
5692 }
5693 if (!mOutputDevicesAll.contains(supportedDevice)) {
5694 continue;
5695 }
5696 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5697 mpClientInterface);
5698 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005699 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5700 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005701 AUDIO_STREAM_DEFAULT,
5702 AUDIO_OUTPUT_FLAG_NONE, &output);
5703 if (status != NO_ERROR) {
5704 ALOGW("Cannot open output stream for devices %s on hw module %s",
5705 supportedDevice->toString().c_str(), hwModule->getName());
5706 continue;
5707 }
5708 for (const auto &device : availProfileDevices) {
5709 // give a valid ID to an attached device once confirmed it is reachable
5710 if (!device->isAttached()) {
5711 device->attach(hwModule);
5712 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005713 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005714 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005715 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5716 }
5717 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005718 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005719 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5720 mPrimaryOutput = outputDesc;
5721 }
Eric Laurent39095982021-08-24 18:29:27 +02005722 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005723 outputDesc->close();
5724 } else {
5725 addOutput(output, outputDesc);
5726 setOutputDevices(outputDesc,
5727 DeviceVector(supportedDevice),
5728 true,
5729 0,
5730 NULL);
5731 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005732 }
5733 // open input streams needed to access attached devices to validate
5734 // mAvailableInputDevices list
5735 for (const auto& inProfile : hwModule->getInputProfiles()) {
5736 if (!inProfile->canOpenNewIo()) {
5737 ALOGE("Invalid Input profile max open count %u for profile %s",
5738 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5739 continue;
5740 }
5741 if (!inProfile->hasSupportedDevices()) {
5742 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5743 continue;
5744 }
5745 // chose first device present in profile's SupportedDevices also part of
5746 // available input devices
5747 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5748 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5749 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005750 ALOGV("%s: Input device list is empty! for profile %s",
5751 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005752 continue;
5753 }
5754 sp<AudioInputDescriptor> inputDesc =
5755 new AudioInputDescriptor(inProfile, mpClientInterface);
5756
5757 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5758 status_t status = inputDesc->open(nullptr,
5759 availProfileDevices.itemAt(0),
5760 AUDIO_SOURCE_MIC,
5761 AUDIO_INPUT_FLAG_NONE,
5762 &input);
5763 if (status != NO_ERROR) {
5764 ALOGW("Cannot open input stream for device %s on hw module %s",
5765 availProfileDevices.toString().c_str(),
5766 hwModule->getName());
5767 continue;
5768 }
5769 for (const auto &device : availProfileDevices) {
5770 // give a valid ID to an attached device once confirmed it is reachable
5771 if (!device->isAttached()) {
5772 device->attach(hwModule);
5773 device->importAudioPortAndPickAudioProfile(inProfile, true);
5774 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005775 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005776 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5777 }
5778 }
5779 inputDesc->close();
5780 }
5781 }
5782}
5783
Eric Laurent98e38192018-02-15 18:31:53 -08005784void AudioPolicyManager::addOutput(audio_io_handle_t output,
5785 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005786{
Eric Laurent1c333e22014-05-20 10:48:17 -07005787 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005788 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005789 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005790 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005791 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005792}
5793
François Gaffie53615e22015-03-19 09:24:12 +01005794void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5795{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005796 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5797 ALOGV("%s: removing primary output", __func__);
5798 mPrimaryOutput = nullptr;
5799 }
François Gaffie53615e22015-03-19 09:24:12 +01005800 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005801 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005802}
5803
Eric Laurent98e38192018-02-15 18:31:53 -08005804void AudioPolicyManager::addInput(audio_io_handle_t input,
5805 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005806{
Eric Laurent1c333e22014-05-20 10:48:17 -07005807 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005808 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005809}
Eric Laurente552edb2014-03-10 17:42:56 -07005810
François Gaffie11d30102018-11-02 16:09:09 +01005811status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005812 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005813 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005814{
François Gaffie11d30102018-11-02 16:09:09 +01005815 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005816 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005817 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005818
François Gaffie11d30102018-11-02 16:09:09 +01005819 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005820 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005821 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005822 }
Eric Laurente552edb2014-03-10 17:42:56 -07005823
Eric Laurent3b73df72014-03-11 09:06:29 -07005824 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005825 // first call getAudioPort to get the supported attributes from the HAL
5826 struct audio_port_v7 port = {};
5827 device->toAudioPort(&port);
5828 status_t status = mpClientInterface->getAudioPort(&port);
5829 if (status == NO_ERROR) {
5830 device->importAudioPort(port);
5831 }
5832
5833 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005834 for (size_t i = 0; i < mOutputs.size(); i++) {
5835 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005836 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005837 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005838 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5839 mOutputs.keyAt(i), device->toString().c_str());
5840 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005841 }
5842 }
5843 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005844 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005845 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005846 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5847 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005848 if (profile->supportsDevice(device)) {
5849 profiles.add(profile);
5850 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5851 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005852 }
5853 }
5854 }
5855
Eric Laurent7b279bb2015-12-14 10:18:23 -08005856 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005857
Eric Laurente552edb2014-03-10 17:42:56 -07005858 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005859 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005860 return BAD_VALUE;
5861 }
5862
5863 // open outputs for matching profiles if needed. Direct outputs are also opened to
5864 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5865 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005866 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005867
5868 // nothing to do if one output is already opened for this profile
5869 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005870 for (j = 0; j < outputs.size(); j++) {
5871 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005872 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005873 // matching profile: save the sample rates, format and channel masks supported
5874 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005875 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005876 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005877 }
Eric Laurente552edb2014-03-10 17:42:56 -07005878 break;
5879 }
5880 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005881 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005882 continue;
5883 }
5884
Eric Laurent3974e3b2017-12-07 17:58:43 -08005885 if (!profile->canOpenNewIo()) {
5886 ALOGW("Max Output number %u already opened for this profile %s",
5887 profile->maxOpenCount, profile->getTagName().c_str());
5888 continue;
5889 }
5890
Eric Laurent83efe1c2017-07-09 16:51:08 -07005891 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005892 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005893 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5894 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005895 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005896 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005897 profiles.removeAt(profile_index);
5898 profile_index--;
5899 } else {
5900 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005901 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005902 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005903 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5904 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005905 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005906 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005907
François Gaffie11d30102018-11-02 16:09:09 +01005908 if (device_distinguishes_on_address(deviceType)) {
5909 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5910 device->toString().c_str());
5911 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5912 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005913 }
Eric Laurente552edb2014-03-10 17:42:56 -07005914 ALOGV("checkOutputsForDevice(): adding output %d", output);
5915 }
5916 }
5917
5918 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005919 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005920 return BAD_VALUE;
5921 }
Eric Laurentd4692962014-05-05 18:13:44 -07005922 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005923 // check if one opened output is not needed any more after disconnecting one device
5924 for (size_t i = 0; i < mOutputs.size(); i++) {
5925 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005926 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005927 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005928 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005929 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005930 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005931 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005932 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5933 mOutputs.keyAt(i));
5934 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005935 }
Eric Laurente552edb2014-03-10 17:42:56 -07005936 }
5937 }
Eric Laurentd4692962014-05-05 18:13:44 -07005938 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005939 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005940 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5941 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005942 if (!profile->supportsDevice(device)) {
5943 continue;
5944 }
5945 ALOGV("checkOutputsForDevice(): "
5946 "clearing direct output profile %zu on module %s",
5947 j, hwModule->getName());
5948 profile->clearAudioProfiles();
5949 if (!profile->hasDynamicAudioProfile()) {
5950 continue;
5951 }
5952 // When a device is disconnected, if there is an IOProfile that contains dynamic
5953 // profiles and supports the disconnected device, call getAudioPort to repopulate
5954 // the capabilities of the devices that is supported by the IOProfile.
5955 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5956 if (supportedDevice == device ||
5957 !mAvailableOutputDevices.contains(supportedDevice)) {
5958 continue;
5959 }
5960 struct audio_port_v7 port;
5961 supportedDevice->toAudioPort(&port);
5962 status_t status = mpClientInterface->getAudioPort(&port);
5963 if (status == NO_ERROR) {
5964 supportedDevice->importAudioPort(port);
5965 }
Eric Laurente552edb2014-03-10 17:42:56 -07005966 }
5967 }
5968 }
5969 }
5970 return NO_ERROR;
5971}
5972
François Gaffie11d30102018-11-02 16:09:09 +01005973status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005974 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005975{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005976 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005977
François Gaffie11d30102018-11-02 16:09:09 +01005978 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005979 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005980 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005981 }
5982
Eric Laurentd4692962014-05-05 18:13:44 -07005983 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005984 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005985 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005986 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005987 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005988 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005989 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005990 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005991
François Gaffie11d30102018-11-02 16:09:09 +01005992 if (profile->supportsDevice(device)) {
5993 profiles.add(profile);
5994 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5995 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005996 }
5997 }
5998 }
5999
Eric Laurent0dd51852019-04-19 18:18:58 -07006000 if (profiles.isEmpty()) {
6001 ALOGW("%s: No input profile available for device %s",
6002 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006003 return BAD_VALUE;
6004 }
6005
6006 // open inputs for matching profiles if needed. Direct inputs are also opened to
6007 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6008 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6009
Eric Laurent1c333e22014-05-20 10:48:17 -07006010 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006011
Eric Laurentd4692962014-05-05 18:13:44 -07006012 // nothing to do if one input is already opened for this profile
6013 size_t input_index;
6014 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6015 desc = mInputs.valueAt(input_index);
6016 if (desc->mProfile == profile) {
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 break;
6021 }
6022 }
6023 if (input_index != mInputs.size()) {
6024 continue;
6025 }
6026
Eric Laurent3974e3b2017-12-07 17:58:43 -08006027 if (!profile->canOpenNewIo()) {
6028 ALOGW("Max Input number %u already opened for this profile %s",
6029 profile->maxOpenCount, profile->getTagName().c_str());
6030 continue;
6031 }
6032
Eric Laurentfe231122017-11-17 17:48:06 -08006033 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006034 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006035 status_t status = desc->open(nullptr,
6036 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006037 AUDIO_SOURCE_MIC,
6038 AUDIO_INPUT_FLAG_NONE,
6039 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006040
Eric Laurentcf2c0212014-07-25 16:20:43 -07006041 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006042 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006043 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006044 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006045 mpClientInterface->setParameters(input, String8(param));
6046 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006047 }
François Gaffie11d30102018-11-02 16:09:09 +01006048 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006049 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006050 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006051 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006052 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006053 }
6054
Eric Laurent0dd51852019-04-19 18:18:58 -07006055 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006056 addInput(input, desc);
6057 }
6058 } // endif input != 0
6059
Eric Laurentcf2c0212014-07-25 16:20:43 -07006060 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006061 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006062 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006063 profiles.removeAt(profile_index);
6064 profile_index--;
6065 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006066 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006067 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006068 }
Eric Laurentd4692962014-05-05 18:13:44 -07006069 ALOGV("checkInputsForDevice(): adding input %d", input);
6070 }
6071 } // end scan profiles
6072
6073 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006074 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006075 return BAD_VALUE;
6076 }
6077 } else {
6078 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006079 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006080 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006081 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006082 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006083 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006084 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006085 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006086 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6087 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006088 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006089 }
6090 }
6091 }
6092 } // end disconnect
6093
6094 return NO_ERROR;
6095}
6096
6097
Eric Laurente0720872014-03-11 09:30:41 -07006098void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006099{
6100 ALOGV("closeOutput(%d)", output);
6101
François Gaffie1c878552018-11-22 16:53:21 +01006102 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6103 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006104 ALOGW("closeOutput() unknown output %d", output);
6105 return;
6106 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006107 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006108 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006109
Eric Laurente552edb2014-03-10 17:42:56 -07006110 // look for duplicated outputs connected to the output being removed.
6111 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006112 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6113 if (dupOutput->isDuplicated() &&
6114 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6115 sp<SwAudioOutputDescriptor> remainingOutput =
6116 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006117 // As all active tracks on duplicated output will be deleted,
6118 // and as they were also referenced on the other output, the reference
6119 // count for their stream type must be adjusted accordingly on
6120 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006121 const bool wasActive = remainingOutput->isActive();
6122 // Note: no-op on the closing output where all clients has already been set inactive
6123 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006124 // stop() will be a no op if the output is still active but is needed in case all
6125 // active streams refcounts where cleared above
6126 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006127 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006128 }
Eric Laurente552edb2014-03-10 17:42:56 -07006129 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6130 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6131
6132 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006133 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006134 }
6135 }
6136
Eric Laurent05b90f82014-08-27 15:32:29 -07006137 nextAudioPortGeneration();
6138
François Gaffie1c878552018-11-22 16:53:21 +01006139 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006140 if (index >= 0) {
6141 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006142 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6143 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006144 mAudioPatches.removeItemsAt(index);
6145 mpClientInterface->onAudioPatchListUpdate();
6146 }
6147
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006148 if (closingOutputWasActive) {
6149 closingOutput->stop();
6150 }
François Gaffie1c878552018-11-22 16:53:21 +01006151 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006152
François Gaffie53615e22015-03-19 09:24:12 +01006153 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006154 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006155 if (closingOutput == mSpatializerOutput) {
6156 mSpatializerOutput.clear();
6157 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006158
6159 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6160 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006161 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006162 bool directOutputOpen = false;
6163 for (size_t i = 0; i < mOutputs.size(); i++) {
6164 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6165 directOutputOpen = true;
6166 break;
6167 }
6168 }
6169 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006170 ALOGV("no direct outputs open, reset MSD patches");
6171 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6172 // how output devices for patching are resolved. Avoid by caching and reusing the
6173 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6174 // devices to patch to. This may be complicated by the fact that devices may become
6175 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006176 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006177 }
6178 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006179}
6180
6181void AudioPolicyManager::closeInput(audio_io_handle_t input)
6182{
6183 ALOGV("closeInput(%d)", input);
6184
6185 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6186 if (inputDesc == NULL) {
6187 ALOGW("closeInput() unknown input %d", input);
6188 return;
6189 }
6190
Eric Laurent6a94d692014-05-20 11:18:06 -07006191 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006192
François Gaffie11d30102018-11-02 16:09:09 +01006193 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006194 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006195 if (index >= 0) {
6196 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006197 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6198 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006199 mAudioPatches.removeItemsAt(index);
6200 mpClientInterface->onAudioPatchListUpdate();
6201 }
6202
Eric Laurentfe231122017-11-17 17:48:06 -08006203 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006204 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006205
François Gaffie11d30102018-11-02 16:09:09 +01006206 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6207 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006208 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006209 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006210 }
Eric Laurente552edb2014-03-10 17:42:56 -07006211}
6212
François Gaffie11d30102018-11-02 16:09:09 +01006213SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6214 const DeviceVector &devices,
6215 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006216{
6217 SortedVector<audio_io_handle_t> outputs;
6218
François Gaffie11d30102018-11-02 16:09:09 +01006219 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006220 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006221 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006222 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006223 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006224 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006225 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006226 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006227 outputs.add(openOutputs.keyAt(i));
6228 }
6229 }
6230 return outputs;
6231}
6232
Mikhail Naganov37977152018-07-11 15:54:44 -07006233void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6234{
6235 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6236 // output is suspended before any tracks are moved to it
6237 checkA2dpSuspend();
6238 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006239 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006240 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006241 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006242 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006243 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6244 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6245 // configuration changes will ultimately be rerouted correctly. We can still avoid
6246 // unnecessary rerouting by caching and reusing the arguments to
6247 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6248 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006249 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006250 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006251 // an event that changed routing likely occurred, inform upper layers
6252 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006253}
6254
François Gaffiec005e562018-11-06 15:04:49 +01006255bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6256 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006257{
François Gaffiec005e562018-11-06 15:04:49 +01006258 return mEngine->getProductStrategyForAttributes(lAttr) ==
6259 mEngine->getProductStrategyForAttributes(rAttr);
6260}
6261
Francois Gaffieff1eb522020-05-06 18:37:04 +02006262void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6263{
6264 for (size_t i = 0; i < mAudioSources.size(); i++) {
6265 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6266 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006267 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006268 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006269 connectAudioSource(sourceDesc);
6270 }
6271 }
6272}
6273
6274void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6275{
6276 for (size_t i = 0; i < mAudioSources.size(); i++) {
6277 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6278 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6279 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6280 disconnectAudioSource(sourceDesc);
6281 }
6282 }
6283}
6284
François Gaffiec005e562018-11-06 15:04:49 +01006285void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6286{
6287 auto psId = mEngine->getProductStrategyForAttributes(attr);
6288
6289 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6290 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006291
François Gaffie11d30102018-11-02 16:09:09 +01006292 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6293 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006294
Eric Laurentc209fe42020-06-05 18:11:23 -07006295 uint32_t maxLatency = 0;
6296 bool invalidate = false;
6297 // take into account dynamic audio policies related changes: if a client is now associated
6298 // to a different policy mix than at creation time, invalidate corresponding stream
6299 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6300 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6301 if (desc->isDuplicated()) {
6302 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006303 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006304 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6305 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6306 continue;
6307 }
6308 sp<AudioPolicyMix> primaryMix;
6309 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
6310 client->flags(), primaryMix, nullptr);
6311 if (status != OK) {
6312 continue;
6313 }
yucliuf4de36d2020-09-14 14:57:56 -07006314 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006315 invalidate = true;
6316 if (desc->isStrategyActive(psId)) {
6317 maxLatency = desc->latency();
6318 }
6319 break;
6320 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006321 }
6322 }
6323
Eric Laurentc209fe42020-06-05 18:11:23 -07006324 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006325 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6326 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006327 for (audio_io_handle_t srcOut : srcOutputs) {
6328 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006329 if (desc == nullptr) continue;
6330
6331 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006332 maxLatency = desc->latency();
6333 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006334
6335 if (invalidate) continue;
6336
6337 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006338 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006339 // a client on a non direct outputs has necessarily a linear PCM format
6340 // so we can call selectOutput() safely
6341 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6342 client->flags(),
6343 client->config().format,
6344 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006345 client->config().sample_rate,
6346 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006347 if (newOutput != srcOut) {
6348 invalidate = true;
6349 break;
6350 }
6351 } else {
6352 sp<IOProfile> profile = getProfileForOutput(newDevices,
6353 client->config().sample_rate,
6354 client->config().format,
6355 client->config().channel_mask,
6356 client->flags(),
6357 true /* directOnly */);
6358 if (profile != desc->mProfile) {
6359 invalidate = true;
6360 break;
6361 }
6362 }
6363 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006364 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006365
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006366 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006367 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006368 std::to_string(srcOutputs[0]).c_str(),
6369 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006370 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006371 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006372 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006373 if (desc == nullptr) continue;
6374
6375 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006376 setStrategyMute(psId, true, desc);
6377 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006378 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006379 }
François Gaffiec005e562018-11-06 15:04:49 +01006380 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006381 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006382 connectAudioSource(source);
6383 }
Eric Laurente552edb2014-03-10 17:42:56 -07006384 }
6385
François Gaffiec005e562018-11-06 15:04:49 +01006386 // Move effects associated to this stream from previous output to new output
6387 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006388 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006389 }
François Gaffiec005e562018-11-06 15:04:49 +01006390 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006391 if (invalidate) {
6392 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6393 mpClientInterface->invalidateStream(stream);
6394 }
jiabin49256852022-03-09 11:21:35 -08006395 for (audio_io_handle_t srcOut : srcOutputs) {
6396 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6397 if (desc == nullptr) continue;
6398
6399 desc->setTracksInvalidatedStatusByStrategy(psId);
6400 }
Eric Laurente552edb2014-03-10 17:42:56 -07006401 }
6402 }
6403}
6404
Eric Laurente0720872014-03-11 09:30:41 -07006405void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006406{
François Gaffiec005e562018-11-06 15:04:49 +01006407 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6408 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6409 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006410 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006411 }
Eric Laurente552edb2014-03-10 17:42:56 -07006412}
6413
Kevin Rocard153f92d2018-12-18 18:33:28 -08006414void AudioPolicyManager::checkSecondaryOutputs() {
6415 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006416 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006417 for (size_t i = 0; i < mOutputs.size(); i++) {
6418 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6419 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006420 sp<AudioPolicyMix> primaryMix;
6421 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006422 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006423 client->flags(), primaryMix, &secondaryMixes);
6424 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6425 for (auto &secondaryMix : secondaryMixes) {
6426 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6427 if (outputDesc != nullptr &&
6428 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6429 secondaryDescs.push_back(outputDesc);
6430 }
6431 }
6432
jiabin10a03f12021-05-07 23:46:28 +00006433 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006434 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006435 } else if (!std::equal(
6436 client->getSecondaryOutputs().begin(),
6437 client->getSecondaryOutputs().end(),
6438 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006439 if (!audio_is_linear_pcm(client->config().format)) {
6440 // If the format is not PCM, the tracks should be invalidated to get correct
6441 // behavior when the secondary output is changed.
6442 streamsToInvalidate.insert(client->stream());
6443 } else {
6444 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6445 std::vector<audio_io_handle_t> secondaryOutputIds;
6446 for (const auto &secondaryDesc: secondaryDescs) {
6447 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6448 weakSecondaryDescs.push_back(secondaryDesc);
6449 }
6450 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6451 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006452 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006453 }
6454 }
6455 }
jiabin10a03f12021-05-07 23:46:28 +00006456 if (!trackSecondaryOutputs.empty()) {
6457 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6458 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006459 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006460 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006461 mpClientInterface->invalidateStream(stream);
6462 }
6463}
6464
Eric Laurent2517af32020-11-25 15:31:27 +01006465bool AudioPolicyManager::isScoRequestedForComm() const {
6466 AudioDeviceTypeAddrVector devices;
6467 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6468 for (const auto &device : devices) {
6469 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6470 return true;
6471 }
6472 }
6473 return false;
6474}
6475
Eric Laurente0720872014-03-11 09:30:41 -07006476void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006477{
François Gaffie53615e22015-03-19 09:24:12 +01006478 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006479 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006480 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006481 return;
6482 }
6483
Eric Laurent3a4311c2014-03-17 12:00:47 -07006484 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006485 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6486 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006487 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006488
6489 // if suspended, restore A2DP output if:
6490 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006491 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006492 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006493 //
Eric Laurentf732e072016-08-03 19:30:28 -07006494 // if not suspended, suspend A2DP output if:
6495 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006496 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006497 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006498 //
6499 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006500 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006501 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006502 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006503 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006504
6505 mpClientInterface->restoreOutput(a2dpOutput);
6506 mA2dpSuspended = false;
6507 }
6508 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006509 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006510 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006511 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006512 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006513
6514 mpClientInterface->suspendOutput(a2dpOutput);
6515 mA2dpSuspended = true;
6516 }
6517 }
6518}
6519
François Gaffie11d30102018-11-02 16:09:09 +01006520DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6521 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006522{
François Gaffie11d30102018-11-02 16:09:09 +01006523 DeviceVector devices;
6524
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006525 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006526 if (index >= 0) {
6527 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006528 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006529 ALOGV("%s device %s forced by patch %d", __func__,
6530 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6531 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006532 }
6533 }
6534
Dean Wheatley514b4312020-06-17 21:45:00 +10006535 // Do not retrieve engine device for outputs through MSD
6536 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6537 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6538 return outputDesc->devices();
6539 }
6540
Eric Laurent97ac8712018-07-27 18:59:02 -07006541 // Honor explicit routing requests only if no client using default routing is active on this
6542 // input: a specific app can not force routing for other apps by setting a preferred device.
6543 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006544 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006545 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006546 if (device != nullptr) {
6547 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006548 }
6549
François Gaffiea807ef92018-11-05 10:44:33 +01006550 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6551 // of setForceUse / Default Bus device here
6552 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6553 if (device != nullptr) {
6554 return DeviceVector(device);
6555 }
6556
François Gaffiec005e562018-11-06 15:04:49 +01006557 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6558 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6559 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306560 auto hasStreamActive = [&](auto stream) {
6561 return hasStream(streams, stream) && isStreamActive(stream, 0);
6562 };
Eric Laurent484e9272018-06-07 17:29:23 -07006563
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306564 auto doGetOutputDevicesForVoice = [&]() {
6565 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006566 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306567 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006568 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6569 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306570 };
6571
6572 // With low-latency playing on speaker, music on WFD, when the first low-latency
6573 // output is stopped, getNewOutputDevices checks for a product strategy
6574 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006575 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306576 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6577 // stream is associated to the output descriptor.
6578 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6579 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6580 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6581 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006582 // Retrieval of devices for voice DL is done on primary output profile, cannot
6583 // check the route (would force modifying configuration file for this profile)
6584 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6585 break;
6586 }
Eric Laurente552edb2014-03-10 17:42:56 -07006587 }
François Gaffiec005e562018-11-06 15:04:49 +01006588 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006589 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006590}
6591
François Gaffie11d30102018-11-02 16:09:09 +01006592sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6593 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006594{
François Gaffie11d30102018-11-02 16:09:09 +01006595 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006596
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006597 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006598 if (index >= 0) {
6599 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006600 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006601 ALOGV("getNewInputDevice() device %s forced by patch %d",
6602 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6603 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006604 }
6605 }
6606
Eric Laurent97ac8712018-07-27 18:59:02 -07006607 // Honor explicit routing requests only if no client using default routing is active on this
6608 // input: a specific app can not force routing for other apps by setting a preferred device.
6609 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006610 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6611 if (device != nullptr) {
6612 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006613 }
6614
Eric Laurentdc95a252018-04-12 12:46:56 -07006615 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006616 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006617 audio_attributes_t attributes;
6618 uid_t uid;
6619 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6620 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006621 attributes = topClient->attributes();
6622 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006623 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006624 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6625 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006626 }
6627
Francois Gaffie716e1432019-01-14 16:58:59 +01006628 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6629 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006630 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006631 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006632 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006633 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006634
Eric Laurente552edb2014-03-10 17:42:56 -07006635 return device;
6636}
6637
Eric Laurent794fde22016-03-11 09:50:45 -08006638bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6639 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006640 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006641}
6642
Dorin Drimusf2196d82022-01-03 12:11:18 +01006643// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006644status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006645 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006646 if (devices == nullptr) {
6647 return BAD_VALUE;
6648 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006649
6650 // Devices are determined in the following precedence:
6651 //
6652 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6653 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6654 //
6655 // If no such dynamic policy then
6656 // 2) Devices containing an active client using setPreferredDevice
6657 // with same strategy as the attributes.
6658 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6659 //
6660 // If no corresponding active client with setPreferredDevice then
6661 // 3) Devices associated with the strategy determined by the attributes
6662 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6663 //
6664 // See related getOutputForAttrInt().
6665
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006666 // check dynamic policies but only for primary descriptors (secondary not used for audible
6667 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006668 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006669 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Andy Hung6d23c0f2022-02-16 09:37:15 -08006670 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr /* secondaryMixes */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006671 if (status != OK) {
6672 return status;
6673 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006674
6675 DeviceVector curDevices;
6676 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6677 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6678 // as they are unaffected by device/stream volume
6679 // (per SwAudioOutputDescriptor::isFixedVolume()).
6680 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6681 ) {
6682 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6683 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6684 curDevices.add(deviceDesc);
6685 } else {
6686 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6687 // which selects setPreferredDevice if active. This means forVolume call
6688 // will take an active setPreferredDevice, if such exists.
6689
6690 curDevices = mEngine->getOutputDevicesForAttributes(
6691 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006692 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006693
6694 if (forVolume) {
6695 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6696 // for single volume control in AudioService (such relationship should exist if
6697 // SPEAKER_SAFE is present).
6698 //
6699 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6700 DeviceVector speakerSafeDevices =
6701 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6702 if (!speakerSafeDevices.isEmpty()) {
6703 curDevices.merge(
6704 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6705 curDevices.remove(speakerSafeDevices);
6706 }
6707 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006708 for (const auto& device : curDevices) {
6709 devices->push_back(device->getDeviceTypeAddr());
6710 }
6711 return NO_ERROR;
6712}
6713
Eric Laurente0720872014-03-11 09:30:41 -07006714void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006715 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006716 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006717 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006718 updateDevicesAndOutputs();
6719 break;
6720 default:
6721 break;
6722 }
6723}
6724
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006725uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006726
6727 // skip beacon mute management if a dedicated TTS output is available
6728 if (mTtsOutputAvailable) {
6729 return 0;
6730 }
6731
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006732 switch(event) {
6733 case STARTING_OUTPUT:
6734 mBeaconMuteRefCount++;
6735 break;
6736 case STOPPING_OUTPUT:
6737 if (mBeaconMuteRefCount > 0) {
6738 mBeaconMuteRefCount--;
6739 }
6740 break;
6741 case STARTING_BEACON:
6742 mBeaconPlayingRefCount++;
6743 break;
6744 case STOPPING_BEACON:
6745 if (mBeaconPlayingRefCount > 0) {
6746 mBeaconPlayingRefCount--;
6747 }
6748 break;
6749 }
6750
6751 if (mBeaconMuteRefCount > 0) {
6752 // any playback causes beacon to be muted
6753 return setBeaconMute(true);
6754 } else {
6755 // no other playback: unmute when beacon starts playing, mute when it stops
6756 return setBeaconMute(mBeaconPlayingRefCount == 0);
6757 }
6758}
6759
6760uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6761 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6762 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6763 // keep track of muted state to avoid repeating mute/unmute operations
6764 if (mBeaconMuted != mute) {
6765 // mute/unmute AUDIO_STREAM_TTS on all outputs
6766 ALOGV("\t muting %d", mute);
6767 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006768 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6769 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6770 ALOGV("\t no tts volume source available");
6771 return 0;
6772 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006773 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006774 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006775 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006776 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006777 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006778 maxLatency = latency;
6779 }
6780 }
6781 mBeaconMuted = mute;
6782 return maxLatency;
6783 }
6784 return 0;
6785}
6786
Eric Laurente0720872014-03-11 09:30:41 -07006787void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006788{
François Gaffiec005e562018-11-06 15:04:49 +01006789 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006790 mPreviousOutputs = mOutputs;
6791}
6792
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006793uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006794 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006795 uint32_t delayMs)
6796{
6797 // mute/unmute strategies using an incompatible device combination
6798 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6799 // if unmuting, unmute only after the specified delay
6800 if (outputDesc->isDuplicated()) {
6801 return 0;
6802 }
6803
6804 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006805 DeviceVector devices = outputDesc->devices();
6806 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006807
François Gaffiec005e562018-11-06 15:04:49 +01006808 auto productStrategies = mEngine->getOrderedProductStrategies();
6809 for (const auto &productStrategy : productStrategies) {
6810 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6811 DeviceVector curDevices =
6812 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6813 curDevices = curDevices.filter(outputDesc->supportedDevices());
6814 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006815 bool doMute = false;
6816
François Gaffiec005e562018-11-06 15:04:49 +01006817 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006818 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006819 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6820 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006821 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006822 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006823 }
Eric Laurent99401132014-05-07 19:48:15 -07006824 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006825 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006826 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006827 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006828 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006829 continue;
6830 }
François Gaffiec005e562018-11-06 15:04:49 +01006831 ALOGVV("%s() %s (curDevice %s)", __func__,
6832 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6833 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6834 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006835 if (mute) {
6836 // FIXME: should not need to double latency if volume could be applied
6837 // immediately by the audioflinger mixer. We must account for the delay
6838 // between now and the next time the audioflinger thread for this output
6839 // will process a buffer (which corresponds to one buffer size,
6840 // usually 1/2 or 1/4 of the latency).
6841 if (muteWaitMs < desc->latency() * 2) {
6842 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006843 }
6844 }
6845 }
6846 }
6847 }
6848 }
6849
Eric Laurent99401132014-05-07 19:48:15 -07006850 // temporary mute output if device selection changes to avoid volume bursts due to
6851 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006852 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006853 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006854
Eric Laurentdc462862016-07-19 12:29:53 -07006855 if (muteWaitMs < tempMuteWaitMs) {
6856 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006857 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006858
6859 // If recommended duration is defined, replace temporary mute duration to avoid
6860 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6861 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6862 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6863 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6864 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6865
François Gaffieaaac0fd2018-11-22 17:56:39 +01006866 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6867 // make sure that we do not start the temporary mute period too early in case of
6868 // delayed device change
6869 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6870 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006871 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006872 }
6873 }
6874
Eric Laurente552edb2014-03-10 17:42:56 -07006875 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6876 if (muteWaitMs > delayMs) {
6877 muteWaitMs -= delayMs;
6878 usleep(muteWaitMs * 1000);
6879 return muteWaitMs;
6880 }
6881 return 0;
6882}
6883
François Gaffie11d30102018-11-02 16:09:09 +01006884uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6885 const DeviceVector &devices,
6886 bool force,
6887 int delayMs,
6888 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006889 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006890{
François Gaffie11d30102018-11-02 16:09:09 +01006891 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006892 uint32_t muteWaitMs;
6893
6894 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006895 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6896 nullptr /* patchHandle */, requiresMuteCheck);
6897 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6898 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006899 return muteWaitMs;
6900 }
Eric Laurente552edb2014-03-10 17:42:56 -07006901
6902 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006903 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006904 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006905 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006906
François Gaffie11d30102018-11-02 16:09:09 +01006907 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6908
6909 if (!filteredDevices.isEmpty()) {
6910 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006911 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006912
6913 // if the outputs are not materially active, there is no need to mute.
6914 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006915 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006916 } else {
6917 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6918 muteWaitMs = 0;
6919 }
Eric Laurente552edb2014-03-10 17:42:56 -07006920
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006921 bool outputRouted = outputDesc->isRouted();
6922
Eric Laurent79ea9582020-06-11 18:49:24 -07006923 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6924 // output profile or if new device is not supported AND previous device(s) is(are) still
6925 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006926 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006927 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6928 // restore previous device after evaluating strategy mute state
6929 outputDesc->setDevices(prevDevices);
6930 return muteWaitMs;
6931 }
6932
Eric Laurente552edb2014-03-10 17:42:56 -07006933 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006934 // the requested device is AUDIO_DEVICE_NONE
6935 // OR the requested device is the same as current device
6936 // AND force is not specified
6937 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006938 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006939 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01006940 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6941 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006942 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6943 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6944 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6945 }
Eric Laurente552edb2014-03-10 17:42:56 -07006946 return muteWaitMs;
6947 }
6948
François Gaffie11d30102018-11-02 16:09:09 +01006949 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006950
Eric Laurente552edb2014-03-10 17:42:56 -07006951 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006952 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006953 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006954 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006955 PatchBuilder patchBuilder;
6956 patchBuilder.addSource(outputDesc);
6957 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6958 for (const auto &filteredDevice : filteredDevices) {
6959 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006960 }
6961
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006962 // Add half reported latency to delayMs when muteWaitMs is null in order
6963 // to avoid disordered sequence of muting volume and changing devices.
6964 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6965 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006966 }
Eric Laurente552edb2014-03-10 17:42:56 -07006967
6968 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006969 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006970
6971 return muteWaitMs;
6972}
6973
Eric Laurentc75307b2015-03-17 15:29:32 -07006974status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006975 int delayMs,
6976 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006977{
Eric Laurent6a94d692014-05-20 11:18:06 -07006978 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006979 if (patchHandle == nullptr && !outputDesc->isRouted()) {
6980 return INVALID_OPERATION;
6981 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006982 if (patchHandle) {
6983 index = mAudioPatches.indexOfKey(*patchHandle);
6984 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006985 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006986 }
6987 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006988 return INVALID_OPERATION;
6989 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006990 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006991 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006992 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006993 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006994 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006995 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006996 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006997 return status;
6998}
6999
7000status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007001 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007002 bool force,
7003 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007004{
7005 status_t status = NO_ERROR;
7006
Eric Laurent1f2f2232014-06-02 12:01:23 -07007007 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007008 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7009 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007010
François Gaffie11d30102018-11-02 16:09:09 +01007011 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007012 PatchBuilder patchBuilder;
7013 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007014 // AUDIO_SOURCE_HOTWORD is for internal use only:
7015 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007016 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7017 auto result = usecase;
7018 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7019 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7020 }
7021 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007022 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007023 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007024 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007025 }
7026 }
7027 return status;
7028}
7029
Eric Laurent6a94d692014-05-20 11:18:06 -07007030status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7031 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007032{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007033 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007034 ssize_t index;
7035 if (patchHandle) {
7036 index = mAudioPatches.indexOfKey(*patchHandle);
7037 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007038 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007039 }
7040 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007041 return INVALID_OPERATION;
7042 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007043 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007044 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007045 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007046 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007047 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007048 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007049 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007050 return status;
7051}
7052
François Gaffie11d30102018-11-02 16:09:09 +01007053sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007054 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007055 audio_format_t& format,
7056 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007057 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007058{
7059 // Choose an input profile based on the requested capture parameters: select the first available
7060 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007061 //
7062 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7063 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007064
Glenn Kasten730b9262018-03-29 15:01:26 -07007065 sp<IOProfile> firstInexact;
7066 uint32_t updatedSamplingRate = 0;
7067 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7068 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007069 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007070 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007071 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007072 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007073 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007074 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007075 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007076 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007077 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007078 &channelMask /*updatedChannelMask*/,
7079 // FIXME ugly cast
7080 (audio_output_flags_t) flags,
7081 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007082 return profile;
7083 }
François Gaffie11d30102018-11-02 16:09:09 +01007084 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007085 samplingRate,
7086 &updatedSamplingRate,
7087 format,
7088 &updatedFormat,
7089 channelMask,
7090 &updatedChannelMask,
7091 // FIXME ugly cast
7092 (audio_output_flags_t) flags,
7093 false /*exactMatchRequiredForInputFlags*/)) {
7094 firstInexact = profile;
7095 }
7096
Eric Laurente552edb2014-03-10 17:42:56 -07007097 }
7098 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007099 if (firstInexact != nullptr) {
7100 samplingRate = updatedSamplingRate;
7101 format = updatedFormat;
7102 channelMask = updatedChannelMask;
7103 return firstInexact;
7104 }
Eric Laurente552edb2014-03-10 17:42:56 -07007105 return NULL;
7106}
7107
François Gaffieaaac0fd2018-11-22 17:56:39 +01007108float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7109 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007110 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007111 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007112{
jiabin9a3361e2019-10-01 09:38:30 -07007113 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007114
7115 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7116 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7117 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7118 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007119 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7120 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7121 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7122 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7123 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007124
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007125 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007126 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7127 mOutputs.isActive(ringVolumeSrc, 0)) {
7128 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007129 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007130 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007131 }
7132
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007133 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007134 if ((volumeSource != callVolumeSrc && (isInCall() ||
7135 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007136 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007137 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7138 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007139 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7140 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7141 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007142 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007143 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007144 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007145 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007146 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007147 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007148 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7149 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7150 // programmatically muted.
7151 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7152 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7153 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007154 bool exemptFromCapping =
7155 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7156 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007157 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7158 volumeSource, volumeDb);
7159 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007160 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7161 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7162 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007163 }
7164 }
Eric Laurente552edb2014-03-10 17:42:56 -07007165 // if a headset is connected, apply the following rules to ring tones and notifications
7166 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007167 // - always attenuate notifications volume by 6dB
7168 // - attenuate ring tones volume by 6dB unless music is not playing and
7169 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007170 // - if music is playing, always limit the volume to current music volume,
7171 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007172 if (!Intersection(deviceTypes,
7173 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7174 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007175 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7176 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007177 ((volumeSource == alarmVolumeSrc ||
7178 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007179 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7180 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7181 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007182 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7183 curves.canBeMuted()) {
7184
Eric Laurente552edb2014-03-10 17:42:56 -07007185 // when the phone is ringing we must consider that music could have been paused just before
7186 // by the music application and behave as if music was active if the last music track was
7187 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007188 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007189 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007190 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007191 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007192 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7193 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007194 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007195 float musicVolDb = computeVolume(musicCurves,
7196 musicVolumeSrc,
7197 musicCurves.getVolumeIndex(musicDevice),
7198 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007199 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7200 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7201 if (volumeDb > minVolDb) {
7202 volumeDb = minVolDb;
7203 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007204 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007205 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7206 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7207 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007208 // on A2DP, also ensure notification volume is not too low compared to media when
7209 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007210 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007211 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007212 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7213 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007214 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7215 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007216 }
7217 }
jiabin9a3361e2019-10-01 09:38:30 -07007218 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007219 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007220 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007221 }
7222 }
7223
François Gaffie43c73442018-11-08 08:21:55 +01007224 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007225}
7226
Eric Laurent3839bc02018-07-10 18:33:34 -07007227int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007228 VolumeSource fromVolumeSource,
7229 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007230{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007231 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007232 return srcIndex;
7233 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007234 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7235 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007236 float minSrc = (float)srcCurves.getVolumeIndexMin();
7237 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7238 float minDst = (float)dstCurves.getVolumeIndexMin();
7239 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007240
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007241 // preserve mute request or correct range
7242 if (srcIndex < minSrc) {
7243 if (srcIndex == 0) {
7244 return 0;
7245 }
7246 srcIndex = minSrc;
7247 } else if (srcIndex > maxSrc) {
7248 srcIndex = maxSrc;
7249 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007250 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7251}
7252
François Gaffieaaac0fd2018-11-22 17:56:39 +01007253status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7254 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007255 int index,
7256 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007257 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007258 int delayMs,
7259 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007260{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007261 // do not change actual attributes volume if the attributes is muted
7262 if (outputDesc->isMuted(volumeSource)) {
7263 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7264 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007265 return NO_ERROR;
7266 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007267 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7268 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7269 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7270 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007271
Eric Laurent2517af32020-11-25 15:31:27 +01007272 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07007273 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007274 // if sco and call follow same curves, bypass forceUseForComm
7275 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007276 ((isVoiceVolSrc && isScoRequested) ||
7277 (isBtScoVolSrc && !isScoRequested))) {
7278 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
7279 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07007280 // Do not return an error here as AudioService will always set both voice call
7281 // and bluetooth SCO volumes due to stream aliasing.
7282 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007283 }
jiabin9a3361e2019-10-01 09:38:30 -07007284 if (deviceTypes.empty()) {
7285 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007286 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007287
jiabin9a3361e2019-10-01 09:38:30 -07007288 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7289 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007290 // Force VoIP volume to max for bluetooth SCO device except if muted
7291 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007292 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007293 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007294 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007295 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007296 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007297 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007298
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007299 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007300 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007301 // 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 +01007302 if (isVoiceVolSrc) {
7303 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007304 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007305 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007306 }
Eric Laurent18fba842016-03-31 14:41:26 -07007307 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007308 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7309 mLastVoiceVolume = voiceVolume;
7310 }
7311 }
Eric Laurente552edb2014-03-10 17:42:56 -07007312 return NO_ERROR;
7313}
7314
Eric Laurentc75307b2015-03-17 15:29:32 -07007315void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007316 const DeviceTypeSet& deviceTypes,
7317 int delayMs,
7318 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007319{
jiabincd510522020-01-22 09:40:55 -08007320 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007321 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7322 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7323 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007324 curves.getVolumeIndex(deviceTypes),
7325 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007326 }
7327}
7328
François Gaffiec005e562018-11-06 15:04:49 +01007329void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7330 bool on,
7331 const sp<AudioOutputDescriptor>& outputDesc,
7332 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007333 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007334{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007335 std::vector<VolumeSource> sourcesToMute;
7336 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7337 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7338 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007339 VolumeSource source = toVolumeSource(attributes, false);
7340 if ((source != VOLUME_SOURCE_NONE) &&
7341 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7342 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007343 sourcesToMute.push_back(source);
7344 }
Eric Laurente552edb2014-03-10 17:42:56 -07007345 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007346 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007347 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007348 }
7349
Eric Laurente552edb2014-03-10 17:42:56 -07007350}
7351
François Gaffieaaac0fd2018-11-22 17:56:39 +01007352void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7353 bool on,
7354 const sp<AudioOutputDescriptor>& outputDesc,
7355 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007356 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007357{
jiabin9a3361e2019-10-01 09:38:30 -07007358 if (deviceTypes.empty()) {
7359 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007360 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007361 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007362 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007363 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007364 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007365 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007366 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7367 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007368 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007369 }
7370 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007371 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7372 // ignored
7373 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007374 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007375 if (!outputDesc->isMuted(volumeSource)) {
7376 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007377 return;
7378 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007379 if (outputDesc->decMuteCount(volumeSource) == 0) {
7380 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007381 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007382 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007383 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007384 delayMs);
7385 }
7386 }
7387}
7388
François Gaffie53615e22015-03-19 09:24:12 +01007389bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7390{
François Gaffiec005e562018-11-06 15:04:49 +01007391 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007392 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7393 return true;
7394 }
7395
7396 // has known usage?
7397 switch (paa->usage) {
7398 case AUDIO_USAGE_UNKNOWN:
7399 case AUDIO_USAGE_MEDIA:
7400 case AUDIO_USAGE_VOICE_COMMUNICATION:
7401 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7402 case AUDIO_USAGE_ALARM:
7403 case AUDIO_USAGE_NOTIFICATION:
7404 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7405 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7406 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7407 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7408 case AUDIO_USAGE_NOTIFICATION_EVENT:
7409 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7410 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7411 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7412 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007413 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007414 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007415 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007416 case AUDIO_USAGE_EMERGENCY:
7417 case AUDIO_USAGE_SAFETY:
7418 case AUDIO_USAGE_VEHICLE_STATUS:
7419 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007420 break;
7421 default:
7422 return false;
7423 }
7424 return true;
7425}
7426
François Gaffie2110e042015-03-24 08:41:51 +01007427audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7428{
7429 return mEngine->getForceUse(usage);
7430}
7431
Eric Laurent96d1dda2022-03-14 17:14:19 +01007432bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007433 return isStateInCall(mEngine->getPhoneState());
7434}
7435
Eric Laurent96d1dda2022-03-14 17:14:19 +01007436bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007437 return is_state_in_call(state);
7438}
7439
Eric Laurent74b71512019-11-06 17:21:57 -08007440bool AudioPolicyManager::isCallAudioAccessible()
7441{
7442 audio_mode_t mode = mEngine->getPhoneState();
7443 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007444 || (mode == AUDIO_MODE_CALL_SCREEN)
7445 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007446}
7447
Eric Laurentd60560a2015-04-10 11:31:20 -07007448void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7449{
7450 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007451 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007452 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007453 sourceDesc->sinkDevice()->equals(deviceDesc))
7454 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007455 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007456 }
7457 }
7458
7459 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7460 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7461 bool release = false;
7462 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7463 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7464 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7465 source->ext.device.type == deviceDesc->type()) {
7466 release = true;
7467 }
7468 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007469 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007470 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7471 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7472 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007473 sink->ext.device.type == deviceDesc->type() &&
7474 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7475 || strncmp(sink->ext.device.address, address,
7476 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007477 release = true;
7478 }
7479 }
7480 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007481 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7482 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007483 }
7484 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007485
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007486 mInputs.clearSessionRoutesForDevice(deviceDesc);
7487
Francois Gaffie716e1432019-01-14 16:58:59 +01007488 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007489}
7490
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007491void AudioPolicyManager::modifySurroundFormats(
7492 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007493 std::unordered_set<audio_format_t> enforcedSurround(
7494 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007495 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7496 for (const auto& pair : mConfig.getSurroundFormats()) {
7497 allSurround.insert(pair.first);
7498 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7499 }
Phil Burk09bc4612016-02-24 15:58:15 -08007500
7501 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7502 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007503 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007504 // This is the resulting set of formats depending on the surround mode:
7505 // 'all surround' = allSurround
7506 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7507 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7508 // 'manual surround' = mManualSurroundFormats
7509 // AUTO: formats v 'enforced surround'
7510 // ALWAYS: formats v 'all surround' v 'enforced surround'
7511 // NEVER: formats ^ 'non-surround'
7512 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007513
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007514 std::unordered_set<audio_format_t> formatSet;
7515 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7516 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007517 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007518 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007519 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007520 formatSet.insert(*formatIter);
7521 }
7522 }
7523 } else {
7524 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7525 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007526 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007527
jiabin81772902018-04-02 17:52:27 -07007528 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007529 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007530 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7531 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7532 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007533 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007534 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7535 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7536 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007537 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007538 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007539 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007540 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007541 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007542 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007543}
7544
jiabin06e4bab2019-07-29 10:13:34 -07007545void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7546 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007547 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7548 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7549
7550 // If NEVER, then remove support for channelMasks > stereo.
7551 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007552 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7553 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007554 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007555 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007556 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007557 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007558 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007559 }
7560 }
jiabin81772902018-04-02 17:52:27 -07007561 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7562 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7563 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007564 bool supports5dot1 = false;
7565 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007566 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007567 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7568 supports5dot1 = true;
7569 break;
7570 }
7571 }
7572 // If not then add 5.1 support.
7573 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007574 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007575 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007576 }
Phil Burk09bc4612016-02-24 15:58:15 -08007577 }
7578}
7579
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007580void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007581 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007582 AudioProfileVector &profiles)
7583{
7584 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007585 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007586
François Gaffie112b0af2015-11-19 16:13:25 +01007587 // Format MUST be checked first to update the list of AudioProfile
7588 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007589 reply = mpClientInterface->getParameters(
7590 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007591 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007592 AudioParameter repliedParameters(reply);
7593 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007594 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007595 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7596 return;
7597 }
Phil Burk09bc4612016-02-24 15:58:15 -08007598 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007599 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007600 if (device == AUDIO_DEVICE_OUT_HDMI
7601 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007602 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007603 }
jiabin3e277cc2019-09-10 14:27:34 -07007604 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007605 }
François Gaffie112b0af2015-11-19 16:13:25 +01007606
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007607 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007608 ChannelMaskSet channelMasks;
7609 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007610 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007611 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007612
7613 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007614 reply = mpClientInterface->getParameters(
7615 ioHandle,
7616 requestedParameters.toString() + ";" +
7617 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007618 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007619 AudioParameter repliedParameters(reply);
7620 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007621 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007622 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007623 }
7624 }
7625 if (profiles.hasDynamicChannelsFor(format)) {
7626 reply = mpClientInterface->getParameters(ioHandle,
7627 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007628 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007629 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007630 AudioParameter repliedParameters(reply);
7631 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007632 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007633 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007634 if (device == AUDIO_DEVICE_OUT_HDMI
7635 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007636 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007637 }
François Gaffie112b0af2015-11-19 16:13:25 +01007638 }
7639 }
jiabin3e277cc2019-09-10 14:27:34 -07007640 addDynamicAudioProfileAndSort(
7641 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007642 }
7643}
Eric Laurentd60560a2015-04-10 11:31:20 -07007644
Mikhail Naganovdc769682018-05-04 15:34:08 -07007645status_t AudioPolicyManager::installPatch(const char *caller,
7646 audio_patch_handle_t *patchHandle,
7647 AudioIODescriptorInterface *ioDescriptor,
7648 const struct audio_patch *patch,
7649 int delayMs)
7650{
7651 ssize_t index = mAudioPatches.indexOfKey(
7652 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7653 *patchHandle : ioDescriptor->getPatchHandle());
7654 sp<AudioPatch> patchDesc;
7655 status_t status = installPatch(
7656 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7657 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007658 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007659 }
7660 return status;
7661}
7662
7663status_t AudioPolicyManager::installPatch(const char *caller,
7664 ssize_t index,
7665 audio_patch_handle_t *patchHandle,
7666 const struct audio_patch *patch,
7667 int delayMs,
7668 uid_t uid,
7669 sp<AudioPatch> *patchDescPtr)
7670{
7671 sp<AudioPatch> patchDesc;
7672 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7673 if (index >= 0) {
7674 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007675 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007676 }
7677
7678 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7679 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7680 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7681 if (status == NO_ERROR) {
7682 if (index < 0) {
7683 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007684 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007685 } else {
7686 patchDesc->mPatch = *patch;
7687 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007688 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007689 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007690 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007691 }
7692 nextAudioPortGeneration();
7693 mpClientInterface->onAudioPatchListUpdate();
7694 }
7695 if (patchDescPtr) *patchDescPtr = patchDesc;
7696 return status;
7697}
7698
jiabinbce0c1d2020-10-05 11:20:18 -07007699bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7700{
7701 const TrackClientVector activeClients = output->getActiveClients();
7702 if (activeClients.empty()) {
7703 return true;
7704 }
7705 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7706 if (index < 0) {
7707 ALOGE("%s, no audio patch found while there are active clients on output %d",
7708 __func__, output->getId());
7709 return false;
7710 }
7711 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7712 DeviceVector routedDevices;
7713 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7714 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7715 patchDesc->mPatch.sinks[i].id);
7716 if (device == nullptr) {
7717 ALOGE("%s, no audio device found with id(%d)",
7718 __func__, patchDesc->mPatch.sinks[i].id);
7719 return false;
7720 }
7721 routedDevices.add(device);
7722 }
7723 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007724 if (client->isInvalid()) {
7725 // No need to take care about invalidated clients.
7726 continue;
7727 }
jiabinbce0c1d2020-10-05 11:20:18 -07007728 sp<DeviceDescriptor> preferredDevice =
7729 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7730 if (mEngine->getOutputDevicesForAttributes(
7731 client->attributes(), preferredDevice, false) == routedDevices) {
7732 return false;
7733 }
7734 }
7735 return true;
7736}
7737
7738sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007739 const sp<IOProfile>& profile, const DeviceVector& devices,
7740 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007741{
7742 for (const auto& device : devices) {
7743 // TODO: This should be checking if the profile supports the device combo.
7744 if (!profile->supportsDevice(device)) {
7745 return nullptr;
7746 }
7747 }
7748 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7749 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007750 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007751 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7752 if (status != NO_ERROR) {
7753 return nullptr;
7754 }
7755
7756 // Here is where the out_set_parameters() for card & device gets called
7757 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7758 const audio_devices_t deviceType = device->type();
7759 const String8 &address = String8(device->address().c_str());
7760 if (!address.isEmpty()) {
7761 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7762 mpClientInterface->setParameters(output, String8(param));
7763 free(param);
7764 }
7765 updateAudioProfiles(device, output, profile->getAudioProfiles());
7766 if (!profile->hasValidAudioProfile()) {
7767 ALOGW("%s() missing param", __func__);
7768 desc->close();
7769 return nullptr;
7770 } else if (profile->hasDynamicAudioProfile()) {
7771 desc->close();
7772 output = AUDIO_IO_HANDLE_NONE;
7773 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7774 profile->pickAudioProfile(
7775 config.sample_rate, config.channel_mask, config.format);
7776 config.offload_info.sample_rate = config.sample_rate;
7777 config.offload_info.channel_mask = config.channel_mask;
7778 config.offload_info.format = config.format;
7779
Eric Laurentb4f42a92022-01-17 17:37:31 +01007780 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007781 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7782 if (status != NO_ERROR) {
7783 return nullptr;
7784 }
7785 }
7786
7787 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007788
jiabinbce0c1d2020-10-05 11:20:18 -07007789 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7790 sp<AudioPolicyMix> policyMix;
7791 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7792 policyMix->setOutput(desc);
7793 desc->mPolicyMix = policyMix;
7794 } else {
7795 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7796 address.string());
7797 }
7798
Eric Laurentb4f42a92022-01-17 17:37:31 +01007799 } else if (hasPrimaryOutput() && profile->getModule()
7800 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7801 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7802 // no duplicated output for:
7803 // - direct outputs
7804 // - outputs used by dynamic policy mixes
7805 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007806 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7807
7808 //TODO: configure audio effect output stage here
7809
7810 // open a duplicating output thread for the new output and the primary output
7811 sp<SwAudioOutputDescriptor> dupOutputDesc =
7812 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7813 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7814 if (status == NO_ERROR) {
7815 // add duplicated output descriptor
7816 addOutput(duplicatedOutput, dupOutputDesc);
7817 } else {
7818 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7819 mPrimaryOutput->mIoHandle, output);
7820 desc->close();
7821 removeOutput(output);
7822 nextAudioPortGeneration();
7823 return nullptr;
7824 }
7825 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007826 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7827 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7828 mPrimaryOutput = desc;
7829 }
jiabinbce0c1d2020-10-05 11:20:18 -07007830 return desc;
7831}
7832
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007833} // namespace android