blob: 550c19463d13898c97b5c3439ca866b9387e6492 [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 Laurente191d1b2022-04-15 11:59:25 +0200293 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200294 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
295 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200296 (desc->mDirectOpenCount == 0))
297 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
298 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200299 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 closeOutput(output);
301 }
Eric Laurente552edb2014-03-10 17:42:56 -0700302 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700303 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
304 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700305 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700306 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800307 };
308
309 if (doCheckForDeviceAndOutputChanges) {
310 checkForDeviceAndOutputChanges(checkCloseOutputs);
311 } else {
312 checkCloseOutputs();
313 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100314 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700315 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100316 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700317 const DeviceVector activeMediaDevices =
318 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700319 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700320 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530321 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
322 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100323 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 // do not force device change on duplicated output because if device is 0, it will
325 // also force a device 0 for the two outputs it is duplicated to which may override
326 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100327 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100328 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700329 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700330 // always force when disconnecting (a non-duplicated device)
331 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100332 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 }
jiabinbce0c1d2020-10-05 11:20:18 -0700334 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000335 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700336 desc->supportsDevicesForPlayback(activeMediaDevices)) {
337 // Reopen the output to query the dynamic profiles when there is not active
338 // clients or all active clients will be rerouted. Otherwise, set the flag
339 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
340 // can be reopened to query dynamic profiles when all clients are inactive.
341 if (areAllActiveTracksRerouted(desc)) {
342 outputsToReopen.push_back(mOutputs.keyAt(i));
343 } else {
344 desc->mPendingReopenToQueryProfiles = true;
345 }
346 }
347 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
348 // Clear the flag that previously set for re-querying profiles.
349 desc->mPendingReopenToQueryProfiles = false;
350 }
351 }
352 for (const auto& output : outputsToReopen) {
353 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
354 closeOutput(output);
355 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700356 }
357
Eric Laurentd60560a2015-04-10 11:31:20 -0700358 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100359 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700360 }
361
Eric Laurent96d1dda2022-03-14 17:14:19 +0100362 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
363
Eric Laurent72aa32f2014-05-30 18:51:48 -0700364 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700365 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700366 } // end if is output device
367
Eric Laurente552edb2014-03-10 17:42:56 -0700368 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700369 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100370 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700371 switch (state)
372 {
373 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700374 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700375 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100376 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700377 return INVALID_OPERATION;
378 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700379
380 if (mAvailableInputDevices.add(device) < 0) {
381 return NO_MEMORY;
382 }
383
François Gaffie44481e72016-04-20 07:49:57 +0200384 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
385 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100386 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200387
Eric Laurent0dd51852019-04-19 18:18:58 -0700388 if (checkInputsForDevice(device, state) != NO_ERROR) {
389 mAvailableInputDevices.remove(device);
390
François Gaffie11d30102018-11-02 16:09:09 +0100391 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100392
393 mHwModules.cleanUpForDevice(device);
394
Eric Laurentd4692962014-05-05 18:13:44 -0700395 return INVALID_OPERATION;
396 }
397
Eric Laurentd4692962014-05-05 18:13:44 -0700398 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700399
400 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700401 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700402 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100403 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700404 return INVALID_OPERATION;
405 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700406
François Gaffie11d30102018-11-02 16:09:09 +0100407 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700408
409 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100410 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700411
François Gaffie11d30102018-11-02 16:09:09 +0100412 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700413
414 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100415
416 // remove device from mReportedFormatsMap cache
417 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700418 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700419
420 default:
François Gaffie11d30102018-11-02 16:09:09 +0100421 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700422 return BAD_VALUE;
423 }
424
Eric Laurent736a1022019-03-27 18:28:46 -0700425 // Propagate device availability to Engine
426 setEngineDeviceConnectionState(device, state);
427
Eric Laurent0dd51852019-04-19 18:18:58 -0700428 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700429 // As the input device list can impact the output device selection, update
430 // getDeviceForStrategy() cache
431 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700432
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100433 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200434 // Reconnect Audio Source
435 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
436 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
437 checkAudioSourceForAttributes(attributes);
438 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700439 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100440 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700441 }
442
Eric Laurentb52c1522014-05-20 11:27:36 -0700443 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700444 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700445 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700446
François Gaffie11d30102018-11-02 16:09:09 +0100447 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return BAD_VALUE;
449}
450
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100451status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
452 const char* device_name,
453 media::AudioPort* aidlPort) {
454 DeviceDescriptorBase devDescr(device, device_address);
455 devDescr.setName(device_name);
456 return devDescr.writeToParcelable(aidlPort);
457}
458
Eric Laurent736a1022019-03-27 18:28:46 -0700459void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
460 audio_policy_dev_state_t state) {
461
462 // the Engine does not have to know about remote submix devices used by dynamic audio policies
463 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
464 return;
465 }
466 mEngine->setDeviceConnectionState(device, state);
467}
468
469
Eric Laurente0720872014-03-11 09:30:41 -0700470audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100471 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700472{
Eric Laurent634b7142016-04-20 13:48:02 -0700473 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800474 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
475 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700476 (strlen(device_address) != 0)/*matchAddress*/);
477
478 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100479 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700480 device, device_address);
481 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
482 }
François Gaffie53615e22015-03-19 09:24:12 +0100483
Eric Laurent3a4311c2014-03-17 12:00:47 -0700484 DeviceVector *deviceVector;
485
Eric Laurente552edb2014-03-10 17:42:56 -0700486 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700487 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700488 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700489 deviceVector = &mAvailableInputDevices;
490 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100491 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700492 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700493 }
Eric Laurent634b7142016-04-20 13:48:02 -0700494
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800495 return (deviceVector->getDevice(
496 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700497 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800498}
499
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800500status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
501 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800502 const char *device_name,
503 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504{
505 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700506 String8 reply;
507 AudioParameter param;
508 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800509
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
511 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800512
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800513 // connect/disconnect only 1 device at a time
514 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
515
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700517 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519 // Nothing to do: device is not connected
520 return NO_ERROR;
521 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700524 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 // configure codecs.
526 // Handle two specific cases by sending a set parameter to
527 // configure A2DP codecs. No need to toggle device state.
528 // Case 1: A2DP active device switches from primary to primary
529 // module
530 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200531 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700532 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
534 if (availablePrimaryOutputDevices().contains(devDesc) &&
535 (module != 0 && module->getHandle() == primaryHandle)) {
536 reply = mpClientInterface->getParameters(
537 AUDIO_IO_HANDLE_NONE,
538 String8(AudioParameter::keyReconfigA2dpSupported));
539 AudioParameter repliedParameters(reply);
540 repliedParameters.getInt(
541 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
542 if (isReconfigA2dpSupported) {
543 const String8 key(AudioParameter::keyReconfigA2dp);
544 param.add(key, String8("true"));
545 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
546 devDesc->setEncodedFormat(encodedFormat);
547 return NO_ERROR;
548 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700549 }
550 }
cnx421bd2dcc42020-07-11 14:58:44 +0800551 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
552 for (size_t i = 0; i < mOutputs.size(); i++) {
553 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
554 // mute media strategies and delay device switch by the largest
555 // This avoid sending the music tail into the earpiece or headset.
556 setStrategyMute(musicStrategy, true, desc);
557 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
558 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
559 nullptr, true /*fromCache*/).types());
560 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800561 // Toggle the device state: UNAVAILABLE -> AVAILABLE
562 // This will force reading again the device configuration
563 status = setDeviceConnectionState(device,
564 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800565 device_address, device_name,
566 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800567 if (status != NO_ERROR) {
568 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
569 status);
570 return status;
571 }
572
573 status = setDeviceConnectionState(device,
574 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800575 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800576 if (status != NO_ERROR) {
577 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
578 status);
579 return status;
580 }
581
582 return NO_ERROR;
583}
584
Pattydd807582021-11-04 21:01:03 +0800585status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
586 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800587{
Pattydd807582021-11-04 21:01:03 +0800588 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800589 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800590 std::unordered_set<audio_format_t> formatSet;
591 sp<HwModule> primaryModule =
592 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700593 if (primaryModule == nullptr) {
594 ALOGE("%s() unable to get primary module", __func__);
595 return NO_INIT;
596 }
Pattydd807582021-11-04 21:01:03 +0800597
598 DeviceTypeSet audioDeviceSet;
599
600 switch(device) {
601 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
602 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
603 break;
604 case AUDIO_DEVICE_OUT_BLE_HEADSET:
605 audioDeviceSet = getAudioDeviceOutAllBleSet();
606 break;
607 default:
608 ALOGE("%s() device type 0x%08x not supported", __func__, device);
609 return BAD_VALUE;
610 }
611
jiabin9a3361e2019-10-01 09:38:30 -0700612 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800613 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800614 for (const auto& device : declaredDevices) {
615 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800616 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800617 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800618 return status;
619}
620
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100621DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
622{
623 DeviceVector rxSinkdevices{};
624 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
625 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
626 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
627 auto rxSinkDevice = rxSinkdevices.itemAt(0);
628 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
629 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
630 // retrieve Rx Source device descriptor
631 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
632 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
633
634 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
635 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
636 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
637 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
638 return DeviceVector(rxSinkDevice);
639 }
640 }
641 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
642 // the device returned is not necessarily reachable via this output
643 // (filter later by setOutputDevices())
644 return getNewOutputDevices(mPrimaryOutput, fromCache);
645}
646
647status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
648{
649 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
650 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
651 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
652 }
653 return INVALID_OPERATION;
654}
655
656status_t AudioPolicyManager::updateCallRoutingInternal(
657 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700658{
659 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100660 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700661 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700662 if(!hasPrimaryOutput() ||
663 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100664 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700665 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100666 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100667
Francois Gaffie716e1432019-01-14 16:58:59 +0100668 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100669 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100670 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100671
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100672 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100673 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674
Francois Gaffie601801d2021-06-22 13:27:39 +0200675 disconnectTelephonyAudioSource(mCallRxSourceClient);
676 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700677
François Gaffie9eb18552018-11-05 10:33:26 +0100678 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700679 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100680 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700681 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100682 // retrieve Rx Source and Tx Sink device descriptors
683 sp<DeviceDescriptor> rxSourceDevice =
684 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
685 String8(),
686 AUDIO_FORMAT_DEFAULT);
687 sp<DeviceDescriptor> txSinkDevice =
688 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
689 String8(),
690 AUDIO_FORMAT_DEFAULT);
691
692 // RX and TX Telephony device are declared by Primary Audio HAL
693 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
694 (telephonyRxModule->getHalVersionMajor() >= 3)) {
695 if (rxSourceDevice == 0 || txSinkDevice == 0) {
696 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100697 ALOGE("%s() no telephony Tx and/or RX device", __func__);
698 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100699 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100700 // createAudioPatchInternal now supports both HW / SW bridging
701 createRxPatch = true;
702 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100703 } else {
704 // If the RX device is on the primary HW module, then use legacy routing method for
705 // voice calls via setOutputDevice() on primary output.
706 // Otherwise, create two audio patches for TX and RX path.
707 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
708 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700709 // If the TX device is also on the primary HW module, setOutputDevice() will take care
710 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100711 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
712 (txSinkDevice != 0);
713 }
714 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
715 // Otherwise, create two audio patches for TX and RX path.
716 if (!createRxPatch) {
717 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700718 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200719 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800720 // If the TX device is on the primary HW module but RX device is
721 // on other HW module, SinkMetaData of telephony input should handle it
722 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700723 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700724 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100725 // terminate active capture if on the same HW module as the call TX source device
726 // FIXME: would be better to refine to only inputs whose profile connects to the
727 // call TX device but this information is not in the audio patch and logic here must be
728 // symmetric to the one in startInput()
729 for (const auto& activeDesc : mInputs.getActiveInputs()) {
730 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
731 closeActiveClients(activeDesc);
732 }
733 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200734 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800735 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100736 if (waitMs != nullptr) {
737 *waitMs = muteWaitMs;
738 }
739 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800740}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741
Mikhail Naganov100f0122018-11-29 11:22:16 -0800742bool AudioPolicyManager::isDeviceOfModule(
743 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
744 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
745 if (module != 0) {
746 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
747 .indexOf(devDesc) != NAME_NOT_FOUND
748 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
749 .indexOf(devDesc) != NAME_NOT_FOUND;
750 }
751 return false;
752}
753
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200754void AudioPolicyManager::connectTelephonyRxAudioSource()
755{
Francois Gaffie601801d2021-06-22 13:27:39 +0200756 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200757 const struct audio_port_config source = {
758 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
759 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
760 };
761 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200762 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
763 ALOGE_IF(mCallRxSourceClient == nullptr,
764 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200765}
766
Francois Gaffie601801d2021-06-22 13:27:39 +0200767void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200768{
Francois Gaffie601801d2021-06-22 13:27:39 +0200769 if (clientDesc == nullptr) {
770 return;
771 }
772 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
773 "%s error stopping audio source", __func__);
774 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200775}
776
777void AudioPolicyManager::connectTelephonyTxAudioSource(
778 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
779 uint32_t delayMs)
780{
Francois Gaffie601801d2021-06-22 13:27:39 +0200781 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200782 if (srcDevice == nullptr || sinkDevice == nullptr) {
783 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
784 return;
785 }
786 PatchBuilder patchBuilder;
787 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
788 ALOGV("%s between source %s and sink %s", __func__,
789 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200790 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200791 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
792
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200793 struct audio_port_config source = {};
794 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200795 mCallTxSourceClient = new InternalSourceClientDescriptor(
796 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200797 mCommunnicationStrategy, toVolumeSource(aa));
798 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
799 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200800 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
801 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200802 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
803 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200805 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200806}
807
Eric Laurente0720872014-03-11 09:30:41 -0700808void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700809{
810 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100811 // store previous phone state for management of sonification strategy below
812 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100813 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100814
815 if (mEngine->setPhoneState(state) != NO_ERROR) {
816 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700817 return;
818 }
François Gaffie2110e042015-03-24 08:41:51 +0100819 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700820 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700821 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700822 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800823 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700824 }
825
François Gaffie2110e042015-03-24 08:41:51 +0100826 /**
827 * Switching to or from incall state or switching between telephony and VoIP lead to force
828 * routing command.
829 */
Eric Laurent74b71512019-11-06 17:21:57 -0800830 bool force = ((isStateInCall(oldState) != isStateInCall(state))
831 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700832
833 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700834 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700835
Eric Laurente552edb2014-03-10 17:42:56 -0700836 int delayMs = 0;
837 if (isStateInCall(state)) {
838 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100839 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
840 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700841 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700842 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700843 // mute media and sonification strategies and delay device switch by the largest
844 // latency of any output where either strategy is active.
845 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100846 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
847 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
848 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700849 (delayMs < (int)desc->latency()*2)) {
850 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700851 }
François Gaffiec005e562018-11-06 15:04:49 +0100852 setStrategyMute(musicStrategy, true, desc);
853 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
854 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
855 nullptr, true /*fromCache*/).types());
856 setStrategyMute(sonificationStrategy, true, desc);
857 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
858 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
859 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700860 }
861 }
862
Eric Laurent87ffa392015-05-22 10:32:38 -0700863 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700864 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100865 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700866 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100867 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
868 // force routing command to audio hardware when ending call
869 // even if no device change is needed
870 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
871 rxDevices = mPrimaryOutput->devices();
872 }
873 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200874 disconnectTelephonyAudioSource(mCallRxSourceClient);
875 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100876 }
François Gaffie11d30102018-11-02 16:09:09 +0100877 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700878 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700879 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700880
881 // reevaluate routing on all outputs in case tracks have been started during the call
882 for (size_t i = 0; i < mOutputs.size(); i++) {
883 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100884 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200885 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
886 bool forceRouting = !newDevices.isEmpty();
887 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
888 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700889 }
890 }
891
Eric Laurent96d1dda2022-03-14 17:14:19 +0100892 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
893
Eric Laurente552edb2014-03-10 17:42:56 -0700894 if (isStateInCall(state)) {
895 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700896 // force reevaluating accessibility routing when call starts
897 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700898 }
899
900 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100901 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
902 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700903}
904
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700905audio_mode_t AudioPolicyManager::getPhoneState() {
906 return mEngine->getPhoneState();
907}
908
Eric Laurente0720872014-03-11 09:30:41 -0700909void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100910 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700911{
François Gaffie2110e042015-03-24 08:41:51 +0100912 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700913 if (config == mEngine->getForceUse(usage)) {
914 return;
915 }
Eric Laurente552edb2014-03-10 17:42:56 -0700916
François Gaffie2110e042015-03-24 08:41:51 +0100917 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
918 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
919 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700920 }
François Gaffie2110e042015-03-24 08:41:51 +0100921 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
922 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
923 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700924
925 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700926 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800927
Eric Laurent22fcda22019-05-17 16:28:47 -0700928 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
929 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
930 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
931 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
932 }
933
Eric Laurentdc462862016-07-19 12:29:53 -0700934 //FIXME: workaround for truncated touch sounds
935 // to be removed when the problem is handled by system UI
936 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700937 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
938 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
939 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700940
941 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100942 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700943}
944
Eric Laurente0720872014-03-11 09:30:41 -0700945void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700946{
947 ALOGV("setSystemProperty() property %s, value %s", property, value);
948}
949
Dorin Drimusecc9f422022-03-09 17:57:40 +0100950// Find an MSD output profile compatible with the parameters passed.
951// When "directOnly" is set, restrict search to profiles for direct outputs.
952sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
953 const DeviceVector& devices,
954 uint32_t samplingRate,
955 audio_format_t format,
956 audio_channel_mask_t channelMask,
957 audio_output_flags_t flags,
958 bool directOnly)
959{
960 flags = getRelevantFlags(flags, directOnly);
961
962 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
963 if (msdModule != nullptr) {
964 // for the msd module check if there are patches to the output devices
965 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
966 HwModuleCollection modules;
967 modules.add(msdModule);
968 return searchCompatibleProfileHwModules(
969 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
970 flags, directOnly);
971 }
972 }
973 return nullptr;
974}
975
Michael Chana94fbb22018-04-24 14:31:19 +1000976// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
977// search to profiles for direct outputs.
978sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100979 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000980 uint32_t samplingRate,
981 audio_format_t format,
982 audio_channel_mask_t channelMask,
983 audio_output_flags_t flags,
984 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700985{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100986 flags = getRelevantFlags(flags, directOnly);
987
988 return searchCompatibleProfileHwModules(
989 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
990}
991
992audio_output_flags_t AudioPolicyManager::getRelevantFlags (
993 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000994 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100995 // only retain flags that will drive the direct output profile selection
996 // if explicitly requested
997 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000998 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100999 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1000 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001001 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001002 return flags;
1003}
Eric Laurent861a6282015-05-18 15:40:16 -07001004
Dorin Drimusecc9f422022-03-09 17:57:40 +01001005sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1006 const HwModuleCollection& hwModules,
1007 const DeviceVector& devices,
1008 uint32_t samplingRate,
1009 audio_format_t format,
1010 audio_channel_mask_t channelMask,
1011 audio_output_flags_t flags,
1012 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001013 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001014 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001015 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001016 if (!curProfile->isCompatibleProfile(devices,
1017 samplingRate, NULL /*updatedSamplingRate*/,
1018 format, NULL /*updatedFormat*/,
1019 channelMask, NULL /*updatedChannelMask*/,
1020 flags)) {
1021 continue;
1022 }
1023 // reject profiles not corresponding to a device currently available
1024 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1025 continue;
1026 }
1027 // reject profiles if connected device does not support codec
1028 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1029 continue;
1030 }
1031 if (!directOnly) {
1032 return curProfile;
1033 }
1034
1035 // when searching for direct outputs, if several profiles are compatible, give priority
1036 // to one with offload capability
1037 if (profile != 0 &&
1038 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001039 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001040 }
1041 profile = curProfile;
1042 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1043 break;
1044 }
Eric Laurente552edb2014-03-10 17:42:56 -07001045 }
1046 }
Eric Laurent861a6282015-05-18 15:40:16 -07001047 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001048}
1049
Eric Laurentfa0f6742021-08-17 18:39:44 +02001050sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001051 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001052{
1053 for (const auto& hwModule : mHwModules) {
1054 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001055 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001056 continue;
1057 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001058 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001059 // reject profiles not corresponding to a device currently available
1060 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1061 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1062 continue;
1063 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001064 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1065 != devices.size()) {
1066 continue;
1067 }
1068 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001069 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1070 return curProfile;
1071 }
1072 }
1073 return nullptr;
1074}
1075
Eric Laurentf4e63452017-11-06 19:31:46 +00001076audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001077{
François Gaffiec005e562018-11-06 15:04:49 +01001078 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001079
1080 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1081 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1082 // format, flags, etc. This may result in some discrepancy for functions that utilize
1083 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1084 // and AudioSystem::getOutputSamplingRate().
1085
François Gaffie11d30102018-11-02 16:09:09 +01001086 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001087 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001088
François Gaffie11d30102018-11-02 16:09:09 +01001089 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1090 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001091 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001092}
1093
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001094status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1095 const audio_attributes_t *srcAttr,
1096 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001097{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001098 if (srcAttr != NULL) {
1099 if (!isValidAttributes(srcAttr)) {
1100 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1101 __func__,
1102 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1103 srcAttr->tags);
1104 return BAD_VALUE;
1105 }
1106 *dstAttr = *srcAttr;
1107 } else {
1108 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1109 ALOGE("%s: invalid stream type", __func__);
1110 return BAD_VALUE;
1111 }
François Gaffiec005e562018-11-06 15:04:49 +01001112 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001113 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001114
1115 // Only honor audibility enforced when required. The client will be
1116 // forced to reconnect if the forced usage changes.
1117 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001118 dstAttr->flags = static_cast<audio_flags_mask_t>(
1119 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001120 }
1121
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001122 return NO_ERROR;
1123}
1124
Kevin Rocard153f92d2018-12-18 18:33:28 -08001125status_t AudioPolicyManager::getOutputForAttrInt(
1126 audio_attributes_t *resultAttr,
1127 audio_io_handle_t *output,
1128 audio_session_t session,
1129 const audio_attributes_t *attr,
1130 audio_stream_type_t *stream,
1131 uid_t uid,
1132 const audio_config_t *config,
1133 audio_output_flags_t *flags,
1134 audio_port_handle_t *selectedDeviceId,
1135 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001136 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001137 output_type_t *outputType,
1138 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001139{
François Gaffiec005e562018-11-06 15:04:49 +01001140 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001141 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001142 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001143 const sp<DeviceDescriptor> requestedDevice =
1144 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1145
Eric Laurent8a1095a2019-11-08 14:44:16 -08001146 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001147 *isSpatialized = false;
1148
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1150 if (status != NO_ERROR) {
1151 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001152 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001153 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001154 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001155 }
François Gaffiec005e562018-11-06 15:04:49 +01001156 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001157
François Gaffiec005e562018-11-06 15:04:49 +01001158 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1159 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001160
Kevin Rocard153f92d2018-12-18 18:33:28 -08001161 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1162 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1163 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001164 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001165 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1166 .channel_mask = config->channel_mask,
1167 .format = config->format,
1168 };
1169 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1170 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001171 if (status != OK) {
1172 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001173 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001174
Kevin Rocard153f92d2018-12-18 18:33:28 -08001175 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001176 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001177
1178 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001179 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1180 && !audio_is_linear_pcm(config->format)) {
1181 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001182 return BAD_VALUE;
1183 }
1184 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001185 sp<DeviceDescriptor> deviceDesc =
1186 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1187 primaryMix->mDeviceAddress,
1188 AUDIO_FORMAT_DEFAULT);
1189 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001190 bool tryDirectForFlags = policyDesc == nullptr ||
1191 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1192 // if a direct output can be opened to deliver the track's multi-channel content to the
1193 // output rather than being downmixed by the primary output, then use this direct
1194 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1195 // mix.
1196 bool tryDirectForChannelMask = policyDesc != nullptr
1197 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1198 audio_channel_count_from_out_mask(config->channel_mask));
1199 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001200 audio_io_handle_t newOutput;
1201 status = openDirectOutput(
1202 *stream, session, config,
1203 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1204 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001205 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001206 policyDesc = mOutputs.valueFor(newOutput);
1207 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001208 } else if (tryDirectForFlags) {
1209 policyDesc = nullptr;
1210 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001211 }
1212 if (policyDesc != nullptr) {
1213 policyDesc->mPolicyMix = primaryMix;
1214 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001215 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001216
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001217 ALOGV("getOutputForAttr() returns output %d", *output);
1218 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1219 *outputType = API_OUT_MIX_PLAYBACK;
1220 } else {
1221 *outputType = API_OUTPUT_LEGACY;
1222 }
1223 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001224 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001225 }
François Gaffiec005e562018-11-06 15:04:49 +01001226 // Virtual sources must always be dynamicaly or explicitly routed
1227 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1228 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1229 return BAD_VALUE;
1230 }
1231 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1232 // in order to let the choice of the order to future vendor engine
1233 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001234
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001235 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001236 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001237 }
1238
Nadav Barb2f18162018-07-18 13:01:53 +03001239 // Set incall music only if device was explicitly set, and fallback to the device which is
1240 // chosen by the engine if not.
1241 // FIXME: provide a more generic approach which is not device specific and move this back
1242 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001243 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001244 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001245 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001246 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001247 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001248 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001249 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001250 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001251 }
1252 }
1253
François Gaffiec005e562018-11-06 15:04:49 +01001254 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1255 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1256 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001257
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001258 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001259 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001260 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001261 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001262 ALOGV("%s() Using MSD devices %s instead of devices %s",
1263 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001264 } else {
1265 *output = AUDIO_IO_HANDLE_NONE;
1266 }
1267 }
1268 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001269 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001270 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001271 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001272 if (*output == AUDIO_IO_HANDLE_NONE) {
1273 return INVALID_OPERATION;
1274 }
Paul McLeanaa981192015-03-21 09:55:15 -07001275
François Gaffiec005e562018-11-06 15:04:49 +01001276 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001277 for (auto &outputDevice : outputDevices) {
1278 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1279 *selectedDeviceId = outputDevice->getId();
1280 break;
1281 }
1282 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001283
Eric Laurent8a1095a2019-11-08 14:44:16 -08001284 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1285 *outputType = API_OUTPUT_TELEPHONY_TX;
1286 } else {
1287 *outputType = API_OUTPUT_LEGACY;
1288 }
1289
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001290 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1291
1292 return NO_ERROR;
1293}
1294
1295status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1296 audio_io_handle_t *output,
1297 audio_session_t session,
1298 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001299 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001300 const audio_config_t *config,
1301 audio_output_flags_t *flags,
1302 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001303 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001304 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001305 output_type_t *outputType,
1306 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001307{
1308 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1309 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1310 return INVALID_OPERATION;
1311 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001312 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001313 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001314 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001315 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001316 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001317 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001318 const sp<DeviceDescriptor> requestedDevice =
1319 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1320
1321 // Prevent from storing invalid requested device id in clients
1322 const audio_port_handle_t sanitizedRequestedPortId =
1323 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1324 *selectedDeviceId = sanitizedRequestedPortId;
1325
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001326 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001327 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001328 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001329 if (status != NO_ERROR) {
1330 return status;
1331 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001332 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001333 if (secondaryOutputs != nullptr) {
1334 for (auto &secondaryMix : secondaryMixes) {
1335 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1336 if (outputDesc != nullptr &&
1337 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1338 secondaryOutputs->push_back(outputDesc->mIoHandle);
1339 weakSecondaryOutputDescs.push_back(outputDesc);
1340 }
1341 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001342 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001343
Eric Laurent8fc147b2018-07-22 19:13:55 -07001344 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001345 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001346 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001347 };
jiabin4ef93452019-09-10 14:29:54 -07001348 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001349
Eric Laurentc209fe42020-06-05 18:11:23 -07001350 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001351 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001352 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001353 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001354 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001355 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001356 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001357 std::move(weakSecondaryOutputDescs),
1358 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001359 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001360
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001361 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1362 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001363
Eric Laurente83b55d2014-11-14 10:06:21 -08001364 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001365}
1366
Eric Laurentc529cf62020-04-17 18:19:10 -07001367status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1368 audio_session_t session,
1369 const audio_config_t *config,
1370 audio_output_flags_t flags,
1371 const DeviceVector &devices,
1372 audio_io_handle_t *output) {
1373
1374 *output = AUDIO_IO_HANDLE_NONE;
1375
1376 // skip direct output selection if the request can obviously be attached to a mixed output
1377 // and not explicitly requested
1378 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1379 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1380 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1381 return NAME_NOT_FOUND;
1382 }
1383
1384 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1385 // This prevents creating an offloaded track and tearing it down immediately after start
1386 // when audioflinger detects there is an active non offloadable effect.
1387 // FIXME: We should check the audio session here but we do not have it in this context.
1388 // This may prevent offloading in rare situations where effects are left active by apps
1389 // in the background.
1390 sp<IOProfile> profile;
1391 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1392 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1393 profile = getProfileForOutput(
1394 devices, config->sample_rate, config->format, config->channel_mask,
1395 flags, true /* directOnly */);
1396 }
1397
1398 if (profile == nullptr) {
1399 return NAME_NOT_FOUND;
1400 }
1401
1402 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1403 for (size_t i = 0; i < mOutputs.size(); i++) {
1404 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1405 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1406 // reuse direct output if currently open by the same client
1407 // and configured with same parameters
1408 if ((config->sample_rate == desc->getSamplingRate()) &&
1409 (config->format == desc->getFormat()) &&
1410 (config->channel_mask == desc->getChannelMask()) &&
1411 (session == desc->mDirectClientSession)) {
1412 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001413 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001414 mOutputs.keyAt(i), session);
1415 *output = mOutputs.keyAt(i);
1416 return NO_ERROR;
1417 }
1418 }
1419 }
1420
1421 if (!profile->canOpenNewIo()) {
1422 return NAME_NOT_FOUND;
1423 }
1424
1425 sp<SwAudioOutputDescriptor> outputDesc =
1426 new SwAudioOutputDescriptor(profile, mpClientInterface);
1427
Michael Chan6fb34492020-12-08 15:44:49 +11001428 // An MSD patch may be using the only output stream that can service this request. Release
1429 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001430 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001431
Eric Laurentf1f22e72021-07-13 14:04:14 +02001432 status_t status =
1433 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001434
1435 // only accept an output with the requested parameters
1436 if (status != NO_ERROR ||
1437 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1438 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1439 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1440 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1441 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1442 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1443 config->channel_mask, outputDesc->getChannelMask());
1444 if (*output != AUDIO_IO_HANDLE_NONE) {
1445 outputDesc->close();
1446 }
1447 // fall back to mixer output if possible when the direct output could not be open
1448 if (audio_is_linear_pcm(config->format) &&
1449 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1450 return NAME_NOT_FOUND;
1451 }
1452 *output = AUDIO_IO_HANDLE_NONE;
1453 return BAD_VALUE;
1454 }
1455 outputDesc->mDirectOpenCount = 1;
1456 outputDesc->mDirectClientSession = session;
1457
1458 addOutput(*output, outputDesc);
1459 mPreviousOutputs = mOutputs;
1460 ALOGV("%s returns new direct output %d", __func__, *output);
1461 mpClientInterface->onAudioPortListUpdate();
1462 return NO_ERROR;
1463}
1464
François Gaffie11d30102018-11-02 16:09:09 +01001465audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1466 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001467 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001468 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001469 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001470 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001471 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001472 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001473{
Andy Hungc88b0642018-04-27 15:42:35 -07001474 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001475
jiabine375d412019-02-26 12:54:53 -08001476 // Discard haptic channel mask when forcing muting haptic channels.
1477 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001478 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1479 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001480
Eric Laurente552edb2014-03-10 17:42:56 -07001481 // open a direct output if required by specified parameters
1482 //force direct flag if offload flag is set: offloading implies a direct output stream
1483 // and all common behaviors are driven by checking only the direct flag
1484 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001485 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1486 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001487 }
Nadav Bar766fb022018-01-07 12:18:03 +02001488 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1489 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001490 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001491
1492 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1493
Eric Laurente83b55d2014-11-14 10:06:21 -08001494 // only allow deep buffering for music stream type
1495 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001496 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001497 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001498 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001499 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1500 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001501 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001502 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001503 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001504 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001505 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001506 audio_is_linear_pcm(config->format) &&
1507 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001508 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001509 AUDIO_OUTPUT_FLAG_DIRECT);
1510 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001511 }
Eric Laurente552edb2014-03-10 17:42:56 -07001512
Carter Hsua3abb402021-10-26 11:11:20 +08001513 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1514 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1515 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1516 }
1517
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001518 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001519 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001520 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001521 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001522 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001523 }
1524
Eric Laurentc529cf62020-04-17 18:19:10 -07001525 audio_config_t directConfig = *config;
1526 directConfig.channel_mask = channelMask;
1527 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1528 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001529 return output;
1530 }
1531
Eric Laurent14cbfca2016-03-17 09:42:16 -07001532 // A request for HW A/V sync cannot fallback to a mixed output because time
1533 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001534 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001535 return AUDIO_IO_HANDLE_NONE;
1536 }
1537
Eric Laurente552edb2014-03-10 17:42:56 -07001538 // ignoring channel mask due to downmix capability in mixer
1539
1540 // open a non direct output
1541
1542 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001543 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001544 // get which output is suitable for the specified stream. The actual
1545 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001546 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001547
Eric Laurent8838a382014-09-08 16:44:28 -07001548 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001549 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001550 output = selectOutput(
1551 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001552 }
François Gaffie11d30102018-11-02 16:09:09 +01001553 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001554 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001555 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001556
Eric Laurente552edb2014-03-10 17:42:56 -07001557 return output;
1558}
1559
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001560sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001561 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1562 mAvailableInputDevices);
1563 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1564}
1565
1566DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1567 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1568 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001569}
1570
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001571const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001572 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001573 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1574 if (msdModule != 0) {
1575 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1576 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1577 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1578 const struct audio_port_config *source = &patch->mPatch.sources[j];
1579 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1580 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001581 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001582 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001583 }
1584 }
1585 }
1586 return msdPatches;
1587}
1588
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001589bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1590 ssize_t index = mAudioPatches.indexOfKey(handle);
1591 if (index < 0) {
1592 return false;
1593 }
1594 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1595 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1596 if (msdModule == nullptr) {
1597 return false;
1598 }
1599 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1600 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1601 return true;
1602 }
1603 index = getMsdOutputPatches().indexOfKey(handle);
1604 if (index < 0) {
1605 return false;
1606 }
1607 return true;
1608}
1609
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001610status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1611 const InputProfileCollection &inputProfiles,
1612 const OutputProfileCollection &outputProfiles,
1613 const sp<DeviceDescriptor> &sourceDevice,
1614 const sp<DeviceDescriptor> &sinkDevice,
1615 AudioProfileVector& sourceProfiles,
1616 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001617 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001618 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001619 return NO_INIT;
1620 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001621 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001622 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001623 return NO_INIT;
1624 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001625 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001626 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1627 inProfile->supportsDevice(sourceDevice)) {
1628 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001629 }
1630 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001631 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001632 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001633 outProfile->supportsDevice(sinkDevice)) {
1634 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001635 }
1636 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001637 return NO_ERROR;
1638}
1639
1640status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1641 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1642 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1643{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001644 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001645 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1646 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1647 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001648 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001649 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1650 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001651 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001652 }
1653 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1654 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1655 sinkConfig->format = bestSinkConfig.format;
1656 // For encoded streams force direct flag to prevent downstream mixing.
1657 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1658 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001659 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1660 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001661 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001662 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1663 // raw and IEC61937 framed streams.
1664 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1665 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1666 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001667 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1668 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1669 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1670 sourceConfig->format = bestSinkConfig.format;
1671 // Copy input stream directly without any processing (e.g. resampling).
1672 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1673 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1674 if (hwAvSync) {
1675 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1676 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1677 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1678 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1679 }
1680 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1681 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1682 sinkConfig->config_mask |= config_mask;
1683 sourceConfig->config_mask |= config_mask;
1684 return NO_ERROR;
1685}
1686
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001687PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1688 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001689{
1690 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001691 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1692 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1693 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1694 if (deviceModule == nullptr) {
1695 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1696 return patchBuilder;
1697 }
1698 const InputProfileCollection inputProfiles = msdIsSource ?
1699 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1700 const OutputProfileCollection outputProfiles = msdIsSource ?
1701 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1702
1703 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1704 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1705 device : getMsdAudioOutDevices().itemAt(0);
1706 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1707
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001708 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1709 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001710 AudioProfileVector sourceProfiles;
1711 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001712 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1713 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001714 for (auto hwAvSync : { true, false }) {
1715 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1716 sourceProfiles, sinkProfiles) != NO_ERROR) {
1717 continue;
1718 }
1719 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1720 &sinkConfig) == NO_ERROR) {
1721 // Found a matching config. Re-create PatchBuilder with this config.
1722 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1723 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001725 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001726 " supporting PCM format conversion.", __func__);
1727 return patchBuilder;
1728}
1729
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001730status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001731 DeviceVector devices;
1732 if (outputDevices != nullptr && outputDevices->size() > 0) {
1733 devices.add(*outputDevices);
1734 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001735 // Use media strategy for unspecified output device. This should only
1736 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1737 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001738 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001739 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001740 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001741 }
Michael Chan6fb34492020-12-08 15:44:49 +11001742 std::vector<PatchBuilder> patchesToCreate;
1743 for (auto i = 0u; i < devices.size(); ++i) {
1744 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001745 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001746 }
1747 // Retain only the MSD patches associated with outputDevices request.
1748 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001749 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001750 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1751 auto retainedPatch = false;
1752 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1753 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1754 patchesToRemove.removeItemsAt(i);
1755 retainedPatch = true;
1756 break;
1757 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001758 }
Michael Chan6fb34492020-12-08 15:44:49 +11001759 if (retainedPatch) {
1760 it = patchesToCreate.erase(it);
1761 continue;
1762 }
1763 ++it;
1764 }
1765 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1766 return NO_ERROR;
1767 }
1768 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1769 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001770 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771 }
Michael Chan6fb34492020-12-08 15:44:49 +11001772 status_t status = NO_ERROR;
1773 for (const auto &p : patchesToCreate) {
1774 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1775 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1776 char message[256];
1777 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1778 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1779 currStatus == NO_ERROR ? "Success" : "Error",
1780 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1781 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1782 if (currStatus == NO_ERROR) {
1783 ALOGD("%s", message);
1784 } else {
1785 ALOGE("%s", message);
1786 if (status == NO_ERROR) {
1787 status = currStatus;
1788 }
1789 }
1790 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001791 return status;
1792}
1793
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001794void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1795 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001796 for (size_t i = 0; i < msdPatches.size(); i++) {
1797 const auto& patch = msdPatches[i];
1798 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1799 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1800 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1801 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1802 releaseAudioPatch(patch->getHandle(), mUidCached);
1803 break;
1804 }
1805 }
1806 }
1807}
1808
Dorin Drimus94d94412022-02-02 09:05:02 +01001809bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1810 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1811 AudioPatchCollection msdPatches = getMsdOutputPatches();
1812 for (size_t i = 0; i < msdPatches.size(); i++) {
1813 const auto& patch = msdPatches[i];
1814 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1815 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1816 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1817 const auto& foundDevice = devicesToCheck.getDevice(
1818 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1819 if (foundDevice != nullptr) {
1820 devicesToCheck.remove(foundDevice);
1821 if (devicesToCheck.isEmpty()) {
1822 return true;
1823 }
1824 }
1825 }
1826 }
1827 }
1828 return false;
1829}
1830
Eric Laurente0720872014-03-11 09:30:41 -07001831audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001832 audio_output_flags_t flags,
1833 audio_format_t format,
1834 audio_channel_mask_t channelMask,
1835 uint32_t samplingRate,
1836 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001837{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001838 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1839 "%s called with format %#x", __func__, format);
1840
jiabinebb6af42020-06-09 17:31:17 -07001841 // Return the output that haptic-generating attached to when 1) session id is specified,
1842 // 2) haptic-generating effect exists for given session id and 3) the output that
1843 // haptic-generating effect attached to is in given outputs.
1844 if (sessionId != AUDIO_SESSION_NONE) {
1845 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1846 sessionId, FX_IID_HAPTICGENERATOR);
1847 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1848 return hapticGeneratingOutput;
1849 }
1850 }
1851
Eric Laurent16c66dd2019-05-01 17:54:10 -07001852 // Flags disqualifying an output: the match must happen before calling selectOutput()
1853 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1854 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1855
1856 // Flags expressing a functional request: must be honored in priority over
1857 // other criteria
1858 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1859 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001860 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1861 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001862 // Flags expressing a performance request: have lower priority than serving
1863 // requested sampling rate or channel mask
1864 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1865 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1866 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1867
1868 const audio_output_flags_t functionalFlags =
1869 (audio_output_flags_t)(flags & kFunctionalFlags);
1870 const audio_output_flags_t performanceFlags =
1871 (audio_output_flags_t)(flags & kPerformanceFlags);
1872
1873 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1874
Eric Laurente552edb2014-03-10 17:42:56 -07001875 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001876 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001877 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001878 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001879 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001880 // with tiebreak preferring the minimum number of extra functional flags
1881 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001882 // 3: the output supporting the exact channel mask
1883 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001884 // 5: the output with the highest sampling rate if the requested sample rate is
1885 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001886 // 6: the output with the highest number of requested performance flags
1887 // 7: the output with the bit depth the closest to the requested one
1888 // 8: the primary output
1889 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001890
Eric Laurent16c66dd2019-05-01 17:54:10 -07001891 // matching criteria values in priority order for best matching output so far
1892 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001893
Eric Laurent16c66dd2019-05-01 17:54:10 -07001894 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1895 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1896 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001897
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001898 for (audio_io_handle_t output : outputs) {
1899 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001900 // matching criteria values in priority order for current output
1901 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001902
Eric Laurent16c66dd2019-05-01 17:54:10 -07001903 if (outputDesc->isDuplicated()) {
1904 continue;
1905 }
1906 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1907 continue;
1908 }
Eric Laurent8838a382014-09-08 16:44:28 -07001909
Eric Laurent16c66dd2019-05-01 17:54:10 -07001910 // If haptic channel is specified, use the haptic output if present.
1911 // When using haptic output, same audio format and sample rate are required.
1912 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001913 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001914 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1915 continue;
1916 }
1917 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001918 && format == outputDesc->getFormat()
1919 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001920 currentMatchCriteria[0] = outputHapticChannelCount;
1921 }
1922
1923 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001924 const int matchingFunctionalFlags =
1925 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1926 const int totalFunctionalFlags =
1927 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1928 // Prefer matching functional flags, but subtract unnecessary functional flags.
1929 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001930
1931 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001932 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1933 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001934 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1935 channelCount <= outputChannelCount) {
1936 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001937 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1938 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001939 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001940 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001941 currentMatchCriteria[3] = outputChannelCount;
1942 }
1943
1944 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001945 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001946 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001947 }
1948
1949 // performance flags match
1950 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1951
1952 // format match
1953 if (format != AUDIO_FORMAT_INVALID) {
1954 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001955 PolicyAudioPort::kFormatDistanceMax -
1956 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001957 }
1958
1959 // primary output match
1960 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1961
1962 // compare match criteria by priority then value
1963 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1964 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1965 bestMatchCriteria = currentMatchCriteria;
1966 bestOutput = output;
1967
1968 std::stringstream result;
1969 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1970 std::ostream_iterator<int>(result, " "));
1971 ALOGV("%s new bestOutput %d criteria %s",
1972 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001973 }
1974 }
1975
Eric Laurent16c66dd2019-05-01 17:54:10 -07001976 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001977}
1978
Eric Laurent8fc147b2018-07-22 19:13:55 -07001979status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001980{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001981 ALOGV("%s portId %d", __FUNCTION__, portId);
1982
1983 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1984 if (outputDesc == 0) {
1985 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001986 return BAD_VALUE;
1987 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001988 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001989
Eric Laurent8fc147b2018-07-22 19:13:55 -07001990 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001991 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001992
Eric Laurent733ce942017-12-07 12:18:25 -08001993 status_t status = outputDesc->start();
1994 if (status != NO_ERROR) {
1995 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001996 }
1997
Eric Laurent97ac8712018-07-27 18:59:02 -07001998 uint32_t delayMs;
1999 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002000
2001 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002002 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002003 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002004 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002005 if (delayMs != 0) {
2006 usleep(delayMs * 1000);
2007 }
2008
2009 return status;
2010}
2011
Eric Laurent96d1dda2022-03-14 17:14:19 +01002012bool AudioPolicyManager::isLeUnicastActive() const {
2013 if (isInCall()) {
2014 return true;
2015 }
2016 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2017}
2018
2019bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2020 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2021 return false;
2022 }
2023 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2024 ALOGV("%s active %d", __func__, active);
2025 return active;
2026}
2027
Eric Laurent97ac8712018-07-27 18:59:02 -07002028status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2029 const sp<TrackClientDescriptor>& client,
2030 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002031{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002032 // cannot start playback of STREAM_TTS if any other output is being used
2033 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002034
2035 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002036 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002037 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002038 auto clientStrategy = client->strategy();
2039 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002040 if (stream == AUDIO_STREAM_TTS) {
2041 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002042 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002043 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002044 return INVALID_OPERATION;
2045 } else {
2046 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2047 }
2048 } else {
2049 // some playback other than beacon starts
2050 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2051 }
2052
Eric Laurent77305a62016-07-25 16:39:22 -07002053 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002054 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002055 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002056
François Gaffie11d30102018-11-02 16:09:09 +01002057 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002058 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002059 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002060 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002061 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002062 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002063 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002064 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002065 } else {
2066 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002067 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002068 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2069 AUDIO_FORMAT_DEFAULT);
2070 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2071 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002072 }
2073
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002074 // requiresMuteCheck is false when we can bypass mute strategy.
2075 // It covers a common case when there is no materially active audio
2076 // and muting would result in unnecessary delay and dropped audio.
2077 const uint32_t outputLatencyMs = outputDesc->latency();
2078 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002079 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002080
Eric Laurente552edb2014-03-10 17:42:56 -07002081 // increment usage count for this stream on the requested output:
2082 // NOTE that the usage count is the same for duplicated output and hardware output which is
2083 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002084 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002085
2086 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002087 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2088 client->isPreferredDeviceForExclusiveUse()) {
2089 // Preferred device may be exclusive, use only if no other active clients on this output
2090 devices = DeviceVector(
2091 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2092 } else {
2093 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2094 }
François Gaffie11d30102018-11-02 16:09:09 +01002095 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002096 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002097 }
2098 }
Eric Laurente552edb2014-03-10 17:42:56 -07002099
François Gaffiec005e562018-11-06 15:04:49 +01002100 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002101 selectOutputForMusicEffects();
2102 }
2103
François Gaffie1c878552018-11-22 16:53:21 +01002104 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002105 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002106 if (devices.isEmpty()) {
2107 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002108 }
François Gaffiec005e562018-11-06 15:04:49 +01002109 bool shouldWait =
2110 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2111 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2112 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002113 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002114 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002115 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002116 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002117 // An output has a shared device if
2118 // - managed by the same hw module
2119 // - supports the currently selected device
2120 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002121 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002122
Eric Laurent77305a62016-07-25 16:39:22 -07002123 // force a device change if any other output is:
2124 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002125 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002126 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002127 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002128 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002129 // change the device currently selected by the other output.
2130 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002131 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002132 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002133 force = true;
2134 }
2135 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002136 // a notification so that audio focus effect can propagate, or that a mute/unmute
2137 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002138 const uint32_t latencyMs = desc->latency();
2139 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2140
2141 if (shouldWait && isActive && (waitMs < latencyMs)) {
2142 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002143 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002144
2145 // Require mute check if another output is on a shared device
2146 // and currently active to have proper drain and avoid pops.
2147 // Note restoring AudioTracks onto this output needs to invoke
2148 // a volume ramp if there is no mute.
2149 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002150 }
2151 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002152
2153 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002154 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002155
Eric Laurente552edb2014-03-10 17:42:56 -07002156 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002157 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002158 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002159 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002160 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002161 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002162 outputDesc->useHwGain() /*force*/)) {
2163 // request AudioService to reinitialize the volume curves asynchronously
2164 ALOGE("checkAndSetVolume failed, requesting volume range init");
2165 mpClientInterface->onVolumeRangeInitRequest();
2166 };
Eric Laurente552edb2014-03-10 17:42:56 -07002167
2168 // update the outputs if starting an output with a stream that can affect notification
2169 // routing
2170 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002171
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002172 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002173 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002174 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2175 }
Eric Laurentdc462862016-07-19 12:29:53 -07002176
2177 if (waitMs > muteWaitMs) {
2178 *delayMs = waitMs - muteWaitMs;
2179 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002180
2181 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2182 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2183 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2184 // change occurs after the MixerThread starts and causes a stream volume
2185 // glitch.
2186 //
2187 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002188 }
Eric Laurentdc462862016-07-19 12:29:53 -07002189
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002190 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002191 mEngine->getForceUse(
2192 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002193 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002194 }
2195
Eric Laurent97ac8712018-07-27 18:59:02 -07002196 // Automatically enable the remote submix input when output is started on a re routing mix
2197 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002198 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2199 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002200 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2201 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2202 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002203 "remote-submix",
2204 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002205 }
2206
Eric Laurent96d1dda2022-03-14 17:14:19 +01002207 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2208
Eric Laurente552edb2014-03-10 17:42:56 -07002209 return NO_ERROR;
2210}
2211
Eric Laurent96d1dda2022-03-14 17:14:19 +01002212void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2213 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2214 bool isUnicastActive = isLeUnicastActive();
2215
2216 if (wasUnicastActive != isUnicastActive) {
2217 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2218 for (size_t i = 0; i < mOutputs.size(); i++) {
2219 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2220 if (desc != ignoredOutput && desc->isActive()
2221 && ((isUnicastActive &&
2222 !desc->devices().
2223 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2224 || (wasUnicastActive &&
2225 !desc->devices().getDevicesFromTypes(
2226 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2227 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2228 bool force = desc->devices() != newDevices;
2229 setOutputDevices(desc, newDevices, force, delayMs);
2230 // re-apply device specific volume if not done by setOutputDevice()
2231 if (!force) {
2232 applyStreamVolumes(desc, newDevices.types(), delayMs);
2233 }
2234 }
2235 }
2236 }
2237}
2238
Eric Laurent8fc147b2018-07-22 19:13:55 -07002239status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002240{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002241 ALOGV("%s portId %d", __FUNCTION__, portId);
2242
2243 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2244 if (outputDesc == 0) {
2245 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002246 return BAD_VALUE;
2247 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002248 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002249
Eric Laurent97ac8712018-07-27 18:59:02 -07002250 ALOGV("stopOutput() output %d, stream %d, session %d",
2251 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002252
Eric Laurent97ac8712018-07-27 18:59:02 -07002253 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002254
Eric Laurent733ce942017-12-07 12:18:25 -08002255 if (status == NO_ERROR ) {
2256 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002257 }
2258 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002259}
2260
Eric Laurent97ac8712018-07-27 18:59:02 -07002261status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2262 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002263{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002264 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002265 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002266 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002267 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002268
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002269 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2270
François Gaffie1c878552018-11-22 16:53:21 +01002271 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2272 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002273 // Automatically disable the remote submix input when output is stopped on a
2274 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002275 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002276 if (isSingleDeviceType(
2277 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002278 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002279 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002280 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2281 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002282 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002283 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002284 }
2285 }
2286 bool forceDeviceUpdate = false;
2287 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002288 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002289 forceDeviceUpdate = true;
2290 }
2291
Eric Laurente552edb2014-03-10 17:42:56 -07002292 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002293 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002294
Eric Laurente552edb2014-03-10 17:42:56 -07002295 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002296 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002297 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002298 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002299
2300 // If the routing does not change, if an output is routed on a device using HwGain
2301 // (aka setAudioPortConfig) and there are still active clients following different
2302 // volume group(s), force reapply volume
2303 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2304 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2305
Eric Laurente552edb2014-03-10 17:42:56 -07002306 // delay the device switch by twice the latency because stopOutput() is executed when
2307 // the track stop() command is received and at that time the audio track buffer can
2308 // still contain data that needs to be drained. The latency only covers the audio HAL
2309 // and kernel buffers. Also the latency does not always include additional delay in the
2310 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002311 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2312 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002313
2314 // force restoring the device selection on other active outputs if it differs from the
2315 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002316 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002317 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002318 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002319 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002320 desc->isActive() &&
2321 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002322 (newDevices != desc->devices())) {
2323 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2324 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002325
François Gaffie11d30102018-11-02 16:09:09 +01002326 setOutputDevices(desc, newDevices2, force, delayMs);
2327
Eric Laurent57de36c2016-09-28 16:59:11 -07002328 // re-apply device specific volume if not done by setOutputDevice()
2329 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002330 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002331 }
Eric Laurente552edb2014-03-10 17:42:56 -07002332 }
2333 }
2334 // update the outputs if stopping one with a stream that can affect notification routing
2335 handleNotificationRoutingForStream(stream);
2336 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002337
2338 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2339 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002340 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002341 }
2342
François Gaffiec005e562018-11-06 15:04:49 +01002343 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002344 selectOutputForMusicEffects();
2345 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002346
2347 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2348
Eric Laurente552edb2014-03-10 17:42:56 -07002349 return NO_ERROR;
2350 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002351 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002352 return INVALID_OPERATION;
2353 }
2354}
2355
jiabinbce0c1d2020-10-05 11:20:18 -07002356bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002357{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002358 ALOGV("%s portId %d", __FUNCTION__, portId);
2359
2360 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2361 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002362 // If an output descriptor is closed due to a device routing change,
2363 // then there are race conditions with releaseOutput from tracks
2364 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2365 // destroyed shortly thereafter.
2366 //
2367 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002368 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002369 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002370 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002371
2372 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002373
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302374 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2375 if (outputDesc->isClientActive(client)) {
2376 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2377 stopOutput(portId);
2378 }
2379
Eric Laurent8fc147b2018-07-22 19:13:55 -07002380 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2381 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002382 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002383 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002384 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002385 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002386 if (--outputDesc->mDirectOpenCount == 0) {
2387 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002388 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002389 }
2390 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302391
Andy Hung39efb7a2018-09-26 15:39:28 -07002392 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002393 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2394 // The output is pending reopened to query dynamic profiles and
2395 // there is no active clients
2396 closeOutput(outputDesc->mIoHandle);
2397 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2398 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2399 if (newOutputDesc == nullptr) {
2400 ALOGE("%s failed to open output", __func__);
2401 }
2402 return true;
2403 }
2404 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002405}
2406
Eric Laurentcaf7f482014-11-25 17:50:47 -08002407status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2408 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002409 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002410 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002411 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002412 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002413 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002414 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002415 input_type_t *inputType,
2416 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002417{
François Gaffiec005e562018-11-06 15:04:49 +01002418 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002419 "flags %#x attributes=%s requested device ID %d",
2420 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2421 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002422
Eric Laurentad2e7b92017-09-14 20:06:42 -07002423 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002424 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002425 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002426 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002427 sp<AudioInputDescriptor> inputDesc;
2428 sp<RecordClientDescriptor> clientDesc;
2429 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002430 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002431 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002432
2433 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2434 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2435 return INVALID_OPERATION;
2436 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002437
Francois Gaffie716e1432019-01-14 16:58:59 +01002438 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2439 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002440 }
2441
Paul McLean466dc8e2015-04-17 13:15:36 -06002442 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002443 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002444 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002445
Eric Laurentad2e7b92017-09-14 20:06:42 -07002446 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2447 // possible
2448 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2449 *input != AUDIO_IO_HANDLE_NONE) {
2450 ssize_t index = mInputs.indexOfKey(*input);
2451 if (index < 0) {
2452 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2453 status = BAD_VALUE;
2454 goto error;
2455 }
2456 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002457 RecordClientVector clients = inputDesc->getClientsForSession(session);
2458 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002459 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2460 status = BAD_VALUE;
2461 goto error;
2462 }
2463 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2464 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002465 // corresponds to a new client and is only permitted from the same UID.
2466 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002467 if (clients.size() > 1) {
2468 for (const auto& client : clients) {
2469 // The client map is ordered by key values (portId) and portIds are allocated
2470 // incrementaly. So the first client in this list is the one opened by audio flinger
2471 // when the mmap stream is created and should be ignored as it does not correspond
2472 // to an actual client
2473 if (client == *clients.cbegin()) {
2474 continue;
2475 }
2476 if (uid != client->uid() && !client->isSilenced()) {
2477 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2478 uid, client->portId(), client->uid());
2479 status = INVALID_OPERATION;
2480 goto error;
2481 }
Eric Laurent331679c2018-04-16 17:03:16 -07002482 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002483 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002484 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002485 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002486
Eric Laurentfecbceb2021-02-09 14:46:43 +01002487 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002488 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002489 }
2490
2491 *input = AUDIO_IO_HANDLE_NONE;
2492 *inputType = API_INPUT_INVALID;
2493
Francois Gaffie716e1432019-01-14 16:58:59 +01002494 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2495 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2496 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002497 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002498 ALOGW("%s could not find input mix for attr %s",
2499 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002500 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002501 }
jiabinc1de2df2019-05-07 14:26:40 -07002502 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2503 String8(attr->tags + strlen("addr=")),
2504 AUDIO_FORMAT_DEFAULT);
2505 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002506 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002507 __func__, attributes.source, attributes.tags);
2508 status = BAD_VALUE;
2509 goto error;
2510 }
2511
Kevin Rocard25f9b052019-02-27 15:08:54 -08002512 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2513 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2514 } else {
2515 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2516 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002517 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002518 if (explicitRoutingDevice != nullptr) {
2519 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002520 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002521 // Prevent from storing invalid requested device id in clients
2522 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002523 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002524 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2525 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002526 }
François Gaffie11d30102018-11-02 16:09:09 +01002527 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002528 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002529 status = BAD_VALUE;
2530 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002531 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002532 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2533 *inputType = API_INPUT_MIX_CAPTURE;
2534 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002535 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2536 // there is an external policy, but this input is attached to a mix of recorders,
2537 // meaning it receives audio injected into the framework, so the recorder doesn't
2538 // know about it and is therefore considered "legacy"
2539 *inputType = API_INPUT_LEGACY;
2540 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002541 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002542 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002543 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002544 } else {
2545 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002546 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002547
Eric Laurent599c7582015-12-07 18:05:55 -08002548 }
2549
François Gaffiec005e562018-11-06 15:04:49 +01002550 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002551 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002552 status = INVALID_OPERATION;
2553 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002554 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002555
Eric Laurent8f42ea12018-08-08 09:08:25 -07002556exit:
2557
François Gaffiec005e562018-11-06 15:04:49 +01002558 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2559 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002560
Francois Gaffie716e1432019-01-14 16:58:59 +01002561 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002562 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002563 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002564
Mikhail Naganov2996f672019-04-18 12:29:59 -07002565 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002566 requestedDeviceId, attributes.source, flags,
2567 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002568 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002569 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002570
2571 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2572 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002573
Eric Laurent599c7582015-12-07 18:05:55 -08002574 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002575
2576error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002577 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002578}
2579
2580
François Gaffie11d30102018-11-02 16:09:09 +01002581audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002582 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002583 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002584 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002585 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002586 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002587{
2588 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002589 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002590 bool isSoundTrigger = false;
2591
François Gaffiec005e562018-11-06 15:04:49 +01002592 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002593 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2594 if (index >= 0) {
2595 input = mSoundTriggerSessions.valueFor(session);
2596 isSoundTrigger = true;
2597 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2598 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2599 } else {
2600 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002601 }
François Gaffiec005e562018-11-06 15:04:49 +01002602 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002603 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002604 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002605 }
2606
Carter Hsua3abb402021-10-26 11:11:20 +08002607 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2608 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2609 }
2610
Andy Hungf129b032015-04-07 13:45:50 -07002611 // find a compatible input profile (not necessarily identical in parameters)
2612 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002613 // sampling rate and flags may be updated by getInputProfile
2614 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2615 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002616 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002617 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002618 audio_input_flags_t profileFlags = flags;
2619 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002620 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002621 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002622 profileFlags);
2623 if (profile != 0) {
2624 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002625 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2626 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002627 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002628 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2629 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002630 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002631 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002632 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002633 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002634 }
Eric Laurente552edb2014-03-10 17:42:56 -07002635 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002636 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002637 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002638 if (samplingRate == 0) {
2639 samplingRate = profileSamplingRate;
2640 }
Eric Laurente552edb2014-03-10 17:42:56 -07002641
Eric Laurent322b4d22015-04-03 15:57:54 -07002642 if (profile->getModuleHandle() == 0) {
2643 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002644 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002645 }
2646
Eric Laurentec376dc2021-04-08 20:41:22 +02002647 // Reuse an already opened input if a client with the same session ID already exists
2648 // on that input
2649 for (size_t i = 0; i < mInputs.size(); i++) {
2650 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2651 if (desc->mProfile != profile) {
2652 continue;
2653 }
2654 RecordClientVector clients = desc->clientsList();
2655 for (const auto &client : clients) {
2656 if (session == client->session()) {
2657 return desc->mIoHandle;
2658 }
2659 }
2660 }
2661
Eric Laurent3974e3b2017-12-07 17:58:43 -08002662 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002663 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002664 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002665 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002666 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002667 continue;
2668 }
2669 // if sound trigger, reuse input if used by other sound trigger on same session
2670 // else
2671 // reuse input if active client app is not in IDLE state
2672 //
2673 RecordClientVector clients = desc->clientsList();
2674 bool doClose = false;
2675 for (const auto& client : clients) {
2676 if (isSoundTrigger != client->isSoundTrigger()) {
2677 continue;
2678 }
2679 if (client->isSoundTrigger()) {
2680 if (session == client->session()) {
2681 return desc->mIoHandle;
2682 }
2683 continue;
2684 }
2685 if (client->active() && client->appState() != APP_STATE_IDLE) {
2686 return desc->mIoHandle;
2687 }
2688 doClose = true;
2689 }
2690 if (doClose) {
2691 closeInput(desc->mIoHandle);
2692 } else {
2693 i++;
2694 }
2695 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002696 }
2697
Eric Laurentfe231122017-11-17 17:48:06 -08002698 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002699
Eric Laurentfe231122017-11-17 17:48:06 -08002700 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2701 lConfig.sample_rate = profileSamplingRate;
2702 lConfig.channel_mask = profileChannelMask;
2703 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002704
François Gaffie11d30102018-11-02 16:09:09 +01002705 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002706
2707 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002708 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002709 (profileSamplingRate != lConfig.sample_rate) ||
2710 !audio_formats_match(profileFormat, lConfig.format) ||
2711 (profileChannelMask != lConfig.channel_mask)) {
2712 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002713 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002714 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002715 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002716 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002717 }
Eric Laurent599c7582015-12-07 18:05:55 -08002718 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002719 }
2720
Eric Laurentc722f302014-12-10 11:21:49 -08002721 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002722
Eric Laurent599c7582015-12-07 18:05:55 -08002723 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002724 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002725
Eric Laurent599c7582015-12-07 18:05:55 -08002726 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002727}
2728
Eric Laurent4eb58f12018-12-07 16:41:02 -08002729status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002730{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002731 ALOGV("%s portId %d", __FUNCTION__, portId);
2732
2733 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2734 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002735 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002736 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002737 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002738 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002739 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002740 if (client->active()) {
2741 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2742 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002743 }
2744
Eric Laurent8f42ea12018-08-08 09:08:25 -07002745 audio_session_t session = client->session();
2746
Eric Laurent4eb58f12018-12-07 16:41:02 -08002747 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002748
Eric Laurent4eb58f12018-12-07 16:41:02 -08002749 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002750
Eric Laurent4eb58f12018-12-07 16:41:02 -08002751 status_t status = inputDesc->start();
2752 if (status != NO_ERROR) {
2753 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002754 }
Eric Laurente552edb2014-03-10 17:42:56 -07002755
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002756 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002757 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002758 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002759
Eric Laurent8f42ea12018-08-08 09:08:25 -07002760 // indicate active capture to sound trigger service if starting capture from a mic on
2761 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002762 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002763 if (device != nullptr) {
2764 status = setInputDevice(input, device, true /* force */);
2765 } else {
2766 ALOGW("%s no new input device can be found for descriptor %d",
2767 __FUNCTION__, inputDesc->getId());
2768 status = BAD_VALUE;
2769 }
Eric Laurente552edb2014-03-10 17:42:56 -07002770
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002771 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002772 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002773 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002774 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002775 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2776 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002777 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002778 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002779
François Gaffie11d30102018-11-02 16:09:09 +01002780 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2781 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002782 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002783 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002784 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002785
Eric Laurent8f42ea12018-08-08 09:08:25 -07002786 // automatically enable the remote submix output when input is started if not
2787 // used by a policy mix of type MIX_TYPE_RECORDERS
2788 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002789 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002790 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002791 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002792 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002793 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2794 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002795 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002796 if (address != "") {
2797 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2798 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002799 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002800 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002801 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002802 } else if (status != NO_ERROR) {
2803 // Restore client activity state.
2804 inputDesc->setClientActive(client, false);
2805 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002806 }
2807
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002808 ALOGV("%s input %d source = %d status = %d exit",
2809 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002810
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002811 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002812}
2813
Eric Laurent8fc147b2018-07-22 19:13:55 -07002814status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002815{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002816 ALOGV("%s portId %d", __FUNCTION__, portId);
2817
2818 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2819 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002820 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002821 return BAD_VALUE;
2822 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002823 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002824 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002825 if (!client->active()) {
2826 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002827 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002828 }
Carter Hsue6139d52021-07-08 10:30:20 +08002829 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002830 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002831
Eric Laurent8f42ea12018-08-08 09:08:25 -07002832 inputDesc->stop();
2833 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002834 auto current_source = inputDesc->source();
2835 setInputDevice(input, getNewInputDevice(inputDesc),
2836 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002837 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002838 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002839 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002840 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002841 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2842 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002843 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002844 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002845
2846 // automatically disable the remote submix output when input is stopped if not
2847 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002848 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002849 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002850 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002851 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002852 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2853 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002854 }
2855 if (address != "") {
2856 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2857 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002858 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002859 }
2860 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002861 resetInputDevice(input);
2862
2863 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2864 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002865 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2866 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002867 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002868 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002869 }
2870 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002871 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002872 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002873}
2874
Eric Laurent8fc147b2018-07-22 19:13:55 -07002875void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002876{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002877 ALOGV("%s portId %d", __FUNCTION__, portId);
2878
2879 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2880 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002881 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002882 return;
2883 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002884 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002885 audio_io_handle_t input = inputDesc->mIoHandle;
2886
Eric Laurent8f42ea12018-08-08 09:08:25 -07002887 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002888
Andy Hung39efb7a2018-09-26 15:39:28 -07002889 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002890
Andy Hung39efb7a2018-09-26 15:39:28 -07002891 if (inputDesc->getClientCount() > 0) {
2892 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002893 return;
2894 }
2895
Eric Laurent05b90f82014-08-27 15:32:29 -07002896 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002897 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002898 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002899}
2900
Eric Laurent8f42ea12018-08-08 09:08:25 -07002901void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002902{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002903 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002904
2905 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002906 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002907 }
2908}
2909
Eric Laurent8f42ea12018-08-08 09:08:25 -07002910void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2911{
2912 stopInput(portId);
2913 releaseInput(portId);
2914}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002915
Eric Laurent0dd51852019-04-19 18:18:58 -07002916void AudioPolicyManager::checkCloseInputs() {
2917 // After connecting or disconnecting an input device, close input if:
2918 // - it has no client (was just opened to check profile) OR
2919 // - none of its supported devices are connected anymore OR
2920 // - one of its clients cannot be routed to one of its supported
2921 // devices anymore. Otherwise update device selection
2922 std::vector<audio_io_handle_t> inputsToClose;
2923 for (size_t i = 0; i < mInputs.size(); i++) {
2924 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2925 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002926 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002927 inputsToClose.push_back(mInputs.keyAt(i));
2928 } else {
2929 bool close = false;
2930 for (const auto& client : input->clientsList()) {
2931 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002932 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002933 if (!input->supportedDevices().contains(device)) {
2934 close = true;
2935 break;
2936 }
2937 }
2938 if (close) {
2939 inputsToClose.push_back(mInputs.keyAt(i));
2940 } else {
2941 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2942 }
2943 }
2944 }
2945
2946 for (const audio_io_handle_t handle : inputsToClose) {
2947 ALOGV("%s closing input %d", __func__, handle);
2948 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002949 }
Eric Laurentd4692962014-05-05 18:13:44 -07002950}
2951
François Gaffie251c7f02018-11-07 10:41:08 +01002952void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002953{
2954 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002955 if (indexMin < 0 || indexMax < 0) {
2956 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2957 return;
2958 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002959 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002960
2961 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002962 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2963 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002964 continue;
2965 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002966 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002967 }
Eric Laurente552edb2014-03-10 17:42:56 -07002968}
2969
Eric Laurente0720872014-03-11 09:30:41 -07002970status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002971 int index,
2972 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002973{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002974 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002975 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2976 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2977 return NO_ERROR;
2978 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002979 ALOGV("%s: stream %s attributes=%s", __func__,
2980 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002981 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002982}
2983
Eric Laurente0720872014-03-11 09:30:41 -07002984status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002985 int *index,
2986 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002987{
François Gaffiec005e562018-11-06 15:04:49 +01002988 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2989 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002990 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002991 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002992 deviceTypes = mEngine->getOutputDevicesForStream(
2993 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002994 }
jiabin9a3361e2019-10-01 09:38:30 -07002995 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002996}
2997
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002998status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002999 int index,
3000 audio_devices_t device)
3001{
3002 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003003 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3004 if (group == VOLUME_GROUP_NONE) {
3005 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003006 return BAD_VALUE;
3007 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003008 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003009 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003010 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003011 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003012 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3013 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3014 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3015 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003016 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3017
3018 status = setVolumeCurveIndex(index, device, curves);
3019 if (status != NO_ERROR) {
3020 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3021 return status;
3022 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003023
jiabin9a3361e2019-10-01 09:38:30 -07003024 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003025 auto curCurvAttrs = curves.getAttributes();
3026 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3027 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003028 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003029 } else if (!curves.getStreamTypes().empty()) {
3030 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003031 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003032 } else {
3033 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3034 return BAD_VALUE;
3035 }
jiabin9a3361e2019-10-01 09:38:30 -07003036 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3037 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003038
François Gaffiecfe17322018-11-07 13:41:29 +01003039 // update volume on all outputs and streams matching the following:
3040 // - The requested stream (or a stream matching for volume control) is active on the output
3041 // - The device (or devices) selected by the engine for this stream includes
3042 // the requested device
3043 // - For non default requested device, currently selected device on the output is either the
3044 // requested device or one of the devices selected by the engine for this stream
3045 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3046 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003047 for (size_t i = 0; i < mOutputs.size(); i++) {
3048 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003049 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003050
jiabin9a3361e2019-10-01 09:38:30 -07003051 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3052 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003053 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003054
3055 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003056 continue;
3057 }
3058 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3059 curDevices.find(device) == curDevices.end()) {
3060 continue;
3061 }
3062 bool applyVolume = false;
3063 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3064 curSrcDevices.insert(device);
3065 applyVolume = (curSrcDevices.find(
3066 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3067 } else {
3068 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3069 }
3070 if (!applyVolume) {
3071 continue; // next output
3072 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003073 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3074 // If a higher priority strategy is active, and the output is routed to a device with a
3075 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003076 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003077 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003078 // If the volume source is active with higher priority source, ensure at least Sw Muted
3079 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003080 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3081 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3082 false /*preferredDevice*/);
3083 if (activeClients.empty()) {
3084 continue;
3085 }
3086 bool isPreempted = false;
3087 bool isHigherPriority = productStrategy < strategy;
3088 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003089 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003090 ALOGV("%s: Strategy=%d (\nrequester:\n"
3091 " group %d, volumeGroup=%d attributes=%s)\n"
3092 " higher priority source active:\n"
3093 " volumeGroup=%d attributes=%s) \n"
3094 " on output %zu, bailing out", __func__, productStrategy,
3095 group, group, toString(attributes).c_str(),
3096 client->volumeSource(), toString(client->attributes()).c_str(), i);
3097 applyVolume = false;
3098 isPreempted = true;
3099 break;
3100 }
3101 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003102 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003103 applyVolume = true;
3104 }
3105 }
3106 if (isPreempted || applyVolume) {
3107 break;
3108 }
3109 }
3110 if (!applyVolume) {
3111 continue; // next output
3112 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003113 }
François Gaffieed91f582020-01-31 10:35:37 +01003114 //FIXME: workaround for truncated touch sounds
3115 // delayed volume change for system stream to be removed when the problem is
3116 // handled by system UI
3117 status_t volStatus = checkAndSetVolume(
3118 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003119 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003120 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3121 if (volStatus != NO_ERROR) {
3122 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003123 }
3124 }
François Gaffiecfe17322018-11-07 13:41:29 +01003125 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3126 return status;
3127}
3128
François Gaffieaaac0fd2018-11-22 17:56:39 +01003129status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003130 audio_devices_t device,
3131 IVolumeCurves &volumeCurves)
3132{
3133 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3134 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003135 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3136 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003137 (index > volumeCurves.getVolumeIndexMax())) {
3138 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3139 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3140 return BAD_VALUE;
3141 }
3142 if (!audio_is_output_device(device)) {
3143 return BAD_VALUE;
3144 }
3145
3146 // Force max volume if stream cannot be muted
3147 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3148
François Gaffieaaac0fd2018-11-22 17:56:39 +01003149 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003150 volumeCurves.addCurrentVolumeIndex(device, index);
3151 return NO_ERROR;
3152}
3153
3154status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3155 int &index,
3156 audio_devices_t device)
3157{
3158 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3159 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003160 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003161 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003162 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3163 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003164 }
jiabin9a3361e2019-10-01 09:38:30 -07003165 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003166}
3167
3168status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3169 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003170 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003171{
jiabin9a3361e2019-10-01 09:38:30 -07003172 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003173 return BAD_VALUE;
3174 }
jiabin9a3361e2019-10-01 09:38:30 -07003175 index = curves.getVolumeIndex(deviceTypes);
3176 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003177 return NO_ERROR;
3178}
3179
3180status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3181 int &index)
3182{
3183 index = getVolumeCurves(attr).getVolumeIndexMin();
3184 return NO_ERROR;
3185}
3186
3187status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3188 int &index)
3189{
3190 index = getVolumeCurves(attr).getVolumeIndexMax();
3191 return NO_ERROR;
3192}
3193
Eric Laurent36829f92017-04-07 19:04:42 -07003194audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003195{
3196 // select one output among several suitable for global effects.
3197 // The priority is as follows:
3198 // 1: An offloaded output. If the effect ends up not being offloadable,
3199 // AudioFlinger will invalidate the track and the offloaded output
3200 // will be closed causing the effect to be moved to a PCM output.
3201 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003202 // 3: The primary output
3203 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003204
François Gaffiec005e562018-11-06 15:04:49 +01003205 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3206 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003207 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003208
Eric Laurent36829f92017-04-07 19:04:42 -07003209 if (outputs.size() == 0) {
3210 return AUDIO_IO_HANDLE_NONE;
3211 }
Eric Laurente552edb2014-03-10 17:42:56 -07003212
Eric Laurent36829f92017-04-07 19:04:42 -07003213 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3214 bool activeOnly = true;
3215
3216 while (output == AUDIO_IO_HANDLE_NONE) {
3217 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3218 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3219 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3220
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003221 for (audio_io_handle_t output : outputs) {
3222 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003223 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003224 continue;
3225 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003226 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3227 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003228 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003229 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003230 }
3231 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003232 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003233 }
3234 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003235 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003236 }
3237 }
3238 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3239 output = outputOffloaded;
3240 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3241 output = outputDeepBuffer;
3242 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3243 output = outputPrimary;
3244 } else {
3245 output = outputs[0];
3246 }
3247 activeOnly = false;
3248 }
3249
3250 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003251 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003252 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3253 mMusicEffectOutput = output;
3254 }
3255
3256 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003257 return output;
3258}
3259
Eric Laurent36829f92017-04-07 19:04:42 -07003260audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3261{
3262 return selectOutputForMusicEffects();
3263}
3264
Eric Laurente0720872014-03-11 09:30:41 -07003265status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003266 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003267 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003268 int session,
3269 int id)
3270{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003271 if (session != AUDIO_SESSION_DEVICE) {
3272 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003273 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003274 index = mInputs.indexOfKey(io);
3275 if (index < 0) {
3276 ALOGW("registerEffect() unknown io %d", io);
3277 return INVALID_OPERATION;
3278 }
Eric Laurente552edb2014-03-10 17:42:56 -07003279 }
3280 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003281 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3282 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3283 || strategy == PRODUCT_STRATEGY_NONE));
3284 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003285}
3286
Eric Laurentc241b0d2018-11-28 09:08:49 -08003287status_t AudioPolicyManager::unregisterEffect(int id)
3288{
3289 if (mEffects.getEffect(id) == nullptr) {
3290 return INVALID_OPERATION;
3291 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003292 if (mEffects.isEffectEnabled(id)) {
3293 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3294 setEffectEnabled(id, false);
3295 }
3296 return mEffects.unregisterEffect(id);
3297}
3298
3299status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3300{
3301 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3302 if (effect == nullptr) {
3303 return INVALID_OPERATION;
3304 }
3305
3306 status_t status = mEffects.setEffectEnabled(id, enabled);
3307 if (status == NO_ERROR) {
3308 mInputs.trackEffectEnabled(effect, enabled);
3309 }
3310 return status;
3311}
3312
Eric Laurent6c796322019-04-09 14:13:17 -07003313
3314status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3315{
3316 mEffects.moveEffects(ids, io);
3317 return NO_ERROR;
3318}
3319
Eric Laurentc75307b2015-03-17 15:29:32 -07003320bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3321{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003322 auto vs = toVolumeSource(stream, false);
3323 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003324}
3325
3326bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3327{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003328 auto vs = toVolumeSource(stream, false);
3329 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003330}
3331
Eric Laurente0720872014-03-11 09:30:41 -07003332bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003333{
3334 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003335 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003336 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003337 return true;
3338 }
3339 }
3340 return false;
3341}
3342
Eric Laurent275e8e92014-11-30 15:14:47 -08003343// Register a list of custom mixes with their attributes and format.
3344// When a mix is registered, corresponding input and output profiles are
3345// added to the remote submix hw module. The profile contains only the
3346// parameters (sampling rate, format...) specified by the mix.
3347// The corresponding input remote submix device is also connected.
3348//
3349// When a remote submix device is connected, the address is checked to select the
3350// appropriate profile and the corresponding input or output stream is opened.
3351//
3352// When capture starts, getInputForAttr() will:
3353// - 1 look for a mix matching the address passed in attribtutes tags if any
3354// - 2 if none found, getDeviceForInputSource() will:
3355// - 2.1 look for a mix matching the attributes source
3356// - 2.2 if none found, default to device selection by policy rules
3357// At this time, the corresponding output remote submix device is also connected
3358// and active playback use cases can be transferred to this mix if needed when reconnecting
3359// after AudioTracks are invalidated
3360//
3361// When playback starts, getOutputForAttr() will:
3362// - 1 look for a mix matching the address passed in attribtutes tags if any
3363// - 2 if none found, look for a mix matching the attributes usage
3364// - 3 if none found, default to device and output selection by policy rules.
3365
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003366status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003367{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003368 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3369 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003370 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003371 sp<HwModule> rSubmixModule;
3372 // examine each mix's route type
3373 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003374 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003375 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3376 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3377 ALOGE("Unsupported Policy Mix %zu of %zu: "
3378 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3379 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003380 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003381 break;
3382 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003383 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3384 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003385 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003386 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3387 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003388 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003389 rSubmixModule = mHwModules.getModuleFromName(
3390 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3391 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003392 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003393 i);
3394 res = INVALID_OPERATION;
3395 break;
3396 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003397 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003398
Eric Laurent97ac8712018-07-27 18:59:02 -07003399 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003400 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003401 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003402 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003403 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3404 } else {
3405 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3406 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003407 }
François Gaffie036e1e92015-03-19 10:16:24 +01003408
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003409 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003410 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003411 res = INVALID_OPERATION;
3412 break;
3413 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003414 audio_config_t outputConfig = mix.mFormat;
3415 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003416 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3417 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003418 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3419 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003420 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003421 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003422 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003423 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003424
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003425 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003426 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3427 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3428 ALOGE("Failed to set remote submix device available, type %u, address %s",
3429 mix.mDeviceType, address.string());
3430 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003431 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003432 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3433 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003434 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003435 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003436 i, mixes.size(), type, address.string());
3437
3438 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3439 mix.mDeviceType, mix.mDeviceAddress,
3440 String8(), AUDIO_FORMAT_DEFAULT);
3441 if (device == nullptr) {
3442 res = INVALID_OPERATION;
3443 break;
3444 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003445
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003446 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003447 // First try to find an already opened output supporting the device
3448 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003449 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003450
Eric Laurentc529cf62020-04-17 18:19:10 -07003451 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003452 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003453 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3454 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003455 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003456 } else {
3457 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003458 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003459 }
3460 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003461 // If no output found, try to find a direct output profile supporting the device
3462 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3463 sp<HwModule> module = mHwModules[i];
3464 for (size_t j = 0;
3465 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3466 j++) {
3467 sp<IOProfile> profile = module->getOutputProfiles()[j];
3468 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3469 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3470 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3471 address.string());
3472 res = INVALID_OPERATION;
3473 } else {
3474 foundOutput = true;
3475 }
3476 }
3477 }
3478 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003479 if (res != NO_ERROR) {
3480 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003481 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003482 res = INVALID_OPERATION;
3483 break;
3484 } else if (!foundOutput) {
3485 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003486 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003487 res = INVALID_OPERATION;
3488 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003489 } else {
3490 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003491 }
Eric Laurentc722f302014-12-10 11:21:49 -08003492 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003493 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003494 if (res != NO_ERROR) {
3495 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003496 } else if (checkOutputs) {
3497 checkForDeviceAndOutputChanges();
3498 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003499 }
3500 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003501}
3502
3503status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3504{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003505 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003506 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003507 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003508 sp<HwModule> rSubmixModule;
3509 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003510 for (const auto& mix : mixes) {
3511 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003512
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003513 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003514 rSubmixModule = mHwModules.getModuleFromName(
3515 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3516 if (rSubmixModule == 0) {
3517 res = INVALID_OPERATION;
3518 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003519 }
3520 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003521
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003522 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003523
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003524 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003525 res = INVALID_OPERATION;
3526 continue;
3527 }
3528
Kevin Rocard04ed0462019-05-02 17:53:24 -07003529 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3530 if (getDeviceConnectionState(device, address.string()) ==
3531 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3532 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3533 address.string(), "remote-submix",
3534 AUDIO_FORMAT_DEFAULT);
3535 if (res != OK) {
3536 ALOGE("Error making RemoteSubmix device unavailable for mix "
3537 "with type %d, address %s", device, address.string());
3538 }
3539 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003540 }
jiabin5740f082019-08-19 15:08:30 -07003541 rSubmixModule->removeOutputProfile(address.c_str());
3542 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003543
Kevin Rocard153f92d2018-12-18 18:33:28 -08003544 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003545 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003546 res = INVALID_OPERATION;
3547 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003548 } else {
3549 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003550 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003551 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003552 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003553 if (res == NO_ERROR && checkOutputs) {
3554 checkForDeviceAndOutputChanges();
3555 updateCallAndOutputRouting();
3556 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003557 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003558}
3559
Mikhail Naganov100f0122018-11-29 11:22:16 -08003560void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3561{
3562 size_t i = 0;
3563 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3564 for (const auto& fmt : mManualSurroundFormats) {
3565 if (i++ != 0) dst->append(", ");
3566 std::string sfmt;
3567 FormatConverter::toString(fmt, sfmt);
3568 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3569 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3570 }
3571}
3572
Eric Laurentc529cf62020-04-17 18:19:10 -07003573// Returns true if all devices types match the predicate and are supported by one HW module
3574bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003575 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003576 std::function<bool(audio_devices_t)> predicate,
3577 const char *context) {
3578 for (size_t i = 0; i < devices.size(); i++) {
3579 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003580 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003581 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003582 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003583 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003584 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003585 return false;
3586 }
3587 }
3588 return true;
3589}
3590
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003591status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003592 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003593 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003594 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3595 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003596 }
3597 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003598 if (res != NO_ERROR) {
3599 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3600 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003601 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003602
3603 checkForDeviceAndOutputChanges();
3604 updateCallAndOutputRouting();
3605
3606 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003607}
3608
3609status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3610 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003611 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3612 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003613 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003614 __FUNCTION__, uid);
3615 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003616 }
3617
Eric Laurentc529cf62020-04-17 18:19:10 -07003618 checkForDeviceAndOutputChanges();
3619 updateCallAndOutputRouting();
3620
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003621 return res;
3622}
3623
Eric Laurent2517af32020-11-25 15:31:27 +01003624
jiabin0a488932020-08-07 17:32:40 -07003625status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3626 device_role_t role,
3627 const AudioDeviceTypeAddrVector &devices) {
3628 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3629 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003630
Eric Laurentc529cf62020-04-17 18:19:10 -07003631 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003632 return BAD_VALUE;
3633 }
jiabin0a488932020-08-07 17:32:40 -07003634 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003635 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003636 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3637 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003638 return status;
3639 }
3640
3641 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003642
3643 bool forceVolumeReeval = false;
3644 // FIXME: workaround for truncated touch sounds
3645 // to be removed when the problem is handled by system UI
3646 uint32_t delayMs = 0;
3647 if (strategy == mCommunnicationStrategy) {
3648 forceVolumeReeval = true;
3649 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3650 updateInputRouting();
3651 }
3652 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003653
3654 return NO_ERROR;
3655}
3656
3657void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3658{
3659 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003660 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003661 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003662 // Only apply special touch sound delay once
3663 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003664 }
3665 for (size_t i = 0; i < mOutputs.size(); i++) {
3666 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3667 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003668 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3669 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003670 // As done in setDeviceConnectionState, we could also fix default device issue by
3671 // preventing the force re-routing in case of default dev that distinguishes on address.
3672 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003673 bool forceRouting = !newDevices.isEmpty();
3674 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3675 true /*requiresMuteCheck*/,
3676 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003677 // Only apply special touch sound delay once
3678 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003679 }
3680 if (forceVolumeReeval && !newDevices.isEmpty()) {
3681 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3682 }
3683 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003684 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003685}
3686
Eric Laurent2517af32020-11-25 15:31:27 +01003687void AudioPolicyManager::updateInputRouting() {
3688 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303689 // Skip for hotword recording as the input device switch
3690 // is handled within sound trigger HAL
3691 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3692 continue;
3693 }
Eric Laurent2517af32020-11-25 15:31:27 +01003694 auto newDevice = getNewInputDevice(activeDesc);
3695 // Force new input selection if the new device can not be reached via current input
3696 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3697 setInputDevice(activeDesc->mIoHandle, newDevice);
3698 } else {
3699 closeInput(activeDesc->mIoHandle);
3700 }
3701 }
3702}
3703
jiabin0a488932020-08-07 17:32:40 -07003704status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3705 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003706{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003707 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003708
jiabin0a488932020-08-07 17:32:40 -07003709 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003710 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003711 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3712 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003713 return status;
3714 }
3715
3716 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003717
3718 bool forceVolumeReeval = false;
3719 // FIXME: workaround for truncated touch sounds
3720 // to be removed when the problem is handled by system UI
3721 uint32_t delayMs = 0;
3722 if (strategy == mCommunnicationStrategy) {
3723 forceVolumeReeval = true;
3724 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3725 updateInputRouting();
3726 }
3727 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003728
3729 return NO_ERROR;
3730}
3731
jiabin0a488932020-08-07 17:32:40 -07003732status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3733 device_role_t role,
3734 AudioDeviceTypeAddrVector &devices) {
3735 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003736}
3737
Jiabin Huang3b98d322020-09-03 17:54:16 +00003738status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3739 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3740 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3741 dumpAudioDeviceTypeAddrVector(devices).c_str());
3742
Mikhail Naganov55773032020-10-01 15:08:13 -07003743 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003744 return BAD_VALUE;
3745 }
3746 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3747 ALOGW_IF(status != NO_ERROR,
3748 "Engine could not set preferred devices %s for audio source %d role %d",
3749 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3750
3751 return status;
3752}
3753
3754status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3755 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3756 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3757 dumpAudioDeviceTypeAddrVector(devices).c_str());
3758
Mikhail Naganov55773032020-10-01 15:08:13 -07003759 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003760 return BAD_VALUE;
3761 }
3762 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3763 ALOGW_IF(status != NO_ERROR,
3764 "Engine could not add preferred devices %s for audio source %d role %d",
3765 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3766
Eric Laurent2517af32020-11-25 15:31:27 +01003767 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003768 return status;
3769}
3770
3771status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3772 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3773{
3774 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3775 dumpAudioDeviceTypeAddrVector(devices).c_str());
3776
Mikhail Naganov55773032020-10-01 15:08:13 -07003777 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003778 return BAD_VALUE;
3779 }
3780
3781 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3782 audioSource, role, devices);
3783 ALOGW_IF(status != NO_ERROR,
3784 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3785
Eric Laurent2517af32020-11-25 15:31:27 +01003786 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003787 return status;
3788}
3789
3790status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3791 device_role_t role) {
3792 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3793
3794 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3795 ALOGW_IF(status != NO_ERROR,
3796 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3797
Eric Laurent2517af32020-11-25 15:31:27 +01003798 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003799 return status;
3800}
3801
3802status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3803 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3804 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3805}
3806
Oscar Azucena90e77632019-11-27 17:12:28 -08003807status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003808 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003809 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003810 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3811 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003812 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003813 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3814 if (status != NO_ERROR) {
3815 ALOGE("%s() could not set device affinity for userId %d",
3816 __FUNCTION__, userId);
3817 return status;
3818 }
3819
3820 // reevaluate outputs for all devices
3821 checkForDeviceAndOutputChanges();
3822 updateCallAndOutputRouting();
3823
3824 return NO_ERROR;
3825}
3826
3827status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003828 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003829 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3830 if (status != NO_ERROR) {
3831 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3832 __FUNCTION__, userId);
3833 return status;
3834 }
3835
3836 // reevaluate outputs for all devices
3837 checkForDeviceAndOutputChanges();
3838 updateCallAndOutputRouting();
3839
3840 return NO_ERROR;
3841}
3842
Andy Hungc29d82b2018-10-05 12:23:17 -07003843void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003844{
Andy Hungc29d82b2018-10-05 12:23:17 -07003845 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003846 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003847 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003848 std::string stateLiteral;
3849 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003850 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003851 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3852 "communications", "media", "record", "dock", "system",
3853 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3854 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3855 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003856 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3857 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3858 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3859 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3860 dst->append(" (MANUAL: ");
3861 dumpManualSurroundFormats(dst);
3862 dst->append(")");
3863 }
3864 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003865 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003866 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3867 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003868 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003869 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003870
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003871 dst->append("\n");
3872 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3873 dst->append("\n");
3874 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003875 mHwModulesAll.dump(dst);
3876 mOutputs.dump(dst);
3877 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003878 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003879 mAudioPatches.dump(dst);
3880 mPolicyMixes.dump(dst);
3881 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003882
Kevin Rocardb99cc752019-03-21 20:52:24 -07003883 dst->appendFormat(" AllowedCapturePolicies:\n");
3884 for (auto& policy : mAllowedCapturePolicies) {
3885 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3886 }
3887
François Gaffiec005e562018-11-06 15:04:49 +01003888 dst->appendFormat("\nPolicy Engine dump:\n");
3889 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003890}
3891
3892status_t AudioPolicyManager::dump(int fd)
3893{
3894 String8 result;
3895 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003896 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003897 return NO_ERROR;
3898}
3899
Kevin Rocardb99cc752019-03-21 20:52:24 -07003900status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3901{
3902 mAllowedCapturePolicies[uid] = capturePolicy;
3903 return NO_ERROR;
3904}
3905
Eric Laurente552edb2014-03-10 17:42:56 -07003906// This function checks for the parameters which can be offloaded.
3907// This can be enhanced depending on the capability of the DSP and policy
3908// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003909audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003910{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003911 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003912 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003913 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003914 offloadInfo.format,
3915 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3916 offloadInfo.has_video);
3917
jiabin2b9d5a12021-12-10 01:06:29 +00003918 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003919 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003920 }
3921
3922 // See if there is a profile to support this.
3923 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003924 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003925 offloadInfo.sample_rate,
3926 offloadInfo.format,
3927 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003928 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3929 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003930 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3931 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3932 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003933 if (profile == nullptr) {
3934 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3935 }
3936 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3937 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3938 }
3939 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003940}
3941
Michael Chana94fbb22018-04-24 14:31:19 +10003942bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3943 const audio_attributes_t& attributes) {
3944 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003945 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003946 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3947 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003948 config.sample_rate,
3949 config.format,
3950 config.channel_mask,
3951 output_flags,
3952 true /* directOnly */);
3953 ALOGV("%s() profile %sfound with name: %s, "
3954 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3955 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003956 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003957 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003958
3959 // also try the MSD module if compatible profile not found
3960 if (profile == nullptr) {
3961 profile = getMsdProfileForOutput(outputDevices,
3962 config.sample_rate,
3963 config.format,
3964 config.channel_mask,
3965 output_flags,
3966 true /* directOnly */);
3967 ALOGV("%s() MSD profile %sfound with name: %s, "
3968 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3969 __FUNCTION__, profile != 0 ? "" : "NOT ",
3970 (profile != 0 ? profile->getTagName().c_str() : "null"),
3971 config.sample_rate, config.format, config.channel_mask, output_flags);
3972 }
3973 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003974}
3975
jiabin2b9d5a12021-12-10 01:06:29 +00003976bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3977 bool durationIgnored) {
3978 if (mMasterMono) {
3979 return false; // no offloading if mono is set.
3980 }
3981
3982 // Check if offload has been disabled
3983 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3984 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3985 return false;
3986 }
3987
3988 // Check if stream type is music, then only allow offload as of now.
3989 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3990 {
3991 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3992 return false;
3993 }
3994
3995 //TODO: enable audio offloading with video when ready
3996 const bool allowOffloadWithVideo =
3997 property_get_bool("audio.offload.video", false /* default_value */);
3998 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3999 ALOGV("%s: has_video == true, returning false", __func__);
4000 return false;
4001 }
4002
4003 //If duration is less than minimum value defined in property, return false
4004 const int min_duration_secs = property_get_int32(
4005 "audio.offload.min.duration.secs", -1 /* default_value */);
4006 if (!durationIgnored) {
4007 if (min_duration_secs >= 0) {
4008 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4009 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4010 __func__, min_duration_secs);
4011 return false;
4012 }
4013 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4014 ALOGV("%s: Offload denied by duration < default min(=%u)",
4015 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4016 return false;
4017 }
4018 }
4019
4020 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4021 // creating an offloaded track and tearing it down immediately after start when audioflinger
4022 // detects there is an active non offloadable effect.
4023 // FIXME: We should check the audio session here but we do not have it in this context.
4024 // This may prevent offloading in rare situations where effects are left active by apps
4025 // in the background.
4026 if (mEffects.isNonOffloadableEffectEnabled()) {
4027 return false;
4028 }
4029
4030 return true;
4031}
4032
4033audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4034 const audio_config_t *config) {
4035 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4036 offloadInfo.format = config->format;
4037 offloadInfo.sample_rate = config->sample_rate;
4038 offloadInfo.channel_mask = config->channel_mask;
4039 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4040 offloadInfo.has_video = false;
4041 offloadInfo.is_streaming = false;
4042 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4043
4044 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4045 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4046 audio_flags_to_audio_output_flags(attr->flags, &flags);
4047 // only retain flags that will drive compressed offload or passthrough
4048 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4049 if (offloadPossible) {
4050 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4051 }
4052 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4053
Dorin Drimusfae3c642022-03-17 18:36:30 +01004054 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004055 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004056 DeviceVector outputDevices = engineOutputDevices;
4057 // the MSD module checks for different conditions and output devices
4058 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4059 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4060 continue;
4061 }
4062 outputDevices = getMsdAudioOutDevices();
4063 }
jiabin2b9d5a12021-12-10 01:06:29 +00004064 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004065 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004066 config->sample_rate, nullptr /*updatedSamplingRate*/,
4067 config->format, nullptr /*updatedFormat*/,
4068 config->channel_mask, nullptr /*updatedChannelMask*/,
4069 flags)) {
4070 continue;
4071 }
4072 // reject profiles not corresponding to a device currently available
4073 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4074 continue;
4075 }
4076 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4077 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004078 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004079 != AUDIO_DIRECT_NOT_SUPPORTED) {
4080 // Already reports offload gapless supported. No need to report offload support.
4081 continue;
4082 }
4083 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4084 != AUDIO_OUTPUT_FLAG_NONE) {
4085 // If offload gapless is reported, no need to report offload support.
4086 directMode = (audio_direct_mode_t) ((directMode &
4087 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4088 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4089 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004090 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004091 }
4092 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004093 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004094 }
4095 }
4096 }
4097 return directMode;
4098}
4099
Dorin Drimusf2196d82022-01-03 12:11:18 +01004100status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4101 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004102 if (mEffects.isNonOffloadableEffectEnabled()) {
4103 return OK;
4104 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004105 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004106 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004107 if (status != OK) {
4108 return status;
4109 }
4110 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4111 if (devices.empty()) {
4112 return OK; // no output devices for the attributes
4113 }
4114
4115 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004116 // the MSD module checks for different conditions
4117 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4118 continue;
4119 }
4120 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4121 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004122 continue;
4123 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004124 // allow only profiles that support all the available and routed devices
4125 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004126 != devices.size()) {
4127 continue;
4128 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004129 audioProfilesVector.addAllValidProfiles(
4130 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004131 }
4132 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004133
4134 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4135 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4136 if (msdModule != nullptr) {
4137 if (msdHasPatchesToAllDevices(devices)) {
4138 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4139 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4140 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4141 continue;
4142 }
4143 audioProfilesVector.addAllValidProfiles(
4144 outputProfile->asAudioPort()->getAudioProfiles());
4145 }
4146 } else {
4147 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4148 }
4149 }
4150
Dorin Drimusf2196d82022-01-03 12:11:18 +01004151 return NO_ERROR;
4152}
4153
Eric Laurent6a94d692014-05-20 11:18:06 -07004154status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4155 audio_port_type_t type,
4156 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004157 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004158 unsigned int *generation)
4159{
jiabin19cdba52020-11-24 11:28:58 -08004160 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4161 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004162 return BAD_VALUE;
4163 }
4164 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004165 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004166 *num_ports = 0;
4167 }
4168
4169 size_t portsWritten = 0;
4170 size_t portsMax = *num_ports;
4171 *num_ports = 0;
4172 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004173 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4174 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004175 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004176 for (const auto& dev : mAvailableOutputDevices) {
4177 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004178 continue;
4179 }
4180 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004181 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004182 }
4183 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004184 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004185 }
4186 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004187 for (const auto& dev : mAvailableInputDevices) {
4188 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004189 continue;
4190 }
4191 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004192 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004193 }
4194 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004195 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004196 }
4197 }
4198 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4199 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4200 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4201 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4202 }
4203 *num_ports += mInputs.size();
4204 }
4205 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004206 size_t numOutputs = 0;
4207 for (size_t i = 0; i < mOutputs.size(); i++) {
4208 if (!mOutputs[i]->isDuplicated()) {
4209 numOutputs++;
4210 if (portsWritten < portsMax) {
4211 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4212 }
4213 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004214 }
Eric Laurent84c70242014-06-23 08:46:27 -07004215 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004216 }
4217 }
4218 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004219 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004220 return NO_ERROR;
4221}
4222
jiabin19cdba52020-11-24 11:28:58 -08004223status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004224{
Eric Laurent99fcae42018-05-17 16:59:18 -07004225 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4226 return BAD_VALUE;
4227 }
4228 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4229 if (dev != 0) {
4230 dev->toAudioPort(port);
4231 return NO_ERROR;
4232 }
4233 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4234 if (dev != 0) {
4235 dev->toAudioPort(port);
4236 return NO_ERROR;
4237 }
4238 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4239 if (out != 0) {
4240 out->toAudioPort(port);
4241 return NO_ERROR;
4242 }
4243 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4244 if (in != 0) {
4245 in->toAudioPort(port);
4246 return NO_ERROR;
4247 }
4248 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004249}
4250
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004251status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4252 audio_patch_handle_t *handle,
4253 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004254{
François Gaffieafd4cea2019-11-18 15:50:22 +01004255 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004256 if (handle == NULL || patch == NULL) {
4257 return BAD_VALUE;
4258 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004259 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004260 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004261 return BAD_VALUE;
4262 }
4263 // only one source per audio patch supported for now
4264 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004265 return INVALID_OPERATION;
4266 }
Eric Laurent874c42872014-08-08 15:13:39 -07004267 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004268 return INVALID_OPERATION;
4269 }
Eric Laurent874c42872014-08-08 15:13:39 -07004270 for (size_t i = 0; i < patch->num_sinks; i++) {
4271 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4272 return INVALID_OPERATION;
4273 }
4274 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004275
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004276 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4277 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4278 if (srcDevice == nullptr || sinkDevice == nullptr) {
4279 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4280 return BAD_VALUE;
4281 }
4282 ALOGV("%s between source %s and sink %s", __func__,
4283 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4284 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4285 // Default attributes, default volume priority, not to infer with non raw audio patches.
4286 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4287 const struct audio_port_config *source = &patch->sources[0];
4288 sp<SourceClientDescriptor> sourceDesc =
4289 new InternalSourceClientDescriptor(
4290 portId, uid, attributes, *source, srcDevice, sinkDevice,
4291 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4292
4293 status_t status =
4294 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4295
4296 if (status != NO_ERROR) {
4297 return INVALID_OPERATION;
4298 }
4299 mAudioSources.add(portId, sourceDesc);
4300 return NO_ERROR;
4301}
4302
4303status_t AudioPolicyManager::connectAudioSourceToSink(
4304 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4305 const struct audio_patch *patch,
4306 audio_patch_handle_t &handle,
4307 uid_t uid, uint32_t delayMs)
4308{
4309 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4310 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4311 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4312 return INVALID_OPERATION;
4313 }
4314 sourceDesc->connect(handle, sinkDevice);
4315 if (isMsdPatch(handle)) {
4316 return NO_ERROR;
4317 }
4318 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4319 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4320 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4321 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4322 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4323 goto FailurePatchAdded;
4324 }
4325 status = swOutput->start();
4326 if (status != NO_ERROR) {
4327 goto FailureSourceAdded;
4328 }
4329 swOutput->addClient(sourceDesc);
4330 status = startSource(swOutput, sourceDesc, &delayMs);
4331 if (status != NO_ERROR) {
4332 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4333 goto FailureSourceActive;
4334 }
4335 if (delayMs != 0) {
4336 usleep(delayMs * 1000);
4337 }
4338 return NO_ERROR;
4339
4340FailureSourceActive:
4341 swOutput->stop();
4342 releaseOutput(sourceDesc->portId());
4343FailureSourceAdded:
4344 sourceDesc->setSwOutput(nullptr);
4345FailurePatchAdded:
4346 releaseAudioPatchInternal(handle);
4347 return INVALID_OPERATION;
4348}
4349
4350status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4351 audio_patch_handle_t *handle,
4352 uid_t uid, uint32_t delayMs,
4353 const sp<SourceClientDescriptor>& sourceDesc)
4354{
4355 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004356 sp<AudioPatch> patchDesc;
4357 ssize_t index = mAudioPatches.indexOfKey(*handle);
4358
François Gaffieafd4cea2019-11-18 15:50:22 +01004359 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4360 patch->sources[0].role,
4361 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004362#if LOG_NDEBUG == 0
4363 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004364 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4365 patch->sinks[i].role,
4366 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004367 }
4368#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004369
4370 if (index >= 0) {
4371 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004372 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4373 __func__, mUidCached, patchDesc->getUid(), uid);
4374 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004375 return INVALID_OPERATION;
4376 }
4377 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004378 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004379 }
4380
4381 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004382 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004383 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004384 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004385 return BAD_VALUE;
4386 }
Eric Laurent84c70242014-06-23 08:46:27 -07004387 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4388 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004389 if (patchDesc != 0) {
4390 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004391 ALOGV("%s source id differs for patch current id %d new id %d",
4392 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004393 return BAD_VALUE;
4394 }
4395 }
Eric Laurent874c42872014-08-08 15:13:39 -07004396 DeviceVector devices;
4397 for (size_t i = 0; i < patch->num_sinks; i++) {
4398 // Only support mix to devices connection
4399 // TODO add support for mix to mix connection
4400 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004401 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004402 return INVALID_OPERATION;
4403 }
4404 sp<DeviceDescriptor> devDesc =
4405 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4406 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004407 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004408 return BAD_VALUE;
4409 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004410
François Gaffie11d30102018-11-02 16:09:09 +01004411 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004412 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004413 NULL, // updatedSamplingRate
4414 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004415 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004416 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004417 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004418 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004419 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004420 return INVALID_OPERATION;
4421 }
4422 devices.add(devDesc);
4423 }
4424 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004425 return INVALID_OPERATION;
4426 }
Eric Laurent874c42872014-08-08 15:13:39 -07004427
Eric Laurent6a94d692014-05-20 11:18:06 -07004428 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004429 ALOGV("%s setting device %s on output %d",
4430 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004431 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004432 index = mAudioPatches.indexOfKey(*handle);
4433 if (index >= 0) {
4434 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004435 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004436 }
4437 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004438 patchDesc->setUid(uid);
4439 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004440 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004441 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004442 return INVALID_OPERATION;
4443 }
4444 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4445 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4446 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004447 // only one sink supported when connecting an input device to a mix
4448 if (patch->num_sinks > 1) {
4449 return INVALID_OPERATION;
4450 }
François Gaffie53615e22015-03-19 09:24:12 +01004451 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004452 if (inputDesc == NULL) {
4453 return BAD_VALUE;
4454 }
4455 if (patchDesc != 0) {
4456 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4457 return BAD_VALUE;
4458 }
4459 }
François Gaffie11d30102018-11-02 16:09:09 +01004460 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004461 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004462 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004463 return BAD_VALUE;
4464 }
4465
François Gaffie11d30102018-11-02 16:09:09 +01004466 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004467 patch->sinks[0].sample_rate,
4468 NULL, /*updatedSampleRate*/
4469 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004470 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004471 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004472 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004473 // FIXME for the parameter type,
4474 // and the NONE
4475 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004476 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004477 return INVALID_OPERATION;
4478 }
4479 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004480 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004481 device->toString().c_str(), inputDesc->mIoHandle);
4482 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004483 index = mAudioPatches.indexOfKey(*handle);
4484 if (index >= 0) {
4485 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004486 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004487 }
4488 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004489 patchDesc->setUid(uid);
4490 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004491 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004492 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004493 return INVALID_OPERATION;
4494 }
4495 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4496 // device to device connection
4497 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004498 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004499 return BAD_VALUE;
4500 }
4501 }
François Gaffie11d30102018-11-02 16:09:09 +01004502 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004503 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004504 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004505 return BAD_VALUE;
4506 }
Eric Laurent874c42872014-08-08 15:13:39 -07004507
Eric Laurent6a94d692014-05-20 11:18:06 -07004508 //update source and sink with our own data as the data passed in the patch may
4509 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004510 PatchBuilder patchBuilder;
4511 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004512
4513 // if first sink is to MSD, establish single MSD patch
4514 if (getMsdAudioOutDevices().contains(
4515 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4516 ALOGV("%s patching to MSD", __FUNCTION__);
4517 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4518 goto installPatch;
4519 }
4520
François Gaffieafd4cea2019-11-18 15:50:22 +01004521 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4522 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004523
Eric Laurent874c42872014-08-08 15:13:39 -07004524 for (size_t i = 0; i < patch->num_sinks; i++) {
4525 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004526 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004527 return INVALID_OPERATION;
4528 }
François Gaffie11d30102018-11-02 16:09:09 +01004529 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004530 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004531 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004532 return BAD_VALUE;
4533 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004534 audio_port_config sinkPortConfig = {};
4535 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4536 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004537
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004538 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4539 // volume management purpose (tracking activity)
4540 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4541 // in config XML to reach the sink so that is can be declared as available.
4542 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004543 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004544 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004545 // take care of dynamic routing for SwOutput selection,
4546 audio_attributes_t attributes = sourceDesc->attributes();
4547 audio_stream_type_t stream = sourceDesc->stream();
4548 audio_attributes_t resultAttr;
4549 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4550 config.sample_rate = sourceDesc->config().sample_rate;
4551 config.channel_mask = sourceDesc->config().channel_mask;
4552 config.format = sourceDesc->config().format;
4553 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4554 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4555 bool isRequestedDeviceForExclusiveUse = false;
4556 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004557 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004558 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4559 &stream, sourceDesc->uid(), &config, &flags,
4560 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004561 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004562 if (output == AUDIO_IO_HANDLE_NONE) {
4563 ALOGV("%s no output for device %s",
4564 __FUNCTION__, sinkDevice->toString().c_str());
4565 return INVALID_OPERATION;
4566 }
4567 outputDesc = mOutputs.valueFor(output);
4568 if (outputDesc->isDuplicated()) {
4569 ALOGE("%s output is duplicated", __func__);
4570 return INVALID_OPERATION;
4571 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004572 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4573 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004574 } else {
4575 // Same for "raw patches" aka created from createAudioPatch API
4576 SortedVector<audio_io_handle_t> outputs =
4577 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4578 // if the sink device is reachable via an opened output stream, request to
4579 // go via this output stream by adding a second source to the patch
4580 // description
4581 output = selectOutput(outputs);
4582 if (output == AUDIO_IO_HANDLE_NONE) {
4583 ALOGE("%s no output available for internal patch sink", __func__);
4584 return INVALID_OPERATION;
4585 }
4586 outputDesc = mOutputs.valueFor(output);
4587 if (outputDesc->isDuplicated()) {
4588 ALOGV("%s output for device %s is duplicated",
4589 __func__, sinkDevice->toString().c_str());
4590 return INVALID_OPERATION;
4591 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004592 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004593 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004594 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004595 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004596 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004597 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004598 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4599 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004600 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4601 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004602 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004603 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004604 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004605 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004606 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004607 return INVALID_OPERATION;
4608 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004609 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004610 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004611 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004612 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004613 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004614 srcMixPortConfig.ext.mix.usecase.stream =
4615 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004616 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4617 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004618 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004619 }
Eric Laurent83b88082014-06-20 18:31:16 -07004620 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004621 }
4622 // TODO: check from routing capabilities in config file and other conflicting patches
4623
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004624installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004625 status_t status = installPatch(
4626 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004627 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004628 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004629 return INVALID_OPERATION;
4630 }
4631 } else {
4632 return BAD_VALUE;
4633 }
4634 } else {
4635 return BAD_VALUE;
4636 }
4637 return NO_ERROR;
4638}
4639
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004640status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004641{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004642 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004643 ssize_t index = mAudioPatches.indexOfKey(handle);
4644
4645 if (index < 0) {
4646 return BAD_VALUE;
4647 }
4648 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004649 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4650 __func__, mUidCached, patchDesc->getUid(), uid);
4651 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004652 return INVALID_OPERATION;
4653 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004654 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4655 for (size_t i = 0; i < mAudioSources.size(); i++) {
4656 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4657 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4658 portId = sourceDesc->portId();
4659 break;
4660 }
4661 }
4662 return portId != AUDIO_PORT_HANDLE_NONE ?
4663 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004664}
Eric Laurent6a94d692014-05-20 11:18:06 -07004665
François Gaffieafd4cea2019-11-18 15:50:22 +01004666status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004667 uint32_t delayMs,
4668 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004669{
4670 ALOGV("%s patch %d", __func__, handle);
4671 if (mAudioPatches.indexOfKey(handle) < 0) {
4672 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4673 return BAD_VALUE;
4674 }
4675 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004676 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004677 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004678 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004679 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004680 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004681 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004682 return BAD_VALUE;
4683 }
4684
François Gaffie11d30102018-11-02 16:09:09 +01004685 setOutputDevices(outputDesc,
4686 getNewOutputDevices(outputDesc, true /*fromCache*/),
4687 true,
4688 0,
4689 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004690 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4691 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004692 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004693 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004694 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004695 return BAD_VALUE;
4696 }
4697 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004698 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004699 true,
4700 NULL);
4701 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004702 status_t status =
4703 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4704 ALOGV("%s patch panel returned %d patchHandle %d",
4705 __func__, status, patchDesc->getAfHandle());
4706 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004707 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004708 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004709 // SW or HW Bridge
4710 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4711 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004712 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004713 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4714 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4715 outputDesc = sourceDesc->swOutput().promote();
4716 }
4717 if (outputDesc == nullptr) {
4718 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4719 // releaseOutput has already called closeOutput in case of direct output
4720 return NO_ERROR;
4721 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004722 patchHandle = outputDesc->getPatchHandle();
4723 // When a Sw bridge is released, the mixer used by this bridge will release its
4724 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4725 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4726 // updating hal patch handle (prevent leaks).
4727 // While using a HwBridge, force reconsidering device only if not reusing an existing
4728 // output and no more activity on output (will force to close).
4729 bool force = sourceDesc->useSwBridge() ||
4730 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4731 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4732 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4733 // Reconsider device only for cases:
4734 // 1 / Active Output
4735 // 2 / Inactive Output previously hosting HwBridge
4736 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4737 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4738 sourceDesc->canCloseOutput();
4739 setOutputDevices(outputDesc,
4740 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4741 outputDesc->devices(),
4742 force,
4743 0,
4744 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004745 } else {
4746 return BAD_VALUE;
4747 }
4748 } else {
4749 return BAD_VALUE;
4750 }
4751 return NO_ERROR;
4752}
4753
4754status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4755 struct audio_patch *patches,
4756 unsigned int *generation)
4757{
François Gaffie53615e22015-03-19 09:24:12 +01004758 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004759 return BAD_VALUE;
4760 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004761 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004762 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004763}
4764
Eric Laurente1715a42014-05-20 11:30:42 -07004765status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004766{
Eric Laurente1715a42014-05-20 11:30:42 -07004767 ALOGV("setAudioPortConfig()");
4768
4769 if (config == NULL) {
4770 return BAD_VALUE;
4771 }
4772 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4773 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004774 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4775 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004776 }
4777
Eric Laurenta121f902014-06-03 13:32:54 -07004778 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004779 if (config->type == AUDIO_PORT_TYPE_MIX) {
4780 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004781 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004782 if (outputDesc == NULL) {
4783 return BAD_VALUE;
4784 }
Eric Laurent84c70242014-06-23 08:46:27 -07004785 ALOG_ASSERT(!outputDesc->isDuplicated(),
4786 "setAudioPortConfig() called on duplicated output %d",
4787 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004788 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004789 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004790 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004791 if (inputDesc == NULL) {
4792 return BAD_VALUE;
4793 }
Eric Laurenta121f902014-06-03 13:32:54 -07004794 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004795 } else {
4796 return BAD_VALUE;
4797 }
4798 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4799 sp<DeviceDescriptor> deviceDesc;
4800 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4801 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4802 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4803 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4804 } else {
4805 return BAD_VALUE;
4806 }
4807 if (deviceDesc == NULL) {
4808 return BAD_VALUE;
4809 }
Eric Laurenta121f902014-06-03 13:32:54 -07004810 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004811 } else {
4812 return BAD_VALUE;
4813 }
4814
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004815 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004816 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4817 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004818 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004819 audioPortConfig->toAudioPortConfig(&newConfig, config);
4820 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004821 }
Eric Laurenta121f902014-06-03 13:32:54 -07004822 if (status != NO_ERROR) {
4823 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004824 }
Eric Laurente1715a42014-05-20 11:30:42 -07004825
4826 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004827}
4828
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004829void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4830{
Eric Laurentd60560a2015-04-10 11:31:20 -07004831 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004832 clearAudioPatches(uid);
4833 clearSessionRoutes(uid);
4834}
4835
Eric Laurent6a94d692014-05-20 11:18:06 -07004836void AudioPolicyManager::clearAudioPatches(uid_t uid)
4837{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004838 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004839 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004840 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004841 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004842 }
4843 }
4844}
4845
François Gaffiec005e562018-11-06 15:04:49 +01004846void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004847{
François Gaffiec005e562018-11-06 15:04:49 +01004848 // Take the first attributes following the product strategy as it is used to retrieve the routed
4849 // device. All attributes wihin a strategy follows the same "routing strategy"
4850 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4851 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004852 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004853 for (size_t j = 0; j < mOutputs.size(); j++) {
4854 if (mOutputs.keyAt(j) == ouptutToSkip) {
4855 continue;
4856 }
4857 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004858 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004859 continue;
4860 }
4861 // If the default device for this strategy is on another output mix,
4862 // invalidate all tracks in this strategy to force re connection.
4863 // Otherwise select new device on the output mix.
4864 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004865 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4866 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004867 }
4868 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004869 setOutputDevices(
4870 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004871 }
4872 }
4873}
4874
4875void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4876{
4877 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004878 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004879 for (size_t i = 0; i < mOutputs.size(); i++) {
4880 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004881 for (const auto& client : outputDesc->getClientIterable()) {
4882 if (client->hasPreferredDevice() && client->uid() == uid) {
4883 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004884 auto clientStrategy = client->strategy();
4885 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4886 end(affectedStrategies)) {
4887 continue;
4888 }
4889 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004890 }
4891 }
4892 }
4893 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004894 for (const auto& strategy : affectedStrategies) {
4895 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004896 }
4897
4898 // remove input routes associated with this uid
4899 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004900 for (size_t i = 0; i < mInputs.size(); i++) {
4901 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004902 for (const auto& client : inputDesc->getClientIterable()) {
4903 if (client->hasPreferredDevice() && client->uid() == uid) {
4904 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4905 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004906 }
4907 }
4908 }
4909 // reroute inputs if necessary
4910 SortedVector<audio_io_handle_t> inputsToClose;
4911 for (size_t i = 0; i < mInputs.size(); i++) {
4912 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004913 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004914 inputsToClose.add(inputDesc->mIoHandle);
4915 }
4916 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004917 for (const auto& input : inputsToClose) {
4918 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004919 }
4920}
4921
Eric Laurentd60560a2015-04-10 11:31:20 -07004922void AudioPolicyManager::clearAudioSources(uid_t uid)
4923{
4924 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004925 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4926 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004927 stopAudioSource(mAudioSources.keyAt(i));
4928 }
4929 }
4930}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004931
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004932status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4933 audio_io_handle_t *ioHandle,
4934 audio_devices_t *device)
4935{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004936 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4937 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004938 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004939 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004940
François Gaffiedf372692015-03-19 10:43:27 +01004941 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004942}
4943
Eric Laurentd60560a2015-04-10 11:31:20 -07004944status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004945 const audio_attributes_t *attributes,
4946 audio_port_handle_t *portId,
4947 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004948{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004949 ALOGV("%s", __FUNCTION__);
4950 *portId = AUDIO_PORT_HANDLE_NONE;
4951
4952 if (source == NULL || attributes == NULL || portId == NULL) {
4953 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4954 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004955 return BAD_VALUE;
4956 }
4957
Eric Laurentd60560a2015-04-10 11:31:20 -07004958 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4959 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004960 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4961 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004962 return INVALID_OPERATION;
4963 }
4964
François Gaffie11d30102018-11-02 16:09:09 +01004965 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004966 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004967 String8(source->ext.device.address),
4968 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004969 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004970 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004971 return BAD_VALUE;
4972 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004973
jiabin4ef93452019-09-10 14:29:54 -07004974 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004975
François Gaffieaaac0fd2018-11-22 17:56:39 +01004976 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004977 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004978 mEngine->getStreamTypeForAttributes(*attributes),
4979 mEngine->getProductStrategyForAttributes(*attributes),
4980 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004981
4982 status_t status = connectAudioSource(sourceDesc);
4983 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004984 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004985 }
4986 return status;
4987}
4988
Francois Gaffie601801d2021-06-22 13:27:39 +02004989sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4990 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4991{
4992 ALOGV("%s", __FUNCTION__);
4993 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4994
4995 status_t status = startAudioSource(source, attributes, &portId, uid);
4996 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4997 return mAudioSources.valueFor(portId);
4998}
4999
5000
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005001status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005002{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005003 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005004
5005 // make sure we only have one patch per source.
5006 disconnectAudioSource(sourceDesc);
5007
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005008 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005009 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5010 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5011 sourceDesc->srcDevice()->type(),
5012 String8(sourceDesc->srcDevice()->address().c_str()),
5013 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005014 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005015 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005016 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005017 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005018 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5019 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5020 return INVALID_OPERATION;
5021 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005022 PatchBuilder patchBuilder;
5023 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5024 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005025
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005026 return connectAudioSourceToSink(
5027 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005028}
5029
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005030status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005031{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005032 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5033 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005034 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005035 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005036 return BAD_VALUE;
5037 }
5038 status_t status = disconnectAudioSource(sourceDesc);
5039
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005040 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005041 return status;
5042}
5043
Andy Hung2ddee192015-12-18 17:34:44 -08005044status_t AudioPolicyManager::setMasterMono(bool mono)
5045{
5046 if (mMasterMono == mono) {
5047 return NO_ERROR;
5048 }
5049 mMasterMono = mono;
5050 // if enabling mono we close all offloaded devices, which will invalidate the
5051 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5052 // for recreating the new AudioTrack as non-offloaded PCM.
5053 //
5054 // If disabling mono, we leave all tracks as is: we don't know which clients
5055 // and tracks are able to be recreated as offloaded. The next "song" should
5056 // play back offloaded.
5057 if (mMasterMono) {
5058 Vector<audio_io_handle_t> offloaded;
5059 for (size_t i = 0; i < mOutputs.size(); ++i) {
5060 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5061 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5062 offloaded.push(desc->mIoHandle);
5063 }
5064 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005065 for (const auto& handle : offloaded) {
5066 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005067 }
5068 }
5069 // update master mono for all remaining outputs
5070 for (size_t i = 0; i < mOutputs.size(); ++i) {
5071 updateMono(mOutputs.keyAt(i));
5072 }
5073 return NO_ERROR;
5074}
5075
5076status_t AudioPolicyManager::getMasterMono(bool *mono)
5077{
5078 *mono = mMasterMono;
5079 return NO_ERROR;
5080}
5081
Eric Laurentac9cef52017-06-09 15:46:26 -07005082float AudioPolicyManager::getStreamVolumeDB(
5083 audio_stream_type_t stream, int index, audio_devices_t device)
5084{
jiabin9a3361e2019-10-01 09:38:30 -07005085 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005086}
5087
jiabin81772902018-04-02 17:52:27 -07005088status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5089 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005090 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005091{
Kriti Dang6537def2021-03-02 13:46:59 +01005092 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5093 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005094 return BAD_VALUE;
5095 }
Kriti Dang6537def2021-03-02 13:46:59 +01005096 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5097 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005098
5099 size_t formatsWritten = 0;
5100 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005101
Kriti Dang6537def2021-03-02 13:46:59 +01005102 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005103 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5104 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005105 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005106 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005107 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005108 bool formatEnabled = true;
5109 switch (forceUse) {
5110 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005111 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005112 break;
5113 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5114 formatEnabled = false;
5115 break;
5116 default: // AUTO or ALWAYS => true
5117 break;
jiabin81772902018-04-02 17:52:27 -07005118 }
5119 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5120 }
jiabin81772902018-04-02 17:52:27 -07005121 }
5122 return NO_ERROR;
5123}
5124
Kriti Dang6537def2021-03-02 13:46:59 +01005125status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5126 audio_format_t *surroundFormats) {
5127 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5128 return BAD_VALUE;
5129 }
5130 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5131 __func__, *numSurroundFormats, surroundFormats);
5132
5133 size_t formatsWritten = 0;
5134 size_t formatsMax = *numSurroundFormats;
5135 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5136
5137 // Return formats from all device profiles that have already been resolved by
5138 // checkOutputsForDevice().
5139 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5140 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5141 audio_devices_t deviceType = device->type();
5142 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5143 // returns formats reported by HDMI devices.
5144 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5145 continue;
5146 }
5147 // Formats reported by sink devices
5148 std::unordered_set<audio_format_t> formatset;
5149 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5150 formatset.insert(it->second.begin(), it->second.end());
5151 }
5152
5153 // Formats hard-coded in the in policy configuration file (if any).
5154 FormatVector encodedFormats = device->encodedFormats();
5155 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5156 // Filter the formats which are supported by the vendor hardware.
5157 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5158 if (mConfig.getSurroundFormats().count(*it) != 0) {
5159 formats.insert(*it);
5160 } else {
5161 for (const auto& pair : mConfig.getSurroundFormats()) {
5162 if (pair.second.count(*it) != 0) {
5163 formats.insert(pair.first);
5164 break;
5165 }
5166 }
5167 }
5168 }
5169 }
5170 *numSurroundFormats = formats.size();
5171 for (const auto& format: formats) {
5172 if (formatsWritten < formatsMax) {
5173 surroundFormats[formatsWritten++] = format;
5174 }
5175 }
5176 return NO_ERROR;
5177}
5178
jiabin81772902018-04-02 17:52:27 -07005179status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5180{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005181 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005182 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5183 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005184 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005185 return BAD_VALUE;
5186 }
5187
Mikhail Naganov100f0122018-11-29 11:22:16 -08005188 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5189 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005190 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005191 return INVALID_OPERATION;
5192 }
5193
Mikhail Naganov100f0122018-11-29 11:22:16 -08005194 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005195 return NO_ERROR;
5196 }
5197
Mikhail Naganov100f0122018-11-29 11:22:16 -08005198 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005199 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005200 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005201 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005202 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005203 }
5204 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005205 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005206 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005207 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005208 }
5209 }
5210
5211 sp<SwAudioOutputDescriptor> outputDesc;
5212 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005213 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5214 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005215 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5216 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005217 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005218 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005219 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5220 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5221 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005222 name.c_str(),
5223 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005224 if (status != NO_ERROR) {
5225 continue;
5226 }
5227 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5228 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5229 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005230 name.c_str(),
5231 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005232 profileUpdated |= (status == NO_ERROR);
5233 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005234 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005235 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005236 AUDIO_DEVICE_IN_HDMI);
5237 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5238 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005239 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005240 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005241 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5242 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5243 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005244 name.c_str(),
5245 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005246 if (status != NO_ERROR) {
5247 continue;
5248 }
5249 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5250 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5251 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005252 name.c_str(),
5253 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005254 profileUpdated |= (status == NO_ERROR);
5255 }
5256
jiabin81772902018-04-02 17:52:27 -07005257 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005258 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005259 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005260 }
5261
5262 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5263}
5264
Eric Laurent5ada82e2019-08-29 17:53:54 -07005265void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005266{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005267 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005268 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005269 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005270 }
5271}
5272
jiabin6012f912018-11-02 17:06:30 -07005273bool AudioPolicyManager::isHapticPlaybackSupported()
5274{
5275 for (const auto& hwModule : mHwModules) {
5276 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5277 for (const auto &outProfile : outputProfiles) {
5278 struct audio_port audioPort;
5279 outProfile->toAudioPort(&audioPort);
5280 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5281 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5282 return true;
5283 }
5284 }
5285 }
5286 }
5287 return false;
5288}
5289
Carter Hsu325a8eb2022-01-19 19:56:51 +08005290bool AudioPolicyManager::isUltrasoundSupported()
5291{
5292 bool hasUltrasoundOutput = false;
5293 bool hasUltrasoundInput = false;
5294 for (const auto& hwModule : mHwModules) {
5295 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5296 if (!hasUltrasoundOutput) {
5297 for (const auto &outProfile : outputProfiles) {
5298 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5299 hasUltrasoundOutput = true;
5300 break;
5301 }
5302 }
5303 }
5304
5305 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5306 if (!hasUltrasoundInput) {
5307 for (const auto &inputProfile : inputProfiles) {
5308 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5309 hasUltrasoundInput = true;
5310 break;
5311 }
5312 }
5313 }
5314
5315 if (hasUltrasoundOutput && hasUltrasoundInput)
5316 return true;
5317 }
5318 return false;
5319}
5320
Eric Laurent8340e672019-11-06 11:01:08 -08005321bool AudioPolicyManager::isCallScreenModeSupported()
5322{
5323 return getConfig().isCallScreenModeSupported();
5324}
5325
5326
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005327status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005328{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005329 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005330 if (!sourceDesc->isConnected()) {
5331 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5332 return NO_ERROR;
5333 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005334 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5335 if (swOutput != 0) {
5336 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005337 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005338 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005339 }
jiabinbce0c1d2020-10-05 11:20:18 -07005340 if (releaseOutput(sourceDesc->portId())) {
5341 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5342 // no need to release audio patch here but just return NO_ERROR.
5343 return NO_ERROR;
5344 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005345 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005346 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005347 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005348 // close Hwoutput and remove from mHwOutputs
5349 } else {
5350 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5351 }
5352 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005353 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005354 sourceDesc->disconnect();
5355 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005356}
5357
François Gaffiec005e562018-11-06 15:04:49 +01005358sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5359 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005360{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005361 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005362 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005363 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005364 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005365 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5366 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005367 source = sourceDesc;
5368 break;
5369 }
5370 }
5371 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005372}
5373
Eric Laurentb4f42a92022-01-17 17:37:31 +01005374bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005375 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005376 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005377{
5378 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5379 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005380 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005381 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005382 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5383 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5384 return false;
5385 }
5386 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5387 return false;
5388 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005389 }
5390
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005391 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005392 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005393 if (profile == nullptr) {
5394 return false;
5395 }
5396
5397 // The caller can have the audio config criteria ignored by either passing a null ptr or
5398 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005399 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005400 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005401
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005402 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005403 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005404 return false;
5405 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005406 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005407 return true;
5408}
5409
5410void AudioPolicyManager::checkVirtualizerClientRoutes() {
5411 std::set<audio_stream_type_t> streamsToInvalidate;
5412 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005413 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5414 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005415 audio_attributes_t attr = client->attributes();
5416 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5417 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5418 audio_config_base_t clientConfig = client->config();
5419 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005420 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005421 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005422 streamsToInvalidate.insert(client->stream());
5423 }
5424 }
5425 }
5426
5427 for (audio_stream_type_t stream : streamsToInvalidate) {
5428 mpClientInterface->invalidateStream(stream);
5429 }
5430}
5431
Eric Laurente191d1b2022-04-15 11:59:25 +02005432
5433bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5434 const sp<SwAudioOutputDescriptor>& outputDesc) {
5435 if (outputDesc->isDuplicated()) {
5436 return false;
5437 }
5438 DeviceVector devices = outputDesc->supportedDevices();
5439 for (size_t i = 0; i < mOutputs.size(); i++) {
5440 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5441 if (desc == outputDesc || desc->isDuplicated()) {
5442 continue;
5443 }
5444 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5445 if (!sharedDevices.isEmpty()
5446 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5447 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5448 return false;
5449 }
5450 }
5451 return true;
5452}
5453
5454
Eric Laurentfa0f6742021-08-17 18:39:44 +02005455status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005456 const audio_attributes_t *attr,
5457 audio_io_handle_t *output) {
5458 *output = AUDIO_IO_HANDLE_NONE;
5459
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005460 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5461 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5462 audio_config_t *configPtr = nullptr;
5463 audio_config_t config;
5464 if (mixerConfig != nullptr) {
5465 config = audio_config_initializer(mixerConfig);
5466 configPtr = &config;
5467 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005468 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005469 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005470 return BAD_VALUE;
5471 }
5472
5473 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005474 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005475 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005476 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005477 return BAD_VALUE;
5478 }
5479
Eric Laurente191d1b2022-04-15 11:59:25 +02005480 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005481 for (size_t i = 0; i < mOutputs.size(); i++) {
5482 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005483 if (!desc->isDuplicated()
5484 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5485 spatializerOutputs.push_back(desc);
5486 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005487 }
5488 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005489 mSpatializerOutput.clear();
5490 bool outputsChanged = false;
5491 for (const auto& desc : spatializerOutputs) {
5492 if (desc->mProfile == profile
5493 && (configPtr == nullptr
5494 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5495 mSpatializerOutput = desc;
5496 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5497 } else {
5498 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5499 " and devices %s", __func__, desc->mIoHandle,
5500 configPtr != nullptr ? configPtr->channel_mask : 0,
5501 devices.toString().c_str());
5502 closeOutput(desc->mIoHandle);
5503 outputsChanged = true;
5504 }
Eric Laurent39095982021-08-24 18:29:27 +02005505 }
5506
Eric Laurente191d1b2022-04-15 11:59:25 +02005507 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005508 sp<SwAudioOutputDescriptor> desc =
5509 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005510 if (desc != nullptr) {
5511 mSpatializerOutput = desc;
5512 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005513 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005514 }
5515
5516 checkVirtualizerClientRoutes();
5517
Eric Laurente191d1b2022-04-15 11:59:25 +02005518 if (outputsChanged) {
5519 mPreviousOutputs = mOutputs;
5520 mpClientInterface->onAudioPortListUpdate();
5521 }
5522
5523 if (mSpatializerOutput == nullptr) {
5524 ALOGV("%s could not open spatializer output with requested config", __func__);
5525 return BAD_VALUE;
5526 }
Eric Laurent39095982021-08-24 18:29:27 +02005527 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005528 ALOGV("%s returning new spatializer output %d", __func__, *output);
5529 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005530}
5531
Eric Laurentfa0f6742021-08-17 18:39:44 +02005532status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5533 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005534 return INVALID_OPERATION;
5535 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005536 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005537 return BAD_VALUE;
5538 }
Eric Laurent39095982021-08-24 18:29:27 +02005539
Eric Laurente191d1b2022-04-15 11:59:25 +02005540 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5541 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5542 closeOutput(mSpatializerOutput->mIoHandle);
5543 //from now on mSpatializerOutput is null
5544 checkVirtualizerClientRoutes();
5545 }
Eric Laurent39095982021-08-24 18:29:27 +02005546
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005547 return NO_ERROR;
5548}
5549
Eric Laurente552edb2014-03-10 17:42:56 -07005550// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005551// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005552// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005553uint32_t AudioPolicyManager::nextAudioPortGeneration()
5554{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005555 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005556}
5557
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005558static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005559 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5560 !audioPolicyXmlConfigFile.empty()) {
5561 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5562 if (ret == NO_ERROR) {
5563 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005564 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005565 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005566 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005567 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005568}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005569
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005570AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5571 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005572 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005573 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005574 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005575 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005576 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005577 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005578 mAudioPortGeneration(1),
5579 mBeaconMuteRefCount(0),
5580 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005581 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005582 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005583 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005584 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005585{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005586}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005587
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005588AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5589 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5590{
5591 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005592}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005593
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005594void AudioPolicyManager::loadConfig() {
5595 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005596 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005597 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005598 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005599}
5600
5601status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005602 {
5603 auto engLib = EngineLibrary::load(
5604 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5605 if (!engLib) {
5606 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5607 return NO_INIT;
5608 }
5609 mEngine = engLib->createEngine();
5610 if (mEngine == nullptr) {
5611 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5612 return NO_INIT;
5613 }
François Gaffie2110e042015-03-24 08:41:51 +01005614 }
5615 mEngine->setObserver(this);
5616 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005617 if (status != NO_ERROR) {
5618 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5619 return status;
5620 }
François Gaffie2110e042015-03-24 08:41:51 +01005621
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005622 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005623 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5624 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5625
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005626 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005627 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005628 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005629
Eric Laurent3a4311c2014-03-17 12:00:47 -07005630 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005631 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5632 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5633 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005634 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005635 }
jiabin9ff780e2018-03-19 18:19:52 -07005636 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005637 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005638 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005639 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005640 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005641 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005642 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005643 }
5644 }
5645 }
Eric Laurente552edb2014-03-10 17:42:56 -07005646
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005647 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005648
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005649 // Silence ALOGV statements
5650 property_set("log.tag." LOG_TAG, "D");
5651
Eric Laurente552edb2014-03-10 17:42:56 -07005652 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005653 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005654}
5655
Eric Laurente0720872014-03-11 09:30:41 -07005656AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005657{
Eric Laurente552edb2014-03-10 17:42:56 -07005658 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005659 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005660 }
5661 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005662 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005663 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005664 mAvailableOutputDevices.clear();
5665 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005666 mOutputs.clear();
5667 mInputs.clear();
5668 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005669 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005670 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005671}
5672
Eric Laurente0720872014-03-11 09:30:41 -07005673status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005674{
Eric Laurent87ffa392015-05-22 10:32:38 -07005675 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005676}
5677
Eric Laurente552edb2014-03-10 17:42:56 -07005678// ---
5679
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005680void AudioPolicyManager::onNewAudioModulesAvailable()
5681{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005682 DeviceVector newDevices;
5683 onNewAudioModulesAvailableInt(&newDevices);
5684 if (!newDevices.empty()) {
5685 nextAudioPortGeneration();
5686 mpClientInterface->onAudioPortListUpdate();
5687 }
5688}
5689
5690void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5691{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005692 for (const auto& hwModule : mHwModulesAll) {
5693 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5694 continue;
5695 }
5696 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5697 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5698 ALOGW("could not open HW module %s", hwModule->getName());
5699 continue;
5700 }
5701 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005702 // open all output streams needed to access attached devices.
5703 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005704 // This also validates mAvailableOutputDevices list
5705 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5706 if (!outProfile->canOpenNewIo()) {
5707 ALOGE("Invalid Output profile max open count %u for profile %s",
5708 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5709 continue;
5710 }
5711 if (!outProfile->hasSupportedDevices()) {
5712 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5713 continue;
5714 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005715 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5716 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005717 mTtsOutputAvailable = true;
5718 }
5719
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005720 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5721 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5722 sp<DeviceDescriptor> supportedDevice = 0;
5723 if (supportedDevices.contains(mDefaultOutputDevice)) {
5724 supportedDevice = mDefaultOutputDevice;
5725 } else {
5726 // choose first device present in profile's SupportedDevices also part of
5727 // mAvailableOutputDevices.
5728 if (availProfileDevices.isEmpty()) {
5729 continue;
5730 }
5731 supportedDevice = availProfileDevices.itemAt(0);
5732 }
5733 if (!mOutputDevicesAll.contains(supportedDevice)) {
5734 continue;
5735 }
5736 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5737 mpClientInterface);
5738 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005739 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5740 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005741 AUDIO_STREAM_DEFAULT,
5742 AUDIO_OUTPUT_FLAG_NONE, &output);
5743 if (status != NO_ERROR) {
5744 ALOGW("Cannot open output stream for devices %s on hw module %s",
5745 supportedDevice->toString().c_str(), hwModule->getName());
5746 continue;
5747 }
5748 for (const auto &device : availProfileDevices) {
5749 // give a valid ID to an attached device once confirmed it is reachable
5750 if (!device->isAttached()) {
5751 device->attach(hwModule);
5752 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005753 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005754 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005755 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5756 }
5757 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005758 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005759 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5760 mPrimaryOutput = outputDesc;
5761 }
Eric Laurent39095982021-08-24 18:29:27 +02005762 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005763 outputDesc->close();
5764 } else {
5765 addOutput(output, outputDesc);
5766 setOutputDevices(outputDesc,
5767 DeviceVector(supportedDevice),
5768 true,
5769 0,
5770 NULL);
5771 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005772 }
5773 // open input streams needed to access attached devices to validate
5774 // mAvailableInputDevices list
5775 for (const auto& inProfile : hwModule->getInputProfiles()) {
5776 if (!inProfile->canOpenNewIo()) {
5777 ALOGE("Invalid Input profile max open count %u for profile %s",
5778 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5779 continue;
5780 }
5781 if (!inProfile->hasSupportedDevices()) {
5782 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5783 continue;
5784 }
5785 // chose first device present in profile's SupportedDevices also part of
5786 // available input devices
5787 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5788 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5789 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005790 ALOGV("%s: Input device list is empty! for profile %s",
5791 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005792 continue;
5793 }
5794 sp<AudioInputDescriptor> inputDesc =
5795 new AudioInputDescriptor(inProfile, mpClientInterface);
5796
5797 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5798 status_t status = inputDesc->open(nullptr,
5799 availProfileDevices.itemAt(0),
5800 AUDIO_SOURCE_MIC,
5801 AUDIO_INPUT_FLAG_NONE,
5802 &input);
5803 if (status != NO_ERROR) {
5804 ALOGW("Cannot open input stream for device %s on hw module %s",
5805 availProfileDevices.toString().c_str(),
5806 hwModule->getName());
5807 continue;
5808 }
5809 for (const auto &device : availProfileDevices) {
5810 // give a valid ID to an attached device once confirmed it is reachable
5811 if (!device->isAttached()) {
5812 device->attach(hwModule);
5813 device->importAudioPortAndPickAudioProfile(inProfile, true);
5814 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005815 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005816 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5817 }
5818 }
5819 inputDesc->close();
5820 }
5821 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005822
5823 // Check if spatializer outputs can be closed until used.
5824 // mOutputs vector never contains duplicated outputs at this point.
5825 std::vector<audio_io_handle_t> outputsClosed;
5826 for (size_t i = 0; i < mOutputs.size(); i++) {
5827 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5828 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5829 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5830 outputsClosed.push_back(desc->mIoHandle);
5831 desc->close();
5832 }
5833 }
5834 for (auto output : outputsClosed) {
5835 removeOutput(output);
5836 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005837}
5838
Eric Laurent98e38192018-02-15 18:31:53 -08005839void AudioPolicyManager::addOutput(audio_io_handle_t output,
5840 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005841{
Eric Laurent1c333e22014-05-20 10:48:17 -07005842 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005843 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005844 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005845 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005846 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005847}
5848
François Gaffie53615e22015-03-19 09:24:12 +01005849void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5850{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005851 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5852 ALOGV("%s: removing primary output", __func__);
5853 mPrimaryOutput = nullptr;
5854 }
François Gaffie53615e22015-03-19 09:24:12 +01005855 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005856 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005857}
5858
Eric Laurent98e38192018-02-15 18:31:53 -08005859void AudioPolicyManager::addInput(audio_io_handle_t input,
5860 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005861{
Eric Laurent1c333e22014-05-20 10:48:17 -07005862 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005863 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005864}
Eric Laurente552edb2014-03-10 17:42:56 -07005865
François Gaffie11d30102018-11-02 16:09:09 +01005866status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005867 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005868 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005869{
François Gaffie11d30102018-11-02 16:09:09 +01005870 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005871 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005872 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005873
François Gaffie11d30102018-11-02 16:09:09 +01005874 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005875 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005876 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005877 }
Eric Laurente552edb2014-03-10 17:42:56 -07005878
Eric Laurent3b73df72014-03-11 09:06:29 -07005879 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005880 // first call getAudioPort to get the supported attributes from the HAL
5881 struct audio_port_v7 port = {};
5882 device->toAudioPort(&port);
5883 status_t status = mpClientInterface->getAudioPort(&port);
5884 if (status == NO_ERROR) {
5885 device->importAudioPort(port);
5886 }
5887
5888 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005889 for (size_t i = 0; i < mOutputs.size(); i++) {
5890 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005891 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005892 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005893 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5894 mOutputs.keyAt(i), device->toString().c_str());
5895 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005896 }
5897 }
5898 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005899 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005900 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005901 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5902 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005903 if (profile->supportsDevice(device)) {
5904 profiles.add(profile);
5905 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5906 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005907 }
5908 }
5909 }
5910
Eric Laurent7b279bb2015-12-14 10:18:23 -08005911 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005912
Eric Laurente552edb2014-03-10 17:42:56 -07005913 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005914 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005915 return BAD_VALUE;
5916 }
5917
5918 // open outputs for matching profiles if needed. Direct outputs are also opened to
5919 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5920 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005921 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005922
5923 // nothing to do if one output is already opened for this profile
5924 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005925 for (j = 0; j < outputs.size(); j++) {
5926 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005927 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005928 // matching profile: save the sample rates, format and channel masks supported
5929 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005930 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005931 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005932 }
Eric Laurente552edb2014-03-10 17:42:56 -07005933 break;
5934 }
5935 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005936 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005937 continue;
5938 }
5939
Eric Laurent3974e3b2017-12-07 17:58:43 -08005940 if (!profile->canOpenNewIo()) {
5941 ALOGW("Max Output number %u already opened for this profile %s",
5942 profile->maxOpenCount, profile->getTagName().c_str());
5943 continue;
5944 }
5945
Eric Laurent83efe1c2017-07-09 16:51:08 -07005946 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005947 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005948 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5949 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005950 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005951 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005952 profiles.removeAt(profile_index);
5953 profile_index--;
5954 } else {
5955 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005956 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005957 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005958 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5959 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005960 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005961 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005962
François Gaffie11d30102018-11-02 16:09:09 +01005963 if (device_distinguishes_on_address(deviceType)) {
5964 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5965 device->toString().c_str());
5966 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5967 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005968 }
Eric Laurente552edb2014-03-10 17:42:56 -07005969 ALOGV("checkOutputsForDevice(): adding output %d", output);
5970 }
5971 }
5972
5973 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005974 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005975 return BAD_VALUE;
5976 }
Eric Laurentd4692962014-05-05 18:13:44 -07005977 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005978 // check if one opened output is not needed any more after disconnecting one device
5979 for (size_t i = 0; i < mOutputs.size(); i++) {
5980 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005981 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005982 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005983 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005984 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005985 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005986 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005987 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5988 mOutputs.keyAt(i));
5989 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005990 }
Eric Laurente552edb2014-03-10 17:42:56 -07005991 }
5992 }
Eric Laurentd4692962014-05-05 18:13:44 -07005993 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005994 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005995 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5996 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005997 if (!profile->supportsDevice(device)) {
5998 continue;
5999 }
6000 ALOGV("checkOutputsForDevice(): "
6001 "clearing direct output profile %zu on module %s",
6002 j, hwModule->getName());
6003 profile->clearAudioProfiles();
6004 if (!profile->hasDynamicAudioProfile()) {
6005 continue;
6006 }
6007 // When a device is disconnected, if there is an IOProfile that contains dynamic
6008 // profiles and supports the disconnected device, call getAudioPort to repopulate
6009 // the capabilities of the devices that is supported by the IOProfile.
6010 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6011 if (supportedDevice == device ||
6012 !mAvailableOutputDevices.contains(supportedDevice)) {
6013 continue;
6014 }
6015 struct audio_port_v7 port;
6016 supportedDevice->toAudioPort(&port);
6017 status_t status = mpClientInterface->getAudioPort(&port);
6018 if (status == NO_ERROR) {
6019 supportedDevice->importAudioPort(port);
6020 }
Eric Laurente552edb2014-03-10 17:42:56 -07006021 }
6022 }
6023 }
6024 }
6025 return NO_ERROR;
6026}
6027
François Gaffie11d30102018-11-02 16:09:09 +01006028status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006029 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006030{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006031 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006032
François Gaffie11d30102018-11-02 16:09:09 +01006033 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006034 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006035 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006036 }
6037
Eric Laurentd4692962014-05-05 18:13:44 -07006038 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006039 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006040 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006041 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006042 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006043 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006044 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006045 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006046
François Gaffie11d30102018-11-02 16:09:09 +01006047 if (profile->supportsDevice(device)) {
6048 profiles.add(profile);
6049 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6050 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006051 }
6052 }
6053 }
6054
Eric Laurent0dd51852019-04-19 18:18:58 -07006055 if (profiles.isEmpty()) {
6056 ALOGW("%s: No input profile available for device %s",
6057 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006058 return BAD_VALUE;
6059 }
6060
6061 // open inputs for matching profiles if needed. Direct inputs are also opened to
6062 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6063 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6064
Eric Laurent1c333e22014-05-20 10:48:17 -07006065 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006066
Eric Laurentd4692962014-05-05 18:13:44 -07006067 // nothing to do if one input is already opened for this profile
6068 size_t input_index;
6069 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6070 desc = mInputs.valueAt(input_index);
6071 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006072 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006073 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006074 }
Eric Laurentd4692962014-05-05 18:13:44 -07006075 break;
6076 }
6077 }
6078 if (input_index != mInputs.size()) {
6079 continue;
6080 }
6081
Eric Laurent3974e3b2017-12-07 17:58:43 -08006082 if (!profile->canOpenNewIo()) {
6083 ALOGW("Max Input number %u already opened for this profile %s",
6084 profile->maxOpenCount, profile->getTagName().c_str());
6085 continue;
6086 }
6087
Eric Laurentfe231122017-11-17 17:48:06 -08006088 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006089 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006090 status_t status = desc->open(nullptr,
6091 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006092 AUDIO_SOURCE_MIC,
6093 AUDIO_INPUT_FLAG_NONE,
6094 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006095
Eric Laurentcf2c0212014-07-25 16:20:43 -07006096 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006097 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006098 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006099 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006100 mpClientInterface->setParameters(input, String8(param));
6101 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006102 }
François Gaffie11d30102018-11-02 16:09:09 +01006103 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006104 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006105 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006106 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006107 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006108 }
6109
Eric Laurent0dd51852019-04-19 18:18:58 -07006110 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006111 addInput(input, desc);
6112 }
6113 } // endif input != 0
6114
Eric Laurentcf2c0212014-07-25 16:20:43 -07006115 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006116 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006117 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006118 profiles.removeAt(profile_index);
6119 profile_index--;
6120 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006121 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006122 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006123 }
Eric Laurentd4692962014-05-05 18:13:44 -07006124 ALOGV("checkInputsForDevice(): adding input %d", input);
6125 }
6126 } // end scan profiles
6127
6128 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006129 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006130 return BAD_VALUE;
6131 }
6132 } else {
6133 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006134 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006135 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006136 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006137 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006138 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006139 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006140 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006141 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6142 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006143 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006144 }
6145 }
6146 }
6147 } // end disconnect
6148
6149 return NO_ERROR;
6150}
6151
6152
Eric Laurente0720872014-03-11 09:30:41 -07006153void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006154{
6155 ALOGV("closeOutput(%d)", output);
6156
François Gaffie1c878552018-11-22 16:53:21 +01006157 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6158 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006159 ALOGW("closeOutput() unknown output %d", output);
6160 return;
6161 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006162 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006163 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006164
Eric Laurente552edb2014-03-10 17:42:56 -07006165 // look for duplicated outputs connected to the output being removed.
6166 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006167 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6168 if (dupOutput->isDuplicated() &&
6169 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6170 sp<SwAudioOutputDescriptor> remainingOutput =
6171 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006172 // As all active tracks on duplicated output will be deleted,
6173 // and as they were also referenced on the other output, the reference
6174 // count for their stream type must be adjusted accordingly on
6175 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006176 const bool wasActive = remainingOutput->isActive();
6177 // Note: no-op on the closing output where all clients has already been set inactive
6178 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006179 // stop() will be a no op if the output is still active but is needed in case all
6180 // active streams refcounts where cleared above
6181 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006182 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006183 }
Eric Laurente552edb2014-03-10 17:42:56 -07006184 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6185 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6186
6187 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006188 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006189 }
6190 }
6191
Eric Laurent05b90f82014-08-27 15:32:29 -07006192 nextAudioPortGeneration();
6193
François Gaffie1c878552018-11-22 16:53:21 +01006194 ssize_t index = mAudioPatches.indexOfKey(closingOutput->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
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006203 if (closingOutputWasActive) {
6204 closingOutput->stop();
6205 }
François Gaffie1c878552018-11-22 16:53:21 +01006206 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006207
François Gaffie53615e22015-03-19 09:24:12 +01006208 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006209 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006210 if (closingOutput == mSpatializerOutput) {
6211 mSpatializerOutput.clear();
6212 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006213
6214 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6215 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006216 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006217 bool directOutputOpen = false;
6218 for (size_t i = 0; i < mOutputs.size(); i++) {
6219 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6220 directOutputOpen = true;
6221 break;
6222 }
6223 }
6224 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006225 ALOGV("no direct outputs open, reset MSD patches");
6226 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6227 // how output devices for patching are resolved. Avoid by caching and reusing the
6228 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6229 // devices to patch to. This may be complicated by the fact that devices may become
6230 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006231 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006232 }
6233 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006234}
6235
6236void AudioPolicyManager::closeInput(audio_io_handle_t input)
6237{
6238 ALOGV("closeInput(%d)", input);
6239
6240 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6241 if (inputDesc == NULL) {
6242 ALOGW("closeInput() unknown input %d", input);
6243 return;
6244 }
6245
Eric Laurent6a94d692014-05-20 11:18:06 -07006246 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006247
François Gaffie11d30102018-11-02 16:09:09 +01006248 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006249 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006250 if (index >= 0) {
6251 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006252 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6253 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006254 mAudioPatches.removeItemsAt(index);
6255 mpClientInterface->onAudioPatchListUpdate();
6256 }
6257
Eric Laurentfe231122017-11-17 17:48:06 -08006258 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006259 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006260
François Gaffie11d30102018-11-02 16:09:09 +01006261 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6262 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006263 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006264 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006265 }
Eric Laurente552edb2014-03-10 17:42:56 -07006266}
6267
François Gaffie11d30102018-11-02 16:09:09 +01006268SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6269 const DeviceVector &devices,
6270 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006271{
6272 SortedVector<audio_io_handle_t> outputs;
6273
François Gaffie11d30102018-11-02 16:09:09 +01006274 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006275 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006276 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006277 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006278 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006279 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006280 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006281 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006282 outputs.add(openOutputs.keyAt(i));
6283 }
6284 }
6285 return outputs;
6286}
6287
Mikhail Naganov37977152018-07-11 15:54:44 -07006288void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6289{
6290 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6291 // output is suspended before any tracks are moved to it
6292 checkA2dpSuspend();
6293 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006294 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006295 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006296 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006297 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006298 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6299 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6300 // configuration changes will ultimately be rerouted correctly. We can still avoid
6301 // unnecessary rerouting by caching and reusing the arguments to
6302 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6303 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006304 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006305 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006306 // an event that changed routing likely occurred, inform upper layers
6307 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006308}
6309
François Gaffiec005e562018-11-06 15:04:49 +01006310bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6311 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006312{
François Gaffiec005e562018-11-06 15:04:49 +01006313 return mEngine->getProductStrategyForAttributes(lAttr) ==
6314 mEngine->getProductStrategyForAttributes(rAttr);
6315}
6316
Francois Gaffieff1eb522020-05-06 18:37:04 +02006317void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6318{
6319 for (size_t i = 0; i < mAudioSources.size(); i++) {
6320 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6321 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006322 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006323 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006324 connectAudioSource(sourceDesc);
6325 }
6326 }
6327}
6328
6329void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6330{
6331 for (size_t i = 0; i < mAudioSources.size(); i++) {
6332 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6333 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6334 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6335 disconnectAudioSource(sourceDesc);
6336 }
6337 }
6338}
6339
François Gaffiec005e562018-11-06 15:04:49 +01006340void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6341{
6342 auto psId = mEngine->getProductStrategyForAttributes(attr);
6343
6344 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6345 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006346
François Gaffie11d30102018-11-02 16:09:09 +01006347 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6348 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006349
Eric Laurentc209fe42020-06-05 18:11:23 -07006350 uint32_t maxLatency = 0;
6351 bool invalidate = false;
6352 // take into account dynamic audio policies related changes: if a client is now associated
6353 // to a different policy mix than at creation time, invalidate corresponding stream
6354 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6355 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6356 if (desc->isDuplicated()) {
6357 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006358 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006359 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6360 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6361 continue;
6362 }
6363 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006364 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6365 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006366 if (status != OK) {
6367 continue;
6368 }
yucliuf4de36d2020-09-14 14:57:56 -07006369 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006370 invalidate = true;
6371 if (desc->isStrategyActive(psId)) {
6372 maxLatency = desc->latency();
6373 }
6374 break;
6375 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006376 }
6377 }
6378
Eric Laurentc209fe42020-06-05 18:11:23 -07006379 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006380 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6381 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006382 for (audio_io_handle_t srcOut : srcOutputs) {
6383 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006384 if (desc == nullptr) continue;
6385
6386 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006387 maxLatency = desc->latency();
6388 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006389
6390 if (invalidate) continue;
6391
6392 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006393 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006394 // a client on a non direct outputs has necessarily a linear PCM format
6395 // so we can call selectOutput() safely
6396 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6397 client->flags(),
6398 client->config().format,
6399 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006400 client->config().sample_rate,
6401 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006402 if (newOutput != srcOut) {
6403 invalidate = true;
6404 break;
6405 }
6406 } else {
6407 sp<IOProfile> profile = getProfileForOutput(newDevices,
6408 client->config().sample_rate,
6409 client->config().format,
6410 client->config().channel_mask,
6411 client->flags(),
6412 true /* directOnly */);
6413 if (profile != desc->mProfile) {
6414 invalidate = true;
6415 break;
6416 }
6417 }
6418 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006419 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006420
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006421 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006422 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006423 std::to_string(srcOutputs[0]).c_str(),
6424 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006425 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006426 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006427 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006428 if (desc == nullptr) continue;
6429
6430 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006431 setStrategyMute(psId, true, desc);
6432 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006433 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006434 }
François Gaffiec005e562018-11-06 15:04:49 +01006435 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006436 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006437 connectAudioSource(source);
6438 }
Eric Laurente552edb2014-03-10 17:42:56 -07006439 }
6440
François Gaffiec005e562018-11-06 15:04:49 +01006441 // Move effects associated to this stream from previous output to new output
6442 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006443 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006444 }
François Gaffiec005e562018-11-06 15:04:49 +01006445 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006446 if (invalidate) {
6447 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6448 mpClientInterface->invalidateStream(stream);
6449 }
jiabin49256852022-03-09 11:21:35 -08006450 for (audio_io_handle_t srcOut : srcOutputs) {
6451 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6452 if (desc == nullptr) continue;
6453
6454 desc->setTracksInvalidatedStatusByStrategy(psId);
6455 }
Eric Laurente552edb2014-03-10 17:42:56 -07006456 }
6457 }
6458}
6459
Eric Laurente0720872014-03-11 09:30:41 -07006460void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006461{
François Gaffiec005e562018-11-06 15:04:49 +01006462 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6463 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6464 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006465 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006466 }
Eric Laurente552edb2014-03-10 17:42:56 -07006467}
6468
Kevin Rocard153f92d2018-12-18 18:33:28 -08006469void AudioPolicyManager::checkSecondaryOutputs() {
6470 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006471 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006472 for (size_t i = 0; i < mOutputs.size(); i++) {
6473 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6474 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006475 sp<AudioPolicyMix> primaryMix;
6476 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006477 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6478 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006479 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6480 for (auto &secondaryMix : secondaryMixes) {
6481 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6482 if (outputDesc != nullptr &&
6483 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6484 secondaryDescs.push_back(outputDesc);
6485 }
6486 }
6487
jiabin10a03f12021-05-07 23:46:28 +00006488 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006489 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006490 } else if (!std::equal(
6491 client->getSecondaryOutputs().begin(),
6492 client->getSecondaryOutputs().end(),
6493 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006494 if (!audio_is_linear_pcm(client->config().format)) {
6495 // If the format is not PCM, the tracks should be invalidated to get correct
6496 // behavior when the secondary output is changed.
6497 streamsToInvalidate.insert(client->stream());
6498 } else {
6499 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6500 std::vector<audio_io_handle_t> secondaryOutputIds;
6501 for (const auto &secondaryDesc: secondaryDescs) {
6502 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6503 weakSecondaryDescs.push_back(secondaryDesc);
6504 }
6505 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6506 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006507 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006508 }
6509 }
6510 }
jiabin10a03f12021-05-07 23:46:28 +00006511 if (!trackSecondaryOutputs.empty()) {
6512 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6513 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006514 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006515 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006516 mpClientInterface->invalidateStream(stream);
6517 }
6518}
6519
Eric Laurent2517af32020-11-25 15:31:27 +01006520bool AudioPolicyManager::isScoRequestedForComm() const {
6521 AudioDeviceTypeAddrVector devices;
6522 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6523 for (const auto &device : devices) {
6524 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6525 return true;
6526 }
6527 }
6528 return false;
6529}
6530
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006531bool AudioPolicyManager::isHearingAidUsedForComm() const {
6532 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6533 true /*fromCache*/);
6534 for (const auto &device : devices) {
6535 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6536 return true;
6537 }
6538 }
6539 return false;
6540}
6541
6542
Eric Laurente0720872014-03-11 09:30:41 -07006543void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006544{
François Gaffie53615e22015-03-19 09:24:12 +01006545 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006546 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006547 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006548 return;
6549 }
6550
Eric Laurent3a4311c2014-03-17 12:00:47 -07006551 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006552 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6553 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006554 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006555
6556 // if suspended, restore A2DP output if:
6557 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006558 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006559 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006560 //
Eric Laurentf732e072016-08-03 19:30:28 -07006561 // if not suspended, suspend A2DP output if:
6562 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006563 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006564 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006565 //
6566 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006567 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006568 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006569 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006570 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006571
6572 mpClientInterface->restoreOutput(a2dpOutput);
6573 mA2dpSuspended = false;
6574 }
6575 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006576 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006577 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006578 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006579 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006580
6581 mpClientInterface->suspendOutput(a2dpOutput);
6582 mA2dpSuspended = true;
6583 }
6584 }
6585}
6586
François Gaffie11d30102018-11-02 16:09:09 +01006587DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6588 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006589{
François Gaffie11d30102018-11-02 16:09:09 +01006590 DeviceVector devices;
6591
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006592 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006593 if (index >= 0) {
6594 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006595 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006596 ALOGV("%s device %s forced by patch %d", __func__,
6597 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6598 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006599 }
6600 }
6601
Dean Wheatley514b4312020-06-17 21:45:00 +10006602 // Do not retrieve engine device for outputs through MSD
6603 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6604 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6605 return outputDesc->devices();
6606 }
6607
Eric Laurent97ac8712018-07-27 18:59:02 -07006608 // Honor explicit routing requests only if no client using default routing is active on this
6609 // input: a specific app can not force routing for other apps by setting a preferred device.
6610 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006611 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006612 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006613 if (device != nullptr) {
6614 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006615 }
6616
François Gaffiea807ef92018-11-05 10:44:33 +01006617 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6618 // of setForceUse / Default Bus device here
6619 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6620 if (device != nullptr) {
6621 return DeviceVector(device);
6622 }
6623
François Gaffiec005e562018-11-06 15:04:49 +01006624 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6625 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6626 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306627 auto hasStreamActive = [&](auto stream) {
6628 return hasStream(streams, stream) && isStreamActive(stream, 0);
6629 };
Eric Laurent484e9272018-06-07 17:29:23 -07006630
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306631 auto doGetOutputDevicesForVoice = [&]() {
6632 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006633 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306634 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006635 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6636 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306637 };
6638
6639 // With low-latency playing on speaker, music on WFD, when the first low-latency
6640 // output is stopped, getNewOutputDevices checks for a product strategy
6641 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006642 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306643 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6644 // stream is associated to the output descriptor.
6645 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6646 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6647 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6648 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006649 // Retrieval of devices for voice DL is done on primary output profile, cannot
6650 // check the route (would force modifying configuration file for this profile)
6651 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6652 break;
6653 }
Eric Laurente552edb2014-03-10 17:42:56 -07006654 }
François Gaffiec005e562018-11-06 15:04:49 +01006655 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006656 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006657}
6658
François Gaffie11d30102018-11-02 16:09:09 +01006659sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6660 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006661{
François Gaffie11d30102018-11-02 16:09:09 +01006662 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006663
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006664 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006665 if (index >= 0) {
6666 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006667 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006668 ALOGV("getNewInputDevice() device %s forced by patch %d",
6669 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6670 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006671 }
6672 }
6673
Eric Laurent97ac8712018-07-27 18:59:02 -07006674 // Honor explicit routing requests only if no client using default routing is active on this
6675 // input: a specific app can not force routing for other apps by setting a preferred device.
6676 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006677 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6678 if (device != nullptr) {
6679 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006680 }
6681
Eric Laurentdc95a252018-04-12 12:46:56 -07006682 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006683 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006684 audio_attributes_t attributes;
6685 uid_t uid;
6686 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6687 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006688 attributes = topClient->attributes();
6689 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006690 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006691 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6692 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006693 }
6694
Francois Gaffie716e1432019-01-14 16:58:59 +01006695 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6696 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006697 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006698 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006699 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006700 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006701
Eric Laurente552edb2014-03-10 17:42:56 -07006702 return device;
6703}
6704
Eric Laurent794fde22016-03-11 09:50:45 -08006705bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6706 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006707 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006708}
6709
Dorin Drimusf2196d82022-01-03 12:11:18 +01006710// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006711status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006712 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006713 if (devices == nullptr) {
6714 return BAD_VALUE;
6715 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006716
6717 // Devices are determined in the following precedence:
6718 //
6719 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6720 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6721 //
6722 // If no such dynamic policy then
6723 // 2) Devices containing an active client using setPreferredDevice
6724 // with same strategy as the attributes.
6725 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6726 //
6727 // If no corresponding active client with setPreferredDevice then
6728 // 3) Devices associated with the strategy determined by the attributes
6729 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6730 //
6731 // See related getOutputForAttrInt().
6732
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006733 // check dynamic policies but only for primary descriptors (secondary not used for audible
6734 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006735 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006736 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6737 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006738 if (status != OK) {
6739 return status;
6740 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006741
6742 DeviceVector curDevices;
6743 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6744 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6745 // as they are unaffected by device/stream volume
6746 // (per SwAudioOutputDescriptor::isFixedVolume()).
6747 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6748 ) {
6749 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6750 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6751 curDevices.add(deviceDesc);
6752 } else {
6753 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6754 // which selects setPreferredDevice if active. This means forVolume call
6755 // will take an active setPreferredDevice, if such exists.
6756
6757 curDevices = mEngine->getOutputDevicesForAttributes(
6758 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006759 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006760
6761 if (forVolume) {
6762 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6763 // for single volume control in AudioService (such relationship should exist if
6764 // SPEAKER_SAFE is present).
6765 //
6766 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6767 DeviceVector speakerSafeDevices =
6768 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6769 if (!speakerSafeDevices.isEmpty()) {
6770 curDevices.merge(
6771 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6772 curDevices.remove(speakerSafeDevices);
6773 }
6774 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006775 for (const auto& device : curDevices) {
6776 devices->push_back(device->getDeviceTypeAddr());
6777 }
6778 return NO_ERROR;
6779}
6780
Eric Laurente0720872014-03-11 09:30:41 -07006781void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006782 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006783 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006784 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006785 updateDevicesAndOutputs();
6786 break;
6787 default:
6788 break;
6789 }
6790}
6791
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006792uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006793
6794 // skip beacon mute management if a dedicated TTS output is available
6795 if (mTtsOutputAvailable) {
6796 return 0;
6797 }
6798
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006799 switch(event) {
6800 case STARTING_OUTPUT:
6801 mBeaconMuteRefCount++;
6802 break;
6803 case STOPPING_OUTPUT:
6804 if (mBeaconMuteRefCount > 0) {
6805 mBeaconMuteRefCount--;
6806 }
6807 break;
6808 case STARTING_BEACON:
6809 mBeaconPlayingRefCount++;
6810 break;
6811 case STOPPING_BEACON:
6812 if (mBeaconPlayingRefCount > 0) {
6813 mBeaconPlayingRefCount--;
6814 }
6815 break;
6816 }
6817
6818 if (mBeaconMuteRefCount > 0) {
6819 // any playback causes beacon to be muted
6820 return setBeaconMute(true);
6821 } else {
6822 // no other playback: unmute when beacon starts playing, mute when it stops
6823 return setBeaconMute(mBeaconPlayingRefCount == 0);
6824 }
6825}
6826
6827uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6828 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6829 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6830 // keep track of muted state to avoid repeating mute/unmute operations
6831 if (mBeaconMuted != mute) {
6832 // mute/unmute AUDIO_STREAM_TTS on all outputs
6833 ALOGV("\t muting %d", mute);
6834 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006835 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6836 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6837 ALOGV("\t no tts volume source available");
6838 return 0;
6839 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006840 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006841 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006842 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006843 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006844 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006845 maxLatency = latency;
6846 }
6847 }
6848 mBeaconMuted = mute;
6849 return maxLatency;
6850 }
6851 return 0;
6852}
6853
Eric Laurente0720872014-03-11 09:30:41 -07006854void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006855{
François Gaffiec005e562018-11-06 15:04:49 +01006856 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006857 mPreviousOutputs = mOutputs;
6858}
6859
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006860uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006861 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006862 uint32_t delayMs)
6863{
6864 // mute/unmute strategies using an incompatible device combination
6865 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6866 // if unmuting, unmute only after the specified delay
6867 if (outputDesc->isDuplicated()) {
6868 return 0;
6869 }
6870
6871 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006872 DeviceVector devices = outputDesc->devices();
6873 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006874
François Gaffiec005e562018-11-06 15:04:49 +01006875 auto productStrategies = mEngine->getOrderedProductStrategies();
6876 for (const auto &productStrategy : productStrategies) {
6877 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6878 DeviceVector curDevices =
6879 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6880 curDevices = curDevices.filter(outputDesc->supportedDevices());
6881 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006882 bool doMute = false;
6883
François Gaffiec005e562018-11-06 15:04:49 +01006884 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006885 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006886 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6887 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006888 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006889 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006890 }
Eric Laurent99401132014-05-07 19:48:15 -07006891 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006892 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006893 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006894 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006895 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006896 continue;
6897 }
François Gaffiec005e562018-11-06 15:04:49 +01006898 ALOGVV("%s() %s (curDevice %s)", __func__,
6899 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6900 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6901 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006902 if (mute) {
6903 // FIXME: should not need to double latency if volume could be applied
6904 // immediately by the audioflinger mixer. We must account for the delay
6905 // between now and the next time the audioflinger thread for this output
6906 // will process a buffer (which corresponds to one buffer size,
6907 // usually 1/2 or 1/4 of the latency).
6908 if (muteWaitMs < desc->latency() * 2) {
6909 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006910 }
6911 }
6912 }
6913 }
6914 }
6915 }
6916
Eric Laurent99401132014-05-07 19:48:15 -07006917 // temporary mute output if device selection changes to avoid volume bursts due to
6918 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006919 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006920 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006921
Eric Laurentdc462862016-07-19 12:29:53 -07006922 if (muteWaitMs < tempMuteWaitMs) {
6923 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006924 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006925
6926 // If recommended duration is defined, replace temporary mute duration to avoid
6927 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6928 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6929 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6930 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6931 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6932
François Gaffieaaac0fd2018-11-22 17:56:39 +01006933 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6934 // make sure that we do not start the temporary mute period too early in case of
6935 // delayed device change
6936 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6937 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006938 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006939 }
6940 }
6941
Eric Laurente552edb2014-03-10 17:42:56 -07006942 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6943 if (muteWaitMs > delayMs) {
6944 muteWaitMs -= delayMs;
6945 usleep(muteWaitMs * 1000);
6946 return muteWaitMs;
6947 }
6948 return 0;
6949}
6950
François Gaffie11d30102018-11-02 16:09:09 +01006951uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6952 const DeviceVector &devices,
6953 bool force,
6954 int delayMs,
6955 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006956 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006957{
François Gaffie11d30102018-11-02 16:09:09 +01006958 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006959 uint32_t muteWaitMs;
6960
6961 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006962 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6963 nullptr /* patchHandle */, requiresMuteCheck);
6964 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6965 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006966 return muteWaitMs;
6967 }
Eric Laurente552edb2014-03-10 17:42:56 -07006968
6969 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006970 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006971 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006972 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006973
François Gaffie11d30102018-11-02 16:09:09 +01006974 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6975
6976 if (!filteredDevices.isEmpty()) {
6977 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006978 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006979
6980 // if the outputs are not materially active, there is no need to mute.
6981 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006982 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006983 } else {
6984 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6985 muteWaitMs = 0;
6986 }
Eric Laurente552edb2014-03-10 17:42:56 -07006987
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006988 bool outputRouted = outputDesc->isRouted();
6989
Eric Laurent79ea9582020-06-11 18:49:24 -07006990 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6991 // output profile or if new device is not supported AND previous device(s) is(are) still
6992 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006993 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006994 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6995 // restore previous device after evaluating strategy mute state
6996 outputDesc->setDevices(prevDevices);
6997 return muteWaitMs;
6998 }
6999
Eric Laurente552edb2014-03-10 17:42:56 -07007000 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007001 // the requested device is AUDIO_DEVICE_NONE
7002 // OR the requested device is the same as current device
7003 // AND force is not specified
7004 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007005 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007006 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007007 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7008 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007009 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7010 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7011 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7012 }
Eric Laurente552edb2014-03-10 17:42:56 -07007013 return muteWaitMs;
7014 }
7015
François Gaffie11d30102018-11-02 16:09:09 +01007016 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007017
Eric Laurente552edb2014-03-10 17:42:56 -07007018 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007019 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007020 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007021 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007022 PatchBuilder patchBuilder;
7023 patchBuilder.addSource(outputDesc);
7024 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7025 for (const auto &filteredDevice : filteredDevices) {
7026 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007027 }
7028
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007029 // Add half reported latency to delayMs when muteWaitMs is null in order
7030 // to avoid disordered sequence of muting volume and changing devices.
7031 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7032 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007033 }
Eric Laurente552edb2014-03-10 17:42:56 -07007034
7035 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007036 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007037
7038 return muteWaitMs;
7039}
7040
Eric Laurentc75307b2015-03-17 15:29:32 -07007041status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007042 int delayMs,
7043 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007044{
Eric Laurent6a94d692014-05-20 11:18:06 -07007045 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007046 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7047 return INVALID_OPERATION;
7048 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007049 if (patchHandle) {
7050 index = mAudioPatches.indexOfKey(*patchHandle);
7051 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007052 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007053 }
7054 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007055 return INVALID_OPERATION;
7056 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007057 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007058 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007059 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007060 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007061 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007062 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007063 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007064 return status;
7065}
7066
7067status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007068 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007069 bool force,
7070 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007071{
7072 status_t status = NO_ERROR;
7073
Eric Laurent1f2f2232014-06-02 12:01:23 -07007074 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007075 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7076 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007077
François Gaffie11d30102018-11-02 16:09:09 +01007078 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007079 PatchBuilder patchBuilder;
7080 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007081 // AUDIO_SOURCE_HOTWORD is for internal use only:
7082 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007083 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7084 auto result = usecase;
7085 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7086 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7087 }
7088 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007089 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007090 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007091 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007092 }
7093 }
7094 return status;
7095}
7096
Eric Laurent6a94d692014-05-20 11:18:06 -07007097status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7098 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007099{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007100 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007101 ssize_t index;
7102 if (patchHandle) {
7103 index = mAudioPatches.indexOfKey(*patchHandle);
7104 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007105 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007106 }
7107 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007108 return INVALID_OPERATION;
7109 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007110 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007111 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007112 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007113 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007114 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007115 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007116 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007117 return status;
7118}
7119
François Gaffie11d30102018-11-02 16:09:09 +01007120sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007121 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007122 audio_format_t& format,
7123 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007124 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007125{
7126 // Choose an input profile based on the requested capture parameters: select the first available
7127 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007128 //
7129 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7130 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007131
Glenn Kasten730b9262018-03-29 15:01:26 -07007132 sp<IOProfile> firstInexact;
7133 uint32_t updatedSamplingRate = 0;
7134 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7135 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007136 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007137 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007138 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007139 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007140 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007141 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007142 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007143 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007144 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007145 &channelMask /*updatedChannelMask*/,
7146 // FIXME ugly cast
7147 (audio_output_flags_t) flags,
7148 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007149 return profile;
7150 }
François Gaffie11d30102018-11-02 16:09:09 +01007151 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007152 samplingRate,
7153 &updatedSamplingRate,
7154 format,
7155 &updatedFormat,
7156 channelMask,
7157 &updatedChannelMask,
7158 // FIXME ugly cast
7159 (audio_output_flags_t) flags,
7160 false /*exactMatchRequiredForInputFlags*/)) {
7161 firstInexact = profile;
7162 }
7163
Eric Laurente552edb2014-03-10 17:42:56 -07007164 }
7165 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007166 if (firstInexact != nullptr) {
7167 samplingRate = updatedSamplingRate;
7168 format = updatedFormat;
7169 channelMask = updatedChannelMask;
7170 return firstInexact;
7171 }
Eric Laurente552edb2014-03-10 17:42:56 -07007172 return NULL;
7173}
7174
François Gaffieaaac0fd2018-11-22 17:56:39 +01007175float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7176 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007177 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007178 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007179{
jiabin9a3361e2019-10-01 09:38:30 -07007180 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007181
7182 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7183 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7184 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7185 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007186 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7187 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7188 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7189 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7190 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007191
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007192 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007193 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7194 mOutputs.isActive(ringVolumeSrc, 0)) {
7195 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007196 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007197 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007198 }
7199
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007200 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007201 if ((volumeSource != callVolumeSrc && (isInCall() ||
7202 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007203 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007204 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7205 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007206 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7207 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7208 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007209 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007210 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007211 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007212 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007213 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007214 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007215 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7216 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7217 // programmatically muted.
7218 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7219 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7220 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007221 bool exemptFromCapping =
7222 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7223 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007224 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7225 volumeSource, volumeDb);
7226 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007227 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7228 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7229 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007230 }
7231 }
Eric Laurente552edb2014-03-10 17:42:56 -07007232 // if a headset is connected, apply the following rules to ring tones and notifications
7233 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007234 // - always attenuate notifications volume by 6dB
7235 // - attenuate ring tones volume by 6dB unless music is not playing and
7236 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007237 // - if music is playing, always limit the volume to current music volume,
7238 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007239 if (!Intersection(deviceTypes,
7240 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7241 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007242 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7243 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007244 ((volumeSource == alarmVolumeSrc ||
7245 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007246 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7247 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7248 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007249 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7250 curves.canBeMuted()) {
7251
Eric Laurente552edb2014-03-10 17:42:56 -07007252 // when the phone is ringing we must consider that music could have been paused just before
7253 // by the music application and behave as if music was active if the last music track was
7254 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007255 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007256 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007257 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007258 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007259 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7260 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007261 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007262 float musicVolDb = computeVolume(musicCurves,
7263 musicVolumeSrc,
7264 musicCurves.getVolumeIndex(musicDevice),
7265 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007266 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7267 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7268 if (volumeDb > minVolDb) {
7269 volumeDb = minVolDb;
7270 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007271 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007272 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7273 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7274 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007275 // on A2DP, also ensure notification volume is not too low compared to media when
7276 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007277 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007278 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007279 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7280 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007281 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7282 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007283 }
7284 }
jiabin9a3361e2019-10-01 09:38:30 -07007285 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007286 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007287 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007288 }
7289 }
7290
François Gaffie43c73442018-11-08 08:21:55 +01007291 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007292}
7293
Eric Laurent3839bc02018-07-10 18:33:34 -07007294int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007295 VolumeSource fromVolumeSource,
7296 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007297{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007298 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007299 return srcIndex;
7300 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007301 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7302 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007303 float minSrc = (float)srcCurves.getVolumeIndexMin();
7304 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7305 float minDst = (float)dstCurves.getVolumeIndexMin();
7306 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007307
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007308 // preserve mute request or correct range
7309 if (srcIndex < minSrc) {
7310 if (srcIndex == 0) {
7311 return 0;
7312 }
7313 srcIndex = minSrc;
7314 } else if (srcIndex > maxSrc) {
7315 srcIndex = maxSrc;
7316 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007317 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7318}
7319
François Gaffieaaac0fd2018-11-22 17:56:39 +01007320status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7321 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007322 int index,
7323 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007324 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007325 int delayMs,
7326 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007327{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007328 // do not change actual attributes volume if the attributes is muted
7329 if (outputDesc->isMuted(volumeSource)) {
7330 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7331 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007332 return NO_ERROR;
7333 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007334 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7335 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7336 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7337 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007338
Eric Laurent2517af32020-11-25 15:31:27 +01007339 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007340 bool isHAUsed = isHearingAidUsedForComm();
7341
Eric Laurente552edb2014-03-10 17:42:56 -07007342 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007343 // if sco and call follow same curves, bypass forceUseForComm
7344 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007345 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007346 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007347 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007348 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007349 // Do not return an error here as AudioService will always set both voice call
7350 // and bluetooth SCO volumes due to stream aliasing.
7351 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007352 }
jiabin9a3361e2019-10-01 09:38:30 -07007353 if (deviceTypes.empty()) {
7354 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007355 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007356
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007357 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7358 ALOGE("invalid volume index range");
7359 return BAD_VALUE;
7360 }
7361
jiabin9a3361e2019-10-01 09:38:30 -07007362 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7363 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007364 // Force VoIP volume to max for bluetooth SCO device except if muted
7365 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007366 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007367 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007368 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007369 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007370 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007371 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007372
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007373 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007374 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007375 // 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 +01007376 if (isVoiceVolSrc) {
7377 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007378 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007379 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007380 }
Eric Laurent18fba842016-03-31 14:41:26 -07007381 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007382 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7383 mLastVoiceVolume = voiceVolume;
7384 }
7385 }
Eric Laurente552edb2014-03-10 17:42:56 -07007386 return NO_ERROR;
7387}
7388
Eric Laurentc75307b2015-03-17 15:29:32 -07007389void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007390 const DeviceTypeSet& deviceTypes,
7391 int delayMs,
7392 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007393{
jiabincd510522020-01-22 09:40:55 -08007394 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007395 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7396 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7397 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007398 curves.getVolumeIndex(deviceTypes),
7399 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007400 }
7401}
7402
François Gaffiec005e562018-11-06 15:04:49 +01007403void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7404 bool on,
7405 const sp<AudioOutputDescriptor>& outputDesc,
7406 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007407 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007408{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007409 std::vector<VolumeSource> sourcesToMute;
7410 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7411 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7412 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007413 VolumeSource source = toVolumeSource(attributes, false);
7414 if ((source != VOLUME_SOURCE_NONE) &&
7415 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7416 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007417 sourcesToMute.push_back(source);
7418 }
Eric Laurente552edb2014-03-10 17:42:56 -07007419 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007420 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007421 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007422 }
7423
Eric Laurente552edb2014-03-10 17:42:56 -07007424}
7425
François Gaffieaaac0fd2018-11-22 17:56:39 +01007426void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7427 bool on,
7428 const sp<AudioOutputDescriptor>& outputDesc,
7429 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007430 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007431{
jiabin9a3361e2019-10-01 09:38:30 -07007432 if (deviceTypes.empty()) {
7433 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007434 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007435 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007436 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007437 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007438 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007439 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007440 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7441 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007442 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007443 }
7444 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007445 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7446 // ignored
7447 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007448 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007449 if (!outputDesc->isMuted(volumeSource)) {
7450 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007451 return;
7452 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007453 if (outputDesc->decMuteCount(volumeSource) == 0) {
7454 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007455 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007456 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007457 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007458 delayMs);
7459 }
7460 }
7461}
7462
François Gaffie53615e22015-03-19 09:24:12 +01007463bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7464{
François Gaffiec005e562018-11-06 15:04:49 +01007465 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007466 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7467 return true;
7468 }
7469
7470 // has known usage?
7471 switch (paa->usage) {
7472 case AUDIO_USAGE_UNKNOWN:
7473 case AUDIO_USAGE_MEDIA:
7474 case AUDIO_USAGE_VOICE_COMMUNICATION:
7475 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7476 case AUDIO_USAGE_ALARM:
7477 case AUDIO_USAGE_NOTIFICATION:
7478 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7479 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7480 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7481 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7482 case AUDIO_USAGE_NOTIFICATION_EVENT:
7483 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7484 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7485 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7486 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007487 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007488 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007489 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007490 case AUDIO_USAGE_EMERGENCY:
7491 case AUDIO_USAGE_SAFETY:
7492 case AUDIO_USAGE_VEHICLE_STATUS:
7493 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007494 break;
7495 default:
7496 return false;
7497 }
7498 return true;
7499}
7500
François Gaffie2110e042015-03-24 08:41:51 +01007501audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7502{
7503 return mEngine->getForceUse(usage);
7504}
7505
Eric Laurent96d1dda2022-03-14 17:14:19 +01007506bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007507 return isStateInCall(mEngine->getPhoneState());
7508}
7509
Eric Laurent96d1dda2022-03-14 17:14:19 +01007510bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007511 return is_state_in_call(state);
7512}
7513
Eric Laurentf9cccec2022-11-16 19:12:00 +01007514bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007515 audio_mode_t mode = mEngine->getPhoneState();
7516 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007517 || (mode == AUDIO_MODE_CALL_SCREEN)
7518 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007519}
7520
Eric Laurentf9cccec2022-11-16 19:12:00 +01007521bool AudioPolicyManager::isInCallOrScreening() const {
7522 audio_mode_t mode = mEngine->getPhoneState();
7523 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7524}
7525
Eric Laurentd60560a2015-04-10 11:31:20 -07007526void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7527{
7528 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007529 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007530 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007531 sourceDesc->sinkDevice()->equals(deviceDesc))
7532 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007533 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007534 }
7535 }
7536
7537 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7538 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7539 bool release = false;
7540 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7541 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7542 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7543 source->ext.device.type == deviceDesc->type()) {
7544 release = true;
7545 }
7546 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007547 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007548 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7549 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7550 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007551 sink->ext.device.type == deviceDesc->type() &&
7552 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7553 || strncmp(sink->ext.device.address, address,
7554 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007555 release = true;
7556 }
7557 }
7558 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007559 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7560 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007561 }
7562 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007563
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007564 mInputs.clearSessionRoutesForDevice(deviceDesc);
7565
Francois Gaffie716e1432019-01-14 16:58:59 +01007566 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007567}
7568
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007569void AudioPolicyManager::modifySurroundFormats(
7570 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007571 std::unordered_set<audio_format_t> enforcedSurround(
7572 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007573 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7574 for (const auto& pair : mConfig.getSurroundFormats()) {
7575 allSurround.insert(pair.first);
7576 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7577 }
Phil Burk09bc4612016-02-24 15:58:15 -08007578
7579 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7580 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007581 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007582 // This is the resulting set of formats depending on the surround mode:
7583 // 'all surround' = allSurround
7584 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7585 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7586 // 'manual surround' = mManualSurroundFormats
7587 // AUTO: formats v 'enforced surround'
7588 // ALWAYS: formats v 'all surround' v 'enforced surround'
7589 // NEVER: formats ^ 'non-surround'
7590 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007591
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007592 std::unordered_set<audio_format_t> formatSet;
7593 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7594 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007595 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007596 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007597 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007598 formatSet.insert(*formatIter);
7599 }
7600 }
7601 } else {
7602 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7603 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007604 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007605
jiabin81772902018-04-02 17:52:27 -07007606 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007607 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007608 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7609 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7610 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007611 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007612 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7613 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7614 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007615 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007616 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007617 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007618 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007619 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007620 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007621}
7622
jiabin06e4bab2019-07-29 10:13:34 -07007623void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7624 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007625 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7626 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7627
7628 // If NEVER, then remove support for channelMasks > stereo.
7629 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007630 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7631 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007632 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007633 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007634 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007635 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007636 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007637 }
7638 }
jiabin81772902018-04-02 17:52:27 -07007639 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7640 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7641 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007642 bool supports5dot1 = false;
7643 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007644 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007645 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7646 supports5dot1 = true;
7647 break;
7648 }
7649 }
7650 // If not then add 5.1 support.
7651 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007652 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007653 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007654 }
Phil Burk09bc4612016-02-24 15:58:15 -08007655 }
7656}
7657
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007658void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007659 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007660 AudioProfileVector &profiles)
7661{
7662 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007663 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007664
François Gaffie112b0af2015-11-19 16:13:25 +01007665 // Format MUST be checked first to update the list of AudioProfile
7666 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007667 reply = mpClientInterface->getParameters(
7668 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007669 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007670 AudioParameter repliedParameters(reply);
7671 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007672 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007673 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7674 return;
7675 }
Phil Burk09bc4612016-02-24 15:58:15 -08007676 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007677 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007678 if (device == AUDIO_DEVICE_OUT_HDMI
7679 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007680 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007681 }
jiabin3e277cc2019-09-10 14:27:34 -07007682 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007683 }
François Gaffie112b0af2015-11-19 16:13:25 +01007684
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007685 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007686 ChannelMaskSet channelMasks;
7687 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007688 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007689 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007690
7691 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007692 reply = mpClientInterface->getParameters(
7693 ioHandle,
7694 requestedParameters.toString() + ";" +
7695 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007696 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007697 AudioParameter repliedParameters(reply);
7698 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007699 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007700 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007701 }
7702 }
7703 if (profiles.hasDynamicChannelsFor(format)) {
7704 reply = mpClientInterface->getParameters(ioHandle,
7705 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007706 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007707 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007708 AudioParameter repliedParameters(reply);
7709 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007710 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007711 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007712 if (device == AUDIO_DEVICE_OUT_HDMI
7713 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007714 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007715 }
François Gaffie112b0af2015-11-19 16:13:25 +01007716 }
7717 }
jiabin3e277cc2019-09-10 14:27:34 -07007718 addDynamicAudioProfileAndSort(
7719 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007720 }
7721}
Eric Laurentd60560a2015-04-10 11:31:20 -07007722
Mikhail Naganovdc769682018-05-04 15:34:08 -07007723status_t AudioPolicyManager::installPatch(const char *caller,
7724 audio_patch_handle_t *patchHandle,
7725 AudioIODescriptorInterface *ioDescriptor,
7726 const struct audio_patch *patch,
7727 int delayMs)
7728{
7729 ssize_t index = mAudioPatches.indexOfKey(
7730 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7731 *patchHandle : ioDescriptor->getPatchHandle());
7732 sp<AudioPatch> patchDesc;
7733 status_t status = installPatch(
7734 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7735 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007736 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007737 }
7738 return status;
7739}
7740
7741status_t AudioPolicyManager::installPatch(const char *caller,
7742 ssize_t index,
7743 audio_patch_handle_t *patchHandle,
7744 const struct audio_patch *patch,
7745 int delayMs,
7746 uid_t uid,
7747 sp<AudioPatch> *patchDescPtr)
7748{
7749 sp<AudioPatch> patchDesc;
7750 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7751 if (index >= 0) {
7752 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007753 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007754 }
7755
7756 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7757 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7758 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7759 if (status == NO_ERROR) {
7760 if (index < 0) {
7761 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007762 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007763 } else {
7764 patchDesc->mPatch = *patch;
7765 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007766 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007767 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007768 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007769 }
7770 nextAudioPortGeneration();
7771 mpClientInterface->onAudioPatchListUpdate();
7772 }
7773 if (patchDescPtr) *patchDescPtr = patchDesc;
7774 return status;
7775}
7776
jiabinbce0c1d2020-10-05 11:20:18 -07007777bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7778{
7779 const TrackClientVector activeClients = output->getActiveClients();
7780 if (activeClients.empty()) {
7781 return true;
7782 }
7783 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7784 if (index < 0) {
7785 ALOGE("%s, no audio patch found while there are active clients on output %d",
7786 __func__, output->getId());
7787 return false;
7788 }
7789 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7790 DeviceVector routedDevices;
7791 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7792 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7793 patchDesc->mPatch.sinks[i].id);
7794 if (device == nullptr) {
7795 ALOGE("%s, no audio device found with id(%d)",
7796 __func__, patchDesc->mPatch.sinks[i].id);
7797 return false;
7798 }
7799 routedDevices.add(device);
7800 }
7801 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007802 if (client->isInvalid()) {
7803 // No need to take care about invalidated clients.
7804 continue;
7805 }
jiabinbce0c1d2020-10-05 11:20:18 -07007806 sp<DeviceDescriptor> preferredDevice =
7807 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7808 if (mEngine->getOutputDevicesForAttributes(
7809 client->attributes(), preferredDevice, false) == routedDevices) {
7810 return false;
7811 }
7812 }
7813 return true;
7814}
7815
7816sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007817 const sp<IOProfile>& profile, const DeviceVector& devices,
7818 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007819{
7820 for (const auto& device : devices) {
7821 // TODO: This should be checking if the profile supports the device combo.
7822 if (!profile->supportsDevice(device)) {
7823 return nullptr;
7824 }
7825 }
7826 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7827 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007828 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007829 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7830 if (status != NO_ERROR) {
7831 return nullptr;
7832 }
7833
7834 // Here is where the out_set_parameters() for card & device gets called
7835 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7836 const audio_devices_t deviceType = device->type();
7837 const String8 &address = String8(device->address().c_str());
7838 if (!address.isEmpty()) {
7839 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7840 mpClientInterface->setParameters(output, String8(param));
7841 free(param);
7842 }
7843 updateAudioProfiles(device, output, profile->getAudioProfiles());
7844 if (!profile->hasValidAudioProfile()) {
7845 ALOGW("%s() missing param", __func__);
7846 desc->close();
7847 return nullptr;
7848 } else if (profile->hasDynamicAudioProfile()) {
7849 desc->close();
7850 output = AUDIO_IO_HANDLE_NONE;
7851 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7852 profile->pickAudioProfile(
7853 config.sample_rate, config.channel_mask, config.format);
7854 config.offload_info.sample_rate = config.sample_rate;
7855 config.offload_info.channel_mask = config.channel_mask;
7856 config.offload_info.format = config.format;
7857
Eric Laurentb4f42a92022-01-17 17:37:31 +01007858 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007859 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7860 if (status != NO_ERROR) {
7861 return nullptr;
7862 }
7863 }
7864
7865 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007866
jiabinbce0c1d2020-10-05 11:20:18 -07007867 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7868 sp<AudioPolicyMix> policyMix;
7869 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7870 policyMix->setOutput(desc);
7871 desc->mPolicyMix = policyMix;
7872 } else {
7873 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7874 address.string());
7875 }
7876
Eric Laurentb4f42a92022-01-17 17:37:31 +01007877 } else if (hasPrimaryOutput() && profile->getModule()
7878 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7879 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7880 // no duplicated output for:
7881 // - direct outputs
7882 // - outputs used by dynamic policy mixes
7883 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007884 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7885
7886 //TODO: configure audio effect output stage here
7887
7888 // open a duplicating output thread for the new output and the primary output
7889 sp<SwAudioOutputDescriptor> dupOutputDesc =
7890 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7891 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7892 if (status == NO_ERROR) {
7893 // add duplicated output descriptor
7894 addOutput(duplicatedOutput, dupOutputDesc);
7895 } else {
7896 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7897 mPrimaryOutput->mIoHandle, output);
7898 desc->close();
7899 removeOutput(output);
7900 nextAudioPortGeneration();
7901 return nullptr;
7902 }
7903 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007904 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7905 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7906 mPrimaryOutput = desc;
7907 }
jiabinbce0c1d2020-10-05 11:20:18 -07007908 return desc;
7909}
7910
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007911} // namespace android