blob: 776cc0e88a999a2cfbc2486141b264b38ba7ac9a [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080037#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110038#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070039
40#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010041#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070042#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070044#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070045#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070046#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070047#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070048#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070049#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <utils/Log.h>
51
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010053#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010057using android::media::audio::common::AudioDevice;
58using android::media::audio::common::AudioDeviceAddress;
59using android::media::audio::common::AudioPortDeviceExt;
60using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000061using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070062
Eric Laurentdc462862016-07-19 12:29:53 -070063//FIXME: workaround for truncated touch sounds
64// to be removed when the problem is handled by system UI
65#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070066
67// Largest difference in dB on earpiece in call between the voice volume and another
68// media / notification / system volume.
69constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
70
Mikhail Naganov15be9d22017-11-08 14:18:13 +110071// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110072static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
73 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110074 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
75// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110076static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110077 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
78 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
79 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
80
jiabin06e4bab2019-07-29 10:13:34 -070081template <typename T>
82bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
83{
84 if (left.size() != right.size()) {
85 return false;
86 }
87 for (size_t index = 0; index < right.size(); index++) {
88 if (left[index] != right[index]) {
89 return false;
90 }
91 }
92 return true;
93}
94
95template <typename T>
96bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
97{
98 return !(left == right);
99}
100
Eric Laurente552edb2014-03-10 17:42:56 -0700101// ----------------------------------------------------------------------------
102// AudioPolicyInterface implementation
103// ----------------------------------------------------------------------------
104
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100105status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
106 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
107 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800108 nextAudioPortGeneration();
109 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110}
111
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100112status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
113 audio_policy_dev_state_t state,
114 const char* device_address,
115 const char* device_name,
116 audio_format_t encodedFormat) {
117 media::AudioPort aidlPort;
118 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
119 status == OK) {
120 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
121 } else {
122 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
123 return status;
124 }
125}
126
François Gaffie11d30102018-11-02 16:09:09 +0100127void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
128 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200129{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000130 audio_port_v7 devicePort;
131 device->toAudioPort(&devicePort);
132 if (status_t status = mpClientInterface->setDeviceConnectedState(
133 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
134 status != OK) {
135 ALOGE("Error %d while setting connected state for device %s", status,
136 device->getDeviceTypeAddr().toString(false).c_str());
137 }
François Gaffie44481e72016-04-20 07:49:57 +0200138}
139
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100140status_t AudioPolicyManager::setDeviceConnectionStateInt(
141 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
142 audio_format_t encodedFormat) {
143 // TODO: b/211601178 Forward 'port' to Audio HAL via mHwModules. For now, only device_type,
144 // device_address and device_name are forwarded.
145 if (port.ext.getTag() != AudioPortExt::device) {
146 return BAD_VALUE;
147 }
148 audio_devices_t device_type;
149 std::string device_address;
150 if (status_t status = aidl2legacy_AudioDevice_audio_device(
151 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
152 status != OK) {
153 return status;
154 };
155 const char* device_name = port.name.c_str();
156 // connect/disconnect only 1 device at a time
157 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
158 return BAD_VALUE;
159
160 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
161 device_type, device_address.c_str(), device_name, encodedFormat,
162 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
163 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
164}
165
François Gaffie11d30102018-11-02 16:09:09 +0100166status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800167 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100168 const char* device_address,
169 const char* device_name,
170 audio_format_t encodedFormat) {
171 media::AudioPort aidlPort;
172 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
173 status == OK) {
174 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
175 } else {
176 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
177 return status;
178 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179}
Paul McLeane743a472015-01-28 11:07:31 -0800180
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
182 audio_policy_dev_state_t state)
183{
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700185 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700186 SortedVector <audio_io_handle_t> outputs;
187
François Gaffie11d30102018-11-02 16:09:09 +0100188 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 // save a copy of the opened output descriptors before any output is opened or closed
191 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
192 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700193 switch (state)
194 {
195 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800196 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700197 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100198 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700199 return INVALID_OPERATION;
200 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800201 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700202 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Eric Laurente552edb2014-03-10 17:42:56 -0700204 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200205 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700206 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700207 }
208
François Gaffie44481e72016-04-20 07:49:57 +0200209 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
210 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100211 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200212
François Gaffie11d30102018-11-02 16:09:09 +0100213 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
214 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200215
Francois Gaffie716e1432019-01-14 16:58:59 +0100216 mHwModules.cleanUpForDevice(device);
217
François Gaffie11d30102018-11-02 16:09:09 +0100218 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700219 return INVALID_OPERATION;
220 }
François Gaffie2110e042015-03-24 08:41:51 +0100221
jiabin1c4794b2020-05-05 10:08:05 -0700222 // Populate encapsulation information when a output device is connected.
223 device->setEncapsulationInfoFromHal(mpClientInterface);
224
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700225 // outputs should never be empty here
226 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
227 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100228 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800229
Eric Laurent3ae5f312015-02-03 17:12:08 -0800230 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700231 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700232 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700235 return INVALID_OPERATION;
236 }
237
François Gaffie11d30102018-11-02 16:09:09 +0100238 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700239
Paul McLeane743a472015-01-28 11:07:31 -0800240 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100241 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700242
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100244 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700245
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100246 mOutputs.clearSessionRoutesForDevice(device);
247
François Gaffie11d30102018-11-02 16:09:09 +0100248 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100249
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800250 // Reset active device codec
251 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
252
Kriti Dangef6be8f2020-11-05 11:58:19 +0100253 // remove device from mReportedFormatsMap cache
254 mReportedFormatsMap.erase(device);
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 } break;
257
258 default:
François Gaffie11d30102018-11-02 16:09:09 +0100259 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700260 return BAD_VALUE;
261 }
262
Eric Laurent736a1022019-03-27 18:28:46 -0700263 // Propagate device availability to Engine
264 setEngineDeviceConnectionState(device, state);
265
Eric Laurentae970022019-01-29 14:25:04 -0800266 // No need to evaluate playback routing when connecting a remote submix
267 // output device used by a dynamic policy of type recorder as no
268 // playback use case is affected.
269 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700270 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800271 for (audio_io_handle_t output : outputs) {
272 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800273 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
274 if (policyMix != nullptr
275 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700276 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800277 doCheckForDeviceAndOutputChanges = false;
278 break;
279 }
280 }
281 }
282
283 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700284 // outputs must be closed after checkOutputForAllStrategies() is executed
285 if (!outputs.isEmpty()) {
286 for (audio_io_handle_t output : outputs) {
287 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100288 // close unused outputs after device disconnection or direct outputs that have
289 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200290 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
291 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurent39095982021-08-24 18:29:27 +0200292 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200293 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700294 closeOutput(output);
295 }
Eric Laurente552edb2014-03-10 17:42:56 -0700296 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
298 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800301 };
302
303 if (doCheckForDeviceAndOutputChanges) {
304 checkForDeviceAndOutputChanges(checkCloseOutputs);
305 } else {
306 checkCloseOutputs();
307 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100308 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700309 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100310 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700311 const DeviceVector activeMediaDevices =
312 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700313 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700314 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530315 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
316 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100317 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700318 // do not force device change on duplicated output because if device is 0, it will
319 // also force a device 0 for the two outputs it is duplicated to which may override
320 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100321 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100322 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700323 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 // always force when disconnecting (a non-duplicated device)
325 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100326 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 }
jiabinbce0c1d2020-10-05 11:20:18 -0700328 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000329 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700330 desc->supportsDevicesForPlayback(activeMediaDevices)) {
331 // Reopen the output to query the dynamic profiles when there is not active
332 // clients or all active clients will be rerouted. Otherwise, set the flag
333 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
334 // can be reopened to query dynamic profiles when all clients are inactive.
335 if (areAllActiveTracksRerouted(desc)) {
336 outputsToReopen.push_back(mOutputs.keyAt(i));
337 } else {
338 desc->mPendingReopenToQueryProfiles = true;
339 }
340 }
341 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
342 // Clear the flag that previously set for re-querying profiles.
343 desc->mPendingReopenToQueryProfiles = false;
344 }
345 }
346 for (const auto& output : outputsToReopen) {
347 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
348 closeOutput(output);
349 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700350 }
351
Eric Laurentd60560a2015-04-10 11:31:20 -0700352 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100353 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700354 }
355
Eric Laurent72aa32f2014-05-30 18:51:48 -0700356 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700357 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700358 } // end if is output device
359
Eric Laurente552edb2014-03-10 17:42:56 -0700360 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700361 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100362 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700363 switch (state)
364 {
365 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700366 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100368 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700369 return INVALID_OPERATION;
370 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700371
372 if (mAvailableInputDevices.add(device) < 0) {
373 return NO_MEMORY;
374 }
375
François Gaffie44481e72016-04-20 07:49:57 +0200376 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
377 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100378 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200379
Eric Laurent0dd51852019-04-19 18:18:58 -0700380 if (checkInputsForDevice(device, state) != NO_ERROR) {
381 mAvailableInputDevices.remove(device);
382
François Gaffie11d30102018-11-02 16:09:09 +0100383 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100384
385 mHwModules.cleanUpForDevice(device);
386
Eric Laurentd4692962014-05-05 18:13:44 -0700387 return INVALID_OPERATION;
388 }
389
Eric Laurentd4692962014-05-05 18:13:44 -0700390 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700391
392 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700393 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700394 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700396 return INVALID_OPERATION;
397 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700398
François Gaffie11d30102018-11-02 16:09:09 +0100399 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700400
401 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100402 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700403
François Gaffie11d30102018-11-02 16:09:09 +0100404 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700405
406 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100407
408 // remove device from mReportedFormatsMap cache
409 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 default:
François Gaffie11d30102018-11-02 16:09:09 +0100413 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700414 return BAD_VALUE;
415 }
416
Eric Laurent736a1022019-03-27 18:28:46 -0700417 // Propagate device availability to Engine
418 setEngineDeviceConnectionState(device, state);
419
Eric Laurent0dd51852019-04-19 18:18:58 -0700420 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700421 // As the input device list can impact the output device selection, update
422 // getDeviceForStrategy() cache
423 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700424
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100425 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200426 // Reconnect Audio Source
427 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
428 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
429 checkAudioSourceForAttributes(attributes);
430 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700431 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100432 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700433 }
434
Eric Laurentb52c1522014-05-20 11:27:36 -0700435 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700436 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700437 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700438
François Gaffie11d30102018-11-02 16:09:09 +0100439 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700440 return BAD_VALUE;
441}
442
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100443status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
444 const char* device_name,
445 media::AudioPort* aidlPort) {
446 DeviceDescriptorBase devDescr(device, device_address);
447 devDescr.setName(device_name);
448 return devDescr.writeToParcelable(aidlPort);
449}
450
Eric Laurent736a1022019-03-27 18:28:46 -0700451void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
452 audio_policy_dev_state_t state) {
453
454 // the Engine does not have to know about remote submix devices used by dynamic audio policies
455 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
456 return;
457 }
458 mEngine->setDeviceConnectionState(device, state);
459}
460
461
Eric Laurente0720872014-03-11 09:30:41 -0700462audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100463 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700464{
Eric Laurent634b7142016-04-20 13:48:02 -0700465 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800466 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
467 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700468 (strlen(device_address) != 0)/*matchAddress*/);
469
470 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100471 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700472 device, device_address);
473 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
474 }
François Gaffie53615e22015-03-19 09:24:12 +0100475
Eric Laurent3a4311c2014-03-17 12:00:47 -0700476 DeviceVector *deviceVector;
477
Eric Laurente552edb2014-03-10 17:42:56 -0700478 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700479 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700480 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700481 deviceVector = &mAvailableInputDevices;
482 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100483 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700484 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700485 }
Eric Laurent634b7142016-04-20 13:48:02 -0700486
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800487 return (deviceVector->getDevice(
488 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700489 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800490}
491
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800492status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
493 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800494 const char *device_name,
495 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800496{
497 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700498 String8 reply;
499 AudioParameter param;
500 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800502 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
503 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800505 // connect/disconnect only 1 device at a time
506 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
507
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700509 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800511 // Nothing to do: device is not connected
512 return NO_ERROR;
513 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800514 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800515
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700516 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 // configure codecs.
518 // Handle two specific cases by sending a set parameter to
519 // configure A2DP codecs. No need to toggle device state.
520 // Case 1: A2DP active device switches from primary to primary
521 // module
522 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200523 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700524 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
526 if (availablePrimaryOutputDevices().contains(devDesc) &&
527 (module != 0 && module->getHandle() == primaryHandle)) {
528 reply = mpClientInterface->getParameters(
529 AUDIO_IO_HANDLE_NONE,
530 String8(AudioParameter::keyReconfigA2dpSupported));
531 AudioParameter repliedParameters(reply);
532 repliedParameters.getInt(
533 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
534 if (isReconfigA2dpSupported) {
535 const String8 key(AudioParameter::keyReconfigA2dp);
536 param.add(key, String8("true"));
537 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
538 devDesc->setEncodedFormat(encodedFormat);
539 return NO_ERROR;
540 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700541 }
542 }
cnx421bd2dcc42020-07-11 14:58:44 +0800543 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
544 for (size_t i = 0; i < mOutputs.size(); i++) {
545 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
546 // mute media strategies and delay device switch by the largest
547 // This avoid sending the music tail into the earpiece or headset.
548 setStrategyMute(musicStrategy, true, desc);
549 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
550 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
551 nullptr, true /*fromCache*/).types());
552 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800553 // Toggle the device state: UNAVAILABLE -> AVAILABLE
554 // This will force reading again the device configuration
555 status = setDeviceConnectionState(device,
556 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800557 device_address, device_name,
558 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800559 if (status != NO_ERROR) {
560 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
561 status);
562 return status;
563 }
564
565 status = setDeviceConnectionState(device,
566 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800567 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 if (status != NO_ERROR) {
569 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
570 status);
571 return status;
572 }
573
574 return NO_ERROR;
575}
576
Pattydd807582021-11-04 21:01:03 +0800577status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
578 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800579{
Pattydd807582021-11-04 21:01:03 +0800580 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800581 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800582 std::unordered_set<audio_format_t> formatSet;
583 sp<HwModule> primaryModule =
584 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700585 if (primaryModule == nullptr) {
586 ALOGE("%s() unable to get primary module", __func__);
587 return NO_INIT;
588 }
Pattydd807582021-11-04 21:01:03 +0800589
590 DeviceTypeSet audioDeviceSet;
591
592 switch(device) {
593 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
594 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
595 break;
596 case AUDIO_DEVICE_OUT_BLE_HEADSET:
597 audioDeviceSet = getAudioDeviceOutAllBleSet();
598 break;
599 default:
600 ALOGE("%s() device type 0x%08x not supported", __func__, device);
601 return BAD_VALUE;
602 }
603
jiabin9a3361e2019-10-01 09:38:30 -0700604 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800605 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800606 for (const auto& device : declaredDevices) {
607 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800608 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800609 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800610 return status;
611}
612
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100613DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
614{
615 DeviceVector rxSinkdevices{};
616 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
617 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
618 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
619 auto rxSinkDevice = rxSinkdevices.itemAt(0);
620 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
621 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
622 // retrieve Rx Source device descriptor
623 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
624 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
625
626 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
627 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
628 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
629 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
630 return DeviceVector(rxSinkDevice);
631 }
632 }
633 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
634 // the device returned is not necessarily reachable via this output
635 // (filter later by setOutputDevices())
636 return getNewOutputDevices(mPrimaryOutput, fromCache);
637}
638
639status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
640{
641 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
642 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
643 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
644 }
645 return INVALID_OPERATION;
646}
647
648status_t AudioPolicyManager::updateCallRoutingInternal(
649 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700650{
651 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100652 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700653 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700654 if(!hasPrimaryOutput() ||
655 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100656 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700657 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100658 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100659
Francois Gaffie716e1432019-01-14 16:58:59 +0100660 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100661 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100663
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100664 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100665 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700666
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200667 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668 // release TX patch if any
669 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100670 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671 mCallTxPatch.clear();
672 }
673
François Gaffie9eb18552018-11-05 10:33:26 +0100674 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700675 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100676 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700677 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100678 // retrieve Rx Source and Tx Sink device descriptors
679 sp<DeviceDescriptor> rxSourceDevice =
680 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
681 String8(),
682 AUDIO_FORMAT_DEFAULT);
683 sp<DeviceDescriptor> txSinkDevice =
684 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
685 String8(),
686 AUDIO_FORMAT_DEFAULT);
687
688 // RX and TX Telephony device are declared by Primary Audio HAL
689 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
690 (telephonyRxModule->getHalVersionMajor() >= 3)) {
691 if (rxSourceDevice == 0 || txSinkDevice == 0) {
692 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100693 ALOGE("%s() no telephony Tx and/or RX device", __func__);
694 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100695 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100696 // createAudioPatchInternal now supports both HW / SW bridging
697 createRxPatch = true;
698 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100699 } else {
700 // If the RX device is on the primary HW module, then use legacy routing method for
701 // voice calls via setOutputDevice() on primary output.
702 // Otherwise, create two audio patches for TX and RX path.
703 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
704 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700705 // If the TX device is also on the primary HW module, setOutputDevice() will take care
706 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100707 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
708 (txSinkDevice != 0);
709 }
710 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
711 // Otherwise, create two audio patches for TX and RX path.
712 if (!createRxPatch) {
713 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700714 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200715 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800716 // If the TX device is on the primary HW module but RX device is
717 // on other HW module, SinkMetaData of telephony input should handle it
718 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700719 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700720 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100721 // terminate active capture if on the same HW module as the call TX source device
722 // FIXME: would be better to refine to only inputs whose profile connects to the
723 // call TX device but this information is not in the audio patch and logic here must be
724 // symmetric to the one in startInput()
725 for (const auto& activeDesc : mInputs.getActiveInputs()) {
726 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
727 closeActiveClients(activeDesc);
728 }
729 }
François Gaffie9eb18552018-11-05 10:33:26 +0100730 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800731 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100732 if (waitMs != nullptr) {
733 *waitMs = muteWaitMs;
734 }
735 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800736}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700737
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800738sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100739 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700740 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741
François Gaffie11d30102018-11-02 16:09:09 +0100742 if (device == nullptr) {
743 return nullptr;
744 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100745
746 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800747 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100748 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800749 addSource(mAvailableInputDevices.getDevice(
750 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800751 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100752 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800753 addSink(mAvailableOutputDevices.getDevice(
754 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800755 }
756
François Gaffieafd4cea2019-11-18 15:50:22 +0100757 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
758 status_t status =
759 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
760 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
761 if (status != NO_ERROR || index < 0) {
762 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
763 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800764 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100765 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800766}
767
Mikhail Naganov100f0122018-11-29 11:22:16 -0800768bool AudioPolicyManager::isDeviceOfModule(
769 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
770 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
771 if (module != 0) {
772 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
773 .indexOf(devDesc) != NAME_NOT_FOUND
774 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
775 .indexOf(devDesc) != NAME_NOT_FOUND;
776 }
777 return false;
778}
779
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200780void AudioPolicyManager::connectTelephonyRxAudioSource()
781{
782 disconnectTelephonyRxAudioSource();
783 const struct audio_port_config source = {
784 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
785 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
786 };
787 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
788 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
789 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
790}
791
792void AudioPolicyManager::disconnectTelephonyRxAudioSource()
793{
794 stopAudioSource(mCallRxSourceClientPort);
795 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
796}
797
Eric Laurente0720872014-03-11 09:30:41 -0700798void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700799{
800 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100801 // store previous phone state for management of sonification strategy below
802 int oldState = mEngine->getPhoneState();
803
804 if (mEngine->setPhoneState(state) != NO_ERROR) {
805 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700806 return;
807 }
François Gaffie2110e042015-03-24 08:41:51 +0100808 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700809 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700810 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700811 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800812 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700813 }
814
François Gaffie2110e042015-03-24 08:41:51 +0100815 /**
816 * Switching to or from incall state or switching between telephony and VoIP lead to force
817 * routing command.
818 */
Eric Laurent74b71512019-11-06 17:21:57 -0800819 bool force = ((isStateInCall(oldState) != isStateInCall(state))
820 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700821
822 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700823 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700824
Eric Laurente552edb2014-03-10 17:42:56 -0700825 int delayMs = 0;
826 if (isStateInCall(state)) {
827 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100828 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
829 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700830 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700831 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700832 // mute media and sonification strategies and delay device switch by the largest
833 // latency of any output where either strategy is active.
834 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100835 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
836 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
837 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700838 (delayMs < (int)desc->latency()*2)) {
839 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700840 }
François Gaffiec005e562018-11-06 15:04:49 +0100841 setStrategyMute(musicStrategy, true, desc);
842 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
843 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
844 nullptr, true /*fromCache*/).types());
845 setStrategyMute(sonificationStrategy, true, desc);
846 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
847 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
848 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700849 }
850 }
851
Eric Laurent87ffa392015-05-22 10:32:38 -0700852 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700853 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100854 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700855 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100856 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
857 // force routing command to audio hardware when ending call
858 // even if no device change is needed
859 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
860 rxDevices = mPrimaryOutput->devices();
861 }
862 if (oldState == AUDIO_MODE_IN_CALL) {
863 disconnectTelephonyRxAudioSource();
864 if (mCallTxPatch != 0) {
865 releaseAudioPatchInternal(mCallTxPatch->getHandle());
866 mCallTxPatch.clear();
867 }
868 }
François Gaffie11d30102018-11-02 16:09:09 +0100869 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700870 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700871 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700872
873 // reevaluate routing on all outputs in case tracks have been started during the call
874 for (size_t i = 0; i < mOutputs.size(); i++) {
875 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100876 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700877 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100878 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700879 }
880 }
881
Eric Laurente552edb2014-03-10 17:42:56 -0700882 if (isStateInCall(state)) {
883 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700884 // force reevaluating accessibility routing when call starts
885 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700886 }
887
888 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100889 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
890 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700891}
892
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700893audio_mode_t AudioPolicyManager::getPhoneState() {
894 return mEngine->getPhoneState();
895}
896
Eric Laurente0720872014-03-11 09:30:41 -0700897void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100898 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700899{
François Gaffie2110e042015-03-24 08:41:51 +0100900 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700901 if (config == mEngine->getForceUse(usage)) {
902 return;
903 }
Eric Laurente552edb2014-03-10 17:42:56 -0700904
François Gaffie2110e042015-03-24 08:41:51 +0100905 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
906 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
907 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700908 }
François Gaffie2110e042015-03-24 08:41:51 +0100909 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
910 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
911 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700912
913 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700914 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800915
Eric Laurent22fcda22019-05-17 16:28:47 -0700916 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
917 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
918 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
919 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
920 }
921
Eric Laurentdc462862016-07-19 12:29:53 -0700922 //FIXME: workaround for truncated touch sounds
923 // to be removed when the problem is handled by system UI
924 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700925 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
926 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
927 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700928
929 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100930 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700931}
932
Eric Laurente0720872014-03-11 09:30:41 -0700933void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700934{
935 ALOGV("setSystemProperty() property %s, value %s", property, value);
936}
937
Michael Chana94fbb22018-04-24 14:31:19 +1000938// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
939// search to profiles for direct outputs.
940sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100941 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000942 uint32_t samplingRate,
943 audio_format_t format,
944 audio_channel_mask_t channelMask,
945 audio_output_flags_t flags,
946 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700947{
Michael Chana94fbb22018-04-24 14:31:19 +1000948 if (directOnly) {
949 // only retain flags that will drive the direct output profile selection
950 // if explicitly requested
951 static const uint32_t kRelevantFlags =
952 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700953 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000954 flags =
955 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
956 }
Eric Laurent861a6282015-05-18 15:40:16 -0700957
958 sp<IOProfile> profile;
959
Mikhail Naganovd4120142017-12-06 15:49:22 -0800960 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800961 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100962 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700963 samplingRate, NULL /*updatedSamplingRate*/,
964 format, NULL /*updatedFormat*/,
965 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700966 flags)) {
967 continue;
968 }
969 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100970 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700971 continue;
972 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800973 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700974 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800975 continue;
976 }
Michael Chana94fbb22018-04-24 14:31:19 +1000977 if (!directOnly) return curProfile;
978 // when searching for direct outputs, if several profiles are compatible, give priority
979 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100980 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700981 continue;
982 }
983 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100984 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700985 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700986 }
Eric Laurente552edb2014-03-10 17:42:56 -0700987 }
988 }
Eric Laurent861a6282015-05-18 15:40:16 -0700989 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700990}
991
Eric Laurentfa0f6742021-08-17 18:39:44 +0200992sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +0200993 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200994{
995 for (const auto& hwModule : mHwModules) {
996 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200997 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200998 continue;
999 }
1000 // reject profiles not corresponding to a device currently available
1001 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1002 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1003 continue;
1004 }
1005 if (!devices.empty()) {
1006 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1007 != devices.size()) {
1008 continue;
1009 }
1010 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001011 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1012 return curProfile;
1013 }
1014 }
1015 return nullptr;
1016}
1017
Eric Laurentf4e63452017-11-06 19:31:46 +00001018audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001019{
François Gaffiec005e562018-11-06 15:04:49 +01001020 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001021
1022 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1023 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1024 // format, flags, etc. This may result in some discrepancy for functions that utilize
1025 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1026 // and AudioSystem::getOutputSamplingRate().
1027
François Gaffie11d30102018-11-02 16:09:09 +01001028 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001029 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001030
François Gaffie11d30102018-11-02 16:09:09 +01001031 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1032 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001033 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001034}
1035
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001036status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1037 const audio_attributes_t *srcAttr,
1038 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001039{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001040 if (srcAttr != NULL) {
1041 if (!isValidAttributes(srcAttr)) {
1042 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1043 __func__,
1044 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1045 srcAttr->tags);
1046 return BAD_VALUE;
1047 }
1048 *dstAttr = *srcAttr;
1049 } else {
1050 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1051 ALOGE("%s: invalid stream type", __func__);
1052 return BAD_VALUE;
1053 }
François Gaffiec005e562018-11-06 15:04:49 +01001054 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001055 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001056
1057 // Only honor audibility enforced when required. The client will be
1058 // forced to reconnect if the forced usage changes.
1059 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001060 dstAttr->flags = static_cast<audio_flags_mask_t>(
1061 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001062 }
1063
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001064 return NO_ERROR;
1065}
1066
Kevin Rocard153f92d2018-12-18 18:33:28 -08001067status_t AudioPolicyManager::getOutputForAttrInt(
1068 audio_attributes_t *resultAttr,
1069 audio_io_handle_t *output,
1070 audio_session_t session,
1071 const audio_attributes_t *attr,
1072 audio_stream_type_t *stream,
1073 uid_t uid,
1074 const audio_config_t *config,
1075 audio_output_flags_t *flags,
1076 audio_port_handle_t *selectedDeviceId,
1077 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001078 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001079 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001080{
François Gaffiec005e562018-11-06 15:04:49 +01001081 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001082 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001083 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001084 const sp<DeviceDescriptor> requestedDevice =
1085 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1086
Eric Laurent8a1095a2019-11-08 14:44:16 -08001087 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001088 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1089 if (status != NO_ERROR) {
1090 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001091 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001092 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001093 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001094 }
François Gaffiec005e562018-11-06 15:04:49 +01001095 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001096
François Gaffiec005e562018-11-06 15:04:49 +01001097 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1098 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001099
Kevin Rocard153f92d2018-12-18 18:33:28 -08001100 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1101 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1102 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001103 sp<AudioPolicyMix> primaryMix;
1104 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001105 if (status != OK) {
1106 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001107 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001108
Kevin Rocard153f92d2018-12-18 18:33:28 -08001109 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001110 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001111
1112 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001113 if ((usePrimaryOutputFromPolicyMixes
1114 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001115 && !audio_is_linear_pcm(config->format)) {
1116 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001117 return BAD_VALUE;
1118 }
1119 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001120 sp<DeviceDescriptor> deviceDesc =
1121 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1122 primaryMix->mDeviceAddress,
1123 AUDIO_FORMAT_DEFAULT);
1124 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001125 if (deviceDesc != nullptr
1126 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001127 audio_io_handle_t newOutput;
1128 status = openDirectOutput(
1129 *stream, session, config,
1130 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1131 DeviceVector(deviceDesc), &newOutput);
1132 if (status != NO_ERROR) {
1133 policyDesc = nullptr;
1134 } else {
1135 policyDesc = mOutputs.valueFor(newOutput);
1136 primaryMix->setOutput(policyDesc);
1137 }
1138 }
1139 if (policyDesc != nullptr) {
1140 policyDesc->mPolicyMix = primaryMix;
1141 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001142 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001143
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001144 ALOGV("getOutputForAttr() returns output %d", *output);
1145 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1146 *outputType = API_OUT_MIX_PLAYBACK;
1147 } else {
1148 *outputType = API_OUTPUT_LEGACY;
1149 }
1150 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001151 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001152 }
François Gaffiec005e562018-11-06 15:04:49 +01001153 // Virtual sources must always be dynamicaly or explicitly routed
1154 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1155 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1156 return BAD_VALUE;
1157 }
1158 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1159 // in order to let the choice of the order to future vendor engine
1160 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001161
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001162 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001163 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001164 }
1165
Nadav Barb2f18162018-07-18 13:01:53 +03001166 // Set incall music only if device was explicitly set, and fallback to the device which is
1167 // chosen by the engine if not.
1168 // FIXME: provide a more generic approach which is not device specific and move this back
1169 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001170 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001171 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001172 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001173 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001174 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001175 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001176 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001177 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001178 }
1179 }
1180
François Gaffiec005e562018-11-06 15:04:49 +01001181 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1182 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1183 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001184
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001185 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001186 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001187 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001188 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001189 ALOGV("%s() Using MSD devices %s instead of devices %s",
1190 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001191 } else {
1192 *output = AUDIO_IO_HANDLE_NONE;
1193 }
1194 }
1195 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001196 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001197 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001198 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001199 if (*output == AUDIO_IO_HANDLE_NONE) {
1200 return INVALID_OPERATION;
1201 }
Paul McLeanaa981192015-03-21 09:55:15 -07001202
François Gaffiec005e562018-11-06 15:04:49 +01001203 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001204 for (auto &outputDevice : outputDevices) {
1205 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1206 *selectedDeviceId = outputDevice->getId();
1207 break;
1208 }
1209 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001210
Eric Laurent8a1095a2019-11-08 14:44:16 -08001211 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1212 *outputType = API_OUTPUT_TELEPHONY_TX;
1213 } else {
1214 *outputType = API_OUTPUT_LEGACY;
1215 }
1216
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001217 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1218
1219 return NO_ERROR;
1220}
1221
1222status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1223 audio_io_handle_t *output,
1224 audio_session_t session,
1225 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001226 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001227 const audio_config_t *config,
1228 audio_output_flags_t *flags,
1229 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001230 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001231 std::vector<audio_io_handle_t> *secondaryOutputs,
1232 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001233{
1234 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1235 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1236 return INVALID_OPERATION;
1237 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001238 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001239 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001240 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001241 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001242 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001243 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001244 const sp<DeviceDescriptor> requestedDevice =
1245 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1246
1247 // Prevent from storing invalid requested device id in clients
1248 const audio_port_handle_t sanitizedRequestedPortId =
1249 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1250 *selectedDeviceId = sanitizedRequestedPortId;
1251
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001252 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001253 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001254 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001255 if (status != NO_ERROR) {
1256 return status;
1257 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001258 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001259 if (secondaryOutputs != nullptr) {
1260 for (auto &secondaryMix : secondaryMixes) {
1261 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1262 if (outputDesc != nullptr &&
1263 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1264 secondaryOutputs->push_back(outputDesc->mIoHandle);
1265 weakSecondaryOutputDescs.push_back(outputDesc);
1266 }
1267 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001268 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001269
Eric Laurent8fc147b2018-07-22 19:13:55 -07001270 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001271 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001272 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001273 };
jiabin4ef93452019-09-10 14:29:54 -07001274 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001275
Eric Laurentc209fe42020-06-05 18:11:23 -07001276 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001277 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001278 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001279 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001280 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001281 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001282 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001283 std::move(weakSecondaryOutputDescs),
1284 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001285 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001286
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001287 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1288 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001289
Eric Laurente83b55d2014-11-14 10:06:21 -08001290 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001291}
1292
Eric Laurentc529cf62020-04-17 18:19:10 -07001293status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1294 audio_session_t session,
1295 const audio_config_t *config,
1296 audio_output_flags_t flags,
1297 const DeviceVector &devices,
1298 audio_io_handle_t *output) {
1299
1300 *output = AUDIO_IO_HANDLE_NONE;
1301
1302 // skip direct output selection if the request can obviously be attached to a mixed output
1303 // and not explicitly requested
1304 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1305 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1306 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1307 return NAME_NOT_FOUND;
1308 }
1309
1310 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1311 // This prevents creating an offloaded track and tearing it down immediately after start
1312 // when audioflinger detects there is an active non offloadable effect.
1313 // FIXME: We should check the audio session here but we do not have it in this context.
1314 // This may prevent offloading in rare situations where effects are left active by apps
1315 // in the background.
1316 sp<IOProfile> profile;
1317 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1318 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1319 profile = getProfileForOutput(
1320 devices, config->sample_rate, config->format, config->channel_mask,
1321 flags, true /* directOnly */);
1322 }
1323
1324 if (profile == nullptr) {
1325 return NAME_NOT_FOUND;
1326 }
1327
1328 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1329 for (size_t i = 0; i < mOutputs.size(); i++) {
1330 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1331 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1332 // reuse direct output if currently open by the same client
1333 // and configured with same parameters
1334 if ((config->sample_rate == desc->getSamplingRate()) &&
1335 (config->format == desc->getFormat()) &&
1336 (config->channel_mask == desc->getChannelMask()) &&
1337 (session == desc->mDirectClientSession)) {
1338 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001339 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001340 mOutputs.keyAt(i), session);
1341 *output = mOutputs.keyAt(i);
1342 return NO_ERROR;
1343 }
1344 }
1345 }
1346
1347 if (!profile->canOpenNewIo()) {
1348 return NAME_NOT_FOUND;
1349 }
1350
1351 sp<SwAudioOutputDescriptor> outputDesc =
1352 new SwAudioOutputDescriptor(profile, mpClientInterface);
1353
Michael Chan6fb34492020-12-08 15:44:49 +11001354 // An MSD patch may be using the only output stream that can service this request. Release
1355 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001356 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001357
Eric Laurentf1f22e72021-07-13 14:04:14 +02001358 status_t status =
1359 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001360
1361 // only accept an output with the requested parameters
1362 if (status != NO_ERROR ||
1363 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1364 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1365 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1366 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1367 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1368 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1369 config->channel_mask, outputDesc->getChannelMask());
1370 if (*output != AUDIO_IO_HANDLE_NONE) {
1371 outputDesc->close();
1372 }
1373 // fall back to mixer output if possible when the direct output could not be open
1374 if (audio_is_linear_pcm(config->format) &&
1375 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1376 return NAME_NOT_FOUND;
1377 }
1378 *output = AUDIO_IO_HANDLE_NONE;
1379 return BAD_VALUE;
1380 }
1381 outputDesc->mDirectOpenCount = 1;
1382 outputDesc->mDirectClientSession = session;
1383
1384 addOutput(*output, outputDesc);
1385 mPreviousOutputs = mOutputs;
1386 ALOGV("%s returns new direct output %d", __func__, *output);
1387 mpClientInterface->onAudioPortListUpdate();
1388 return NO_ERROR;
1389}
1390
François Gaffie11d30102018-11-02 16:09:09 +01001391audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1392 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001393 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001394 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001395 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001396 audio_output_flags_t *flags,
1397 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001398{
Andy Hungc88b0642018-04-27 15:42:35 -07001399 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001400
jiabine375d412019-02-26 12:54:53 -08001401 // Discard haptic channel mask when forcing muting haptic channels.
1402 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001403 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1404 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001405
Eric Laurente552edb2014-03-10 17:42:56 -07001406 // open a direct output if required by specified parameters
1407 //force direct flag if offload flag is set: offloading implies a direct output stream
1408 // and all common behaviors are driven by checking only the direct flag
1409 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001410 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1411 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001412 }
Nadav Bar766fb022018-01-07 12:18:03 +02001413 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1414 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001415 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001416
1417 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1418
Eric Laurente83b55d2014-11-14 10:06:21 -08001419 // only allow deep buffering for music stream type
1420 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001421 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001422 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001423 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001424 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1425 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001426 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001427 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001428 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001429 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001430 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001431 audio_is_linear_pcm(config->format) &&
1432 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001433 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001434 AUDIO_OUTPUT_FLAG_DIRECT);
1435 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001436 }
Eric Laurente552edb2014-03-10 17:42:56 -07001437
Carter Hsua3abb402021-10-26 11:11:20 +08001438 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1439 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1440 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1441 }
1442
Eric Laurentfa0f6742021-08-17 18:39:44 +02001443 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001444 && canBeSpatializedInt(attr, config,
1445 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02001446 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001447 }
1448
Eric Laurentc529cf62020-04-17 18:19:10 -07001449 audio_config_t directConfig = *config;
1450 directConfig.channel_mask = channelMask;
1451 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1452 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001453 return output;
1454 }
1455
Eric Laurent14cbfca2016-03-17 09:42:16 -07001456 // A request for HW A/V sync cannot fallback to a mixed output because time
1457 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001458 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001459 return AUDIO_IO_HANDLE_NONE;
1460 }
1461
Eric Laurente552edb2014-03-10 17:42:56 -07001462 // ignoring channel mask due to downmix capability in mixer
1463
1464 // open a non direct output
1465
1466 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001467 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001468 // get which output is suitable for the specified stream. The actual
1469 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001470 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001471
Eric Laurent8838a382014-09-08 16:44:28 -07001472 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001473 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001474 output = selectOutput(
1475 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001476 }
François Gaffie11d30102018-11-02 16:09:09 +01001477 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001478 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001479 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001480
Eric Laurente552edb2014-03-10 17:42:56 -07001481 return output;
1482}
1483
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001484sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001485 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1486 mAvailableInputDevices);
1487 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1488}
1489
1490DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1491 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1492 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001493}
1494
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001495const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001496 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001497 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1498 if (msdModule != 0) {
1499 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1500 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1501 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1502 const struct audio_port_config *source = &patch->mPatch.sources[j];
1503 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1504 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001505 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001506 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001507 }
1508 }
1509 }
1510 return msdPatches;
1511}
1512
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001513status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1514 const InputProfileCollection &inputProfiles,
1515 const OutputProfileCollection &outputProfiles,
1516 const sp<DeviceDescriptor> &sourceDevice,
1517 const sp<DeviceDescriptor> &sinkDevice,
1518 AudioProfileVector& sourceProfiles,
1519 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001520 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001521 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001522 return NO_INIT;
1523 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001524 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001525 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001526 return NO_INIT;
1527 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001528 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001529 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1530 inProfile->supportsDevice(sourceDevice)) {
1531 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001532 }
1533 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001534 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001535 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001536 outProfile->supportsDevice(sinkDevice)) {
1537 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001538 }
1539 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001540 return NO_ERROR;
1541}
1542
1543status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1544 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1545 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1546{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001547 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001548 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1549 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1550 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001551 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001552 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1553 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001554 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001555 }
1556 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1557 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1558 sinkConfig->format = bestSinkConfig.format;
1559 // For encoded streams force direct flag to prevent downstream mixing.
1560 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1561 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001562 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1563 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001564 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001565 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1566 // raw and IEC61937 framed streams.
1567 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1568 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1569 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001570 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1571 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1572 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1573 sourceConfig->format = bestSinkConfig.format;
1574 // Copy input stream directly without any processing (e.g. resampling).
1575 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1576 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1577 if (hwAvSync) {
1578 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1579 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1580 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1581 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1582 }
1583 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1584 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1585 sinkConfig->config_mask |= config_mask;
1586 sourceConfig->config_mask |= config_mask;
1587 return NO_ERROR;
1588}
1589
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001590PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1591 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001592{
1593 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001594 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1595 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1596 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1597 if (deviceModule == nullptr) {
1598 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1599 return patchBuilder;
1600 }
1601 const InputProfileCollection inputProfiles = msdIsSource ?
1602 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1603 const OutputProfileCollection outputProfiles = msdIsSource ?
1604 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1605
1606 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1607 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1608 device : getMsdAudioOutDevices().itemAt(0);
1609 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1610
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001611 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1612 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001613 AudioProfileVector sourceProfiles;
1614 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001615 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1616 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001617 for (auto hwAvSync : { true, false }) {
1618 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1619 sourceProfiles, sinkProfiles) != NO_ERROR) {
1620 continue;
1621 }
1622 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1623 &sinkConfig) == NO_ERROR) {
1624 // Found a matching config. Re-create PatchBuilder with this config.
1625 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1626 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001627 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001628 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001629 " supporting PCM format conversion.", __func__);
1630 return patchBuilder;
1631}
1632
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001633status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001634 DeviceVector devices;
1635 if (outputDevices != nullptr && outputDevices->size() > 0) {
1636 devices.add(*outputDevices);
1637 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001638 // Use media strategy for unspecified output device. This should only
1639 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1640 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001641 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001642 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001643 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001644 }
Michael Chan6fb34492020-12-08 15:44:49 +11001645 std::vector<PatchBuilder> patchesToCreate;
1646 for (auto i = 0u; i < devices.size(); ++i) {
1647 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001648 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001649 }
1650 // Retain only the MSD patches associated with outputDevices request.
1651 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001652 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001653 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1654 auto retainedPatch = false;
1655 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1656 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1657 patchesToRemove.removeItemsAt(i);
1658 retainedPatch = true;
1659 break;
1660 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001661 }
Michael Chan6fb34492020-12-08 15:44:49 +11001662 if (retainedPatch) {
1663 it = patchesToCreate.erase(it);
1664 continue;
1665 }
1666 ++it;
1667 }
1668 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1669 return NO_ERROR;
1670 }
1671 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1672 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001673 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001674 }
Michael Chan6fb34492020-12-08 15:44:49 +11001675 status_t status = NO_ERROR;
1676 for (const auto &p : patchesToCreate) {
1677 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1678 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1679 char message[256];
1680 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1681 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1682 currStatus == NO_ERROR ? "Success" : "Error",
1683 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1684 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1685 if (currStatus == NO_ERROR) {
1686 ALOGD("%s", message);
1687 } else {
1688 ALOGE("%s", message);
1689 if (status == NO_ERROR) {
1690 status = currStatus;
1691 }
1692 }
1693 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001694 return status;
1695}
1696
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001697void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1698 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001699 for (size_t i = 0; i < msdPatches.size(); i++) {
1700 const auto& patch = msdPatches[i];
1701 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1702 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1703 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1704 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1705 releaseAudioPatch(patch->getHandle(), mUidCached);
1706 break;
1707 }
1708 }
1709 }
1710}
1711
Dorin Drimus94d94412022-02-02 09:05:02 +01001712bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1713 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1714 AudioPatchCollection msdPatches = getMsdOutputPatches();
1715 for (size_t i = 0; i < msdPatches.size(); i++) {
1716 const auto& patch = msdPatches[i];
1717 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1718 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1719 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1720 const auto& foundDevice = devicesToCheck.getDevice(
1721 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1722 if (foundDevice != nullptr) {
1723 devicesToCheck.remove(foundDevice);
1724 if (devicesToCheck.isEmpty()) {
1725 return true;
1726 }
1727 }
1728 }
1729 }
1730 }
1731 return false;
1732}
1733
Eric Laurente0720872014-03-11 09:30:41 -07001734audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001735 audio_output_flags_t flags,
1736 audio_format_t format,
1737 audio_channel_mask_t channelMask,
1738 uint32_t samplingRate,
1739 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001740{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001741 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1742 "%s called with format %#x", __func__, format);
1743
jiabinebb6af42020-06-09 17:31:17 -07001744 // Return the output that haptic-generating attached to when 1) session id is specified,
1745 // 2) haptic-generating effect exists for given session id and 3) the output that
1746 // haptic-generating effect attached to is in given outputs.
1747 if (sessionId != AUDIO_SESSION_NONE) {
1748 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1749 sessionId, FX_IID_HAPTICGENERATOR);
1750 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1751 return hapticGeneratingOutput;
1752 }
1753 }
1754
Eric Laurent16c66dd2019-05-01 17:54:10 -07001755 // Flags disqualifying an output: the match must happen before calling selectOutput()
1756 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1757 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1758
1759 // Flags expressing a functional request: must be honored in priority over
1760 // other criteria
1761 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1762 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001763 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1764 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001765 // Flags expressing a performance request: have lower priority than serving
1766 // requested sampling rate or channel mask
1767 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1768 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1769 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1770
1771 const audio_output_flags_t functionalFlags =
1772 (audio_output_flags_t)(flags & kFunctionalFlags);
1773 const audio_output_flags_t performanceFlags =
1774 (audio_output_flags_t)(flags & kPerformanceFlags);
1775
1776 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1777
Eric Laurente552edb2014-03-10 17:42:56 -07001778 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001779 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001780 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001781 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001782 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001783 // with tiebreak preferring the minimum number of extra functional flags
1784 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001785 // 3: the output supporting the exact channel mask
1786 // 4: the output with a higher channel count than requested
1787 // 5: the output with a higher sampling rate than requested
1788 // 6: the output with the highest number of requested performance flags
1789 // 7: the output with the bit depth the closest to the requested one
1790 // 8: the primary output
1791 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001792
Eric Laurent16c66dd2019-05-01 17:54:10 -07001793 // matching criteria values in priority order for best matching output so far
1794 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001795
Eric Laurent16c66dd2019-05-01 17:54:10 -07001796 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1797 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1798 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001799
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001800 for (audio_io_handle_t output : outputs) {
1801 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001802 // matching criteria values in priority order for current output
1803 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001804
Eric Laurent16c66dd2019-05-01 17:54:10 -07001805 if (outputDesc->isDuplicated()) {
1806 continue;
1807 }
1808 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1809 continue;
1810 }
Eric Laurent8838a382014-09-08 16:44:28 -07001811
Eric Laurent16c66dd2019-05-01 17:54:10 -07001812 // If haptic channel is specified, use the haptic output if present.
1813 // When using haptic output, same audio format and sample rate are required.
1814 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001815 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001816 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1817 continue;
1818 }
1819 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001820 && format == outputDesc->getFormat()
1821 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001822 currentMatchCriteria[0] = outputHapticChannelCount;
1823 }
1824
1825 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001826 const int matchingFunctionalFlags =
1827 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1828 const int totalFunctionalFlags =
1829 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1830 // Prefer matching functional flags, but subtract unnecessary functional flags.
1831 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001832
1833 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001834 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1835 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001836 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1837 channelCount <= outputChannelCount) {
1838 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001839 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1840 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001841 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001842 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001843 currentMatchCriteria[3] = outputChannelCount;
1844 }
1845
1846 // sampling rate match
1847 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001848 samplingRate <= outputDesc->getSamplingRate()) {
1849 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001850 }
1851
1852 // performance flags match
1853 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1854
1855 // format match
1856 if (format != AUDIO_FORMAT_INVALID) {
1857 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001858 PolicyAudioPort::kFormatDistanceMax -
1859 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001860 }
1861
1862 // primary output match
1863 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1864
1865 // compare match criteria by priority then value
1866 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1867 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1868 bestMatchCriteria = currentMatchCriteria;
1869 bestOutput = output;
1870
1871 std::stringstream result;
1872 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1873 std::ostream_iterator<int>(result, " "));
1874 ALOGV("%s new bestOutput %d criteria %s",
1875 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001876 }
1877 }
1878
Eric Laurent16c66dd2019-05-01 17:54:10 -07001879 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001880}
1881
Eric Laurent8fc147b2018-07-22 19:13:55 -07001882status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001883{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001884 ALOGV("%s portId %d", __FUNCTION__, portId);
1885
1886 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1887 if (outputDesc == 0) {
1888 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001889 return BAD_VALUE;
1890 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001891 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001892
Eric Laurent8fc147b2018-07-22 19:13:55 -07001893 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001894 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001895
Eric Laurent733ce942017-12-07 12:18:25 -08001896 status_t status = outputDesc->start();
1897 if (status != NO_ERROR) {
1898 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001899 }
1900
Eric Laurent97ac8712018-07-27 18:59:02 -07001901 uint32_t delayMs;
1902 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001903
1904 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001905 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001906 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001907 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001908 if (delayMs != 0) {
1909 usleep(delayMs * 1000);
1910 }
1911
1912 return status;
1913}
1914
Eric Laurent97ac8712018-07-27 18:59:02 -07001915status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1916 const sp<TrackClientDescriptor>& client,
1917 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001918{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001919 // cannot start playback of STREAM_TTS if any other output is being used
1920 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001921
1922 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001923 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001924 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001925 auto clientStrategy = client->strategy();
1926 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001927 if (stream == AUDIO_STREAM_TTS) {
1928 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001929 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01001930 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001931 return INVALID_OPERATION;
1932 } else {
1933 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1934 }
1935 } else {
1936 // some playback other than beacon starts
1937 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1938 }
1939
Eric Laurent77305a62016-07-25 16:39:22 -07001940 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001941 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001942 bool force = !outputDesc->isActive() &&
1943 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001944
François Gaffie11d30102018-11-02 16:09:09 +01001945 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001946 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001947 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001948 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001949 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001950 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001951 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001952 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001953 } else {
1954 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001955 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001956 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1957 AUDIO_FORMAT_DEFAULT);
1958 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1959 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001960 }
1961
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001962 // requiresMuteCheck is false when we can bypass mute strategy.
1963 // It covers a common case when there is no materially active audio
1964 // and muting would result in unnecessary delay and dropped audio.
1965 const uint32_t outputLatencyMs = outputDesc->latency();
1966 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1967
Eric Laurente552edb2014-03-10 17:42:56 -07001968 // increment usage count for this stream on the requested output:
1969 // NOTE that the usage count is the same for duplicated output and hardware output which is
1970 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001971 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001972
1973 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001974 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1975 client->isPreferredDeviceForExclusiveUse()) {
1976 // Preferred device may be exclusive, use only if no other active clients on this output
1977 devices = DeviceVector(
1978 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1979 } else {
1980 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1981 }
François Gaffie11d30102018-11-02 16:09:09 +01001982 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001983 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001984 }
1985 }
Eric Laurente552edb2014-03-10 17:42:56 -07001986
François Gaffiec005e562018-11-06 15:04:49 +01001987 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001988 selectOutputForMusicEffects();
1989 }
1990
François Gaffie1c878552018-11-22 16:53:21 +01001991 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001992 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001993 if (devices.isEmpty()) {
1994 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001995 }
François Gaffiec005e562018-11-06 15:04:49 +01001996 bool shouldWait =
1997 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1998 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1999 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002000 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002001 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002002 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002003 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002004 // An output has a shared device if
2005 // - managed by the same hw module
2006 // - supports the currently selected device
2007 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002008 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002009
Eric Laurent77305a62016-07-25 16:39:22 -07002010 // force a device change if any other output is:
2011 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002012 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002013 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002014 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002015 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002016 // change the device currently selected by the other output.
2017 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002018 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002019 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002020 force = true;
2021 }
2022 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002023 // a notification so that audio focus effect can propagate, or that a mute/unmute
2024 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002025 const uint32_t latencyMs = desc->latency();
2026 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2027
2028 if (shouldWait && isActive && (waitMs < latencyMs)) {
2029 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002030 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002031
2032 // Require mute check if another output is on a shared device
2033 // and currently active to have proper drain and avoid pops.
2034 // Note restoring AudioTracks onto this output needs to invoke
2035 // a volume ramp if there is no mute.
2036 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002037 }
2038 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002039
2040 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002041 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002042
Eric Laurente552edb2014-03-10 17:42:56 -07002043 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002044 auto &curves = getVolumeCurves(client->attributes());
2045 checkAndSetVolume(curves, client->volumeSource(),
2046 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002047 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002048 outputDesc->devices().types(), 0 /*delay*/,
2049 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002050
2051 // update the outputs if starting an output with a stream that can affect notification
2052 // routing
2053 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002054
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002055 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002056 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002057 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2058 }
Eric Laurentdc462862016-07-19 12:29:53 -07002059
2060 if (waitMs > muteWaitMs) {
2061 *delayMs = waitMs - muteWaitMs;
2062 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002063
2064 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2065 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2066 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2067 // change occurs after the MixerThread starts and causes a stream volume
2068 // glitch.
2069 //
2070 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002071 }
Eric Laurentdc462862016-07-19 12:29:53 -07002072
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002073 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002074 mEngine->getForceUse(
2075 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002076 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002077 }
2078
Eric Laurent97ac8712018-07-27 18:59:02 -07002079 // Automatically enable the remote submix input when output is started on a re routing mix
2080 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002081 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2082 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002083 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2084 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2085 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002086 "remote-submix",
2087 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002088 }
2089
Eric Laurente552edb2014-03-10 17:42:56 -07002090 return NO_ERROR;
2091}
2092
Eric Laurent8fc147b2018-07-22 19:13:55 -07002093status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002094{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002095 ALOGV("%s portId %d", __FUNCTION__, portId);
2096
2097 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2098 if (outputDesc == 0) {
2099 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002100 return BAD_VALUE;
2101 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002102 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002103
Eric Laurent97ac8712018-07-27 18:59:02 -07002104 ALOGV("stopOutput() output %d, stream %d, session %d",
2105 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002106
Eric Laurent97ac8712018-07-27 18:59:02 -07002107 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002108
Eric Laurent733ce942017-12-07 12:18:25 -08002109 if (status == NO_ERROR ) {
2110 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002111 }
2112 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002113}
2114
Eric Laurent97ac8712018-07-27 18:59:02 -07002115status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2116 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002117{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002118 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002119 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002120 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002121
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002122 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2123
François Gaffie1c878552018-11-22 16:53:21 +01002124 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2125 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002126 // Automatically disable the remote submix input when output is stopped on a
2127 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002128 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002129 if (isSingleDeviceType(
2130 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002131 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002132 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002133 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2134 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002135 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002136 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002137 }
2138 }
2139 bool forceDeviceUpdate = false;
2140 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002141 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002142 forceDeviceUpdate = true;
2143 }
2144
Eric Laurente552edb2014-03-10 17:42:56 -07002145 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002146 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002147
Eric Laurente552edb2014-03-10 17:42:56 -07002148 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002149 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002150 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002151 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002152
2153 // If the routing does not change, if an output is routed on a device using HwGain
2154 // (aka setAudioPortConfig) and there are still active clients following different
2155 // volume group(s), force reapply volume
2156 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2157 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2158
Eric Laurente552edb2014-03-10 17:42:56 -07002159 // delay the device switch by twice the latency because stopOutput() is executed when
2160 // the track stop() command is received and at that time the audio track buffer can
2161 // still contain data that needs to be drained. The latency only covers the audio HAL
2162 // and kernel buffers. Also the latency does not always include additional delay in the
2163 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002164 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2165 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002166
2167 // force restoring the device selection on other active outputs if it differs from the
2168 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002169 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002170 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002171 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002172 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002173 desc->isActive() &&
2174 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002175 (newDevices != desc->devices())) {
2176 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2177 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002178
François Gaffie11d30102018-11-02 16:09:09 +01002179 setOutputDevices(desc, newDevices2, force, delayMs);
2180
Eric Laurent57de36c2016-09-28 16:59:11 -07002181 // re-apply device specific volume if not done by setOutputDevice()
2182 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002183 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002184 }
Eric Laurente552edb2014-03-10 17:42:56 -07002185 }
2186 }
2187 // update the outputs if stopping one with a stream that can affect notification routing
2188 handleNotificationRoutingForStream(stream);
2189 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002190
2191 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2192 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002193 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002194 }
2195
François Gaffiec005e562018-11-06 15:04:49 +01002196 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002197 selectOutputForMusicEffects();
2198 }
Eric Laurente552edb2014-03-10 17:42:56 -07002199 return NO_ERROR;
2200 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002201 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002202 return INVALID_OPERATION;
2203 }
2204}
2205
jiabinbce0c1d2020-10-05 11:20:18 -07002206bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002207{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002208 ALOGV("%s portId %d", __FUNCTION__, portId);
2209
2210 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2211 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002212 // If an output descriptor is closed due to a device routing change,
2213 // then there are race conditions with releaseOutput from tracks
2214 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2215 // destroyed shortly thereafter.
2216 //
2217 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002218 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002219 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002220 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002221
2222 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002223
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302224 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2225 if (outputDesc->isClientActive(client)) {
2226 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2227 stopOutput(portId);
2228 }
2229
Eric Laurent8fc147b2018-07-22 19:13:55 -07002230 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2231 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002232 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002233 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002234 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002235 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002236 if (--outputDesc->mDirectOpenCount == 0) {
2237 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002238 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002239 }
2240 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302241
Andy Hung39efb7a2018-09-26 15:39:28 -07002242 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002243 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2244 // The output is pending reopened to query dynamic profiles and
2245 // there is no active clients
2246 closeOutput(outputDesc->mIoHandle);
2247 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2248 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2249 if (newOutputDesc == nullptr) {
2250 ALOGE("%s failed to open output", __func__);
2251 }
2252 return true;
2253 }
2254 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002255}
2256
Eric Laurentcaf7f482014-11-25 17:50:47 -08002257status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2258 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002259 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002260 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002261 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002262 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002263 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002264 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002265 input_type_t *inputType,
2266 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002267{
François Gaffiec005e562018-11-06 15:04:49 +01002268 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002269 "flags %#x attributes=%s requested device ID %d",
2270 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2271 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002272
Eric Laurentad2e7b92017-09-14 20:06:42 -07002273 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002274 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002275 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002276 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002277 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002278 sp<AudioInputDescriptor> inputDesc;
2279 sp<RecordClientDescriptor> clientDesc;
2280 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002281 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002282 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002283
2284 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2285 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2286 return INVALID_OPERATION;
2287 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002288
Francois Gaffie716e1432019-01-14 16:58:59 +01002289 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2290 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002291 }
2292
Paul McLean466dc8e2015-04-17 13:15:36 -06002293 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002294 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002295 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002296
Eric Laurentad2e7b92017-09-14 20:06:42 -07002297 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2298 // possible
2299 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2300 *input != AUDIO_IO_HANDLE_NONE) {
2301 ssize_t index = mInputs.indexOfKey(*input);
2302 if (index < 0) {
2303 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2304 status = BAD_VALUE;
2305 goto error;
2306 }
2307 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002308 RecordClientVector clients = inputDesc->getClientsForSession(session);
2309 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002310 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2311 status = BAD_VALUE;
2312 goto error;
2313 }
2314 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2315 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002316 // corresponds to a new client and is only permitted from the same UID.
2317 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002318 if (clients.size() > 1) {
2319 for (const auto& client : clients) {
2320 // The client map is ordered by key values (portId) and portIds are allocated
2321 // incrementaly. So the first client in this list is the one opened by audio flinger
2322 // when the mmap stream is created and should be ignored as it does not correspond
2323 // to an actual client
2324 if (client == *clients.cbegin()) {
2325 continue;
2326 }
2327 if (uid != client->uid() && !client->isSilenced()) {
2328 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2329 uid, client->portId(), client->uid());
2330 status = INVALID_OPERATION;
2331 goto error;
2332 }
Eric Laurent331679c2018-04-16 17:03:16 -07002333 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002334 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002335 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002336 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002337
Eric Laurentfecbceb2021-02-09 14:46:43 +01002338 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002339 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002340 }
2341
2342 *input = AUDIO_IO_HANDLE_NONE;
2343 *inputType = API_INPUT_INVALID;
2344
Francois Gaffie716e1432019-01-14 16:58:59 +01002345 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002346
Francois Gaffie716e1432019-01-14 16:58:59 +01002347 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2348 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2349 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002350 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002351 ALOGW("%s could not find input mix for attr %s",
2352 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002353 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002354 }
jiabinc1de2df2019-05-07 14:26:40 -07002355 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2356 String8(attr->tags + strlen("addr=")),
2357 AUDIO_FORMAT_DEFAULT);
2358 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002359 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002360 __func__, attributes.source, attributes.tags);
2361 status = BAD_VALUE;
2362 goto error;
2363 }
2364
Kevin Rocard25f9b052019-02-27 15:08:54 -08002365 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2366 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2367 } else {
2368 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2369 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002370 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002371 if (explicitRoutingDevice != nullptr) {
2372 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002373 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002374 // Prevent from storing invalid requested device id in clients
2375 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002376 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002377 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2378 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002379 }
François Gaffie11d30102018-11-02 16:09:09 +01002380 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002381 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002382 status = BAD_VALUE;
2383 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002384 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002385 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2386 *inputType = API_INPUT_MIX_CAPTURE;
2387 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002388 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2389 // there is an external policy, but this input is attached to a mix of recorders,
2390 // meaning it receives audio injected into the framework, so the recorder doesn't
2391 // know about it and is therefore considered "legacy"
2392 *inputType = API_INPUT_LEGACY;
2393 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002394 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002395 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002396 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002397 } else {
2398 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002399 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002400
Eric Laurent599c7582015-12-07 18:05:55 -08002401 }
2402
François Gaffiec005e562018-11-06 15:04:49 +01002403 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002404 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002405 status = INVALID_OPERATION;
2406 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002407 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002408
Eric Laurent8f42ea12018-08-08 09:08:25 -07002409exit:
2410
François Gaffiec005e562018-11-06 15:04:49 +01002411 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2412 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002413
Francois Gaffie716e1432019-01-14 16:58:59 +01002414 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002415 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002416 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002417
Mikhail Naganov2996f672019-04-18 12:29:59 -07002418 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002419 requestedDeviceId, attributes.source, flags,
2420 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002421 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002422 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002423
2424 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2425 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002426
Eric Laurent599c7582015-12-07 18:05:55 -08002427 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002428
2429error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002430 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002431}
2432
2433
François Gaffie11d30102018-11-02 16:09:09 +01002434audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002435 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002436 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002437 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002438 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002439 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002440{
2441 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002442 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002443 bool isSoundTrigger = false;
2444
François Gaffiec005e562018-11-06 15:04:49 +01002445 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002446 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2447 if (index >= 0) {
2448 input = mSoundTriggerSessions.valueFor(session);
2449 isSoundTrigger = true;
2450 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2451 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2452 } else {
2453 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002454 }
François Gaffiec005e562018-11-06 15:04:49 +01002455 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002456 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002457 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002458 }
2459
Carter Hsua3abb402021-10-26 11:11:20 +08002460 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2461 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2462 }
2463
Andy Hungf129b032015-04-07 13:45:50 -07002464 // find a compatible input profile (not necessarily identical in parameters)
2465 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002466 // sampling rate and flags may be updated by getInputProfile
2467 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2468 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002469 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002470 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002471 audio_input_flags_t profileFlags = flags;
2472 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002473 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002474 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002475 profileFlags);
2476 if (profile != 0) {
2477 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002478 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2479 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002480 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002481 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2482 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002483 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002484 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002485 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002486 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002487 }
Eric Laurente552edb2014-03-10 17:42:56 -07002488 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002489 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002490 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002491 if (samplingRate == 0) {
2492 samplingRate = profileSamplingRate;
2493 }
Eric Laurente552edb2014-03-10 17:42:56 -07002494
Eric Laurent322b4d22015-04-03 15:57:54 -07002495 if (profile->getModuleHandle() == 0) {
2496 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002497 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002498 }
2499
Eric Laurentec376dc2021-04-08 20:41:22 +02002500 // Reuse an already opened input if a client with the same session ID already exists
2501 // on that input
2502 for (size_t i = 0; i < mInputs.size(); i++) {
2503 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2504 if (desc->mProfile != profile) {
2505 continue;
2506 }
2507 RecordClientVector clients = desc->clientsList();
2508 for (const auto &client : clients) {
2509 if (session == client->session()) {
2510 return desc->mIoHandle;
2511 }
2512 }
2513 }
2514
Eric Laurent3974e3b2017-12-07 17:58:43 -08002515 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002516 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002517 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002518 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002519 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002520 continue;
2521 }
2522 // if sound trigger, reuse input if used by other sound trigger on same session
2523 // else
2524 // reuse input if active client app is not in IDLE state
2525 //
2526 RecordClientVector clients = desc->clientsList();
2527 bool doClose = false;
2528 for (const auto& client : clients) {
2529 if (isSoundTrigger != client->isSoundTrigger()) {
2530 continue;
2531 }
2532 if (client->isSoundTrigger()) {
2533 if (session == client->session()) {
2534 return desc->mIoHandle;
2535 }
2536 continue;
2537 }
2538 if (client->active() && client->appState() != APP_STATE_IDLE) {
2539 return desc->mIoHandle;
2540 }
2541 doClose = true;
2542 }
2543 if (doClose) {
2544 closeInput(desc->mIoHandle);
2545 } else {
2546 i++;
2547 }
2548 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002549 }
2550
Eric Laurentfe231122017-11-17 17:48:06 -08002551 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002552
Eric Laurentfe231122017-11-17 17:48:06 -08002553 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2554 lConfig.sample_rate = profileSamplingRate;
2555 lConfig.channel_mask = profileChannelMask;
2556 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002557
François Gaffie11d30102018-11-02 16:09:09 +01002558 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002559
2560 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002561 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002562 (profileSamplingRate != lConfig.sample_rate) ||
2563 !audio_formats_match(profileFormat, lConfig.format) ||
2564 (profileChannelMask != lConfig.channel_mask)) {
2565 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002566 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002567 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002568 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002569 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002570 }
Eric Laurent599c7582015-12-07 18:05:55 -08002571 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002572 }
2573
Eric Laurentc722f302014-12-10 11:21:49 -08002574 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002575
Eric Laurent599c7582015-12-07 18:05:55 -08002576 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002577 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002578
Eric Laurent599c7582015-12-07 18:05:55 -08002579 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002580}
2581
Eric Laurent4eb58f12018-12-07 16:41:02 -08002582status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002583{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002584 ALOGV("%s portId %d", __FUNCTION__, portId);
2585
2586 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2587 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002588 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002589 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002590 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002591 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002592 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002593 if (client->active()) {
2594 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2595 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002596 }
2597
Eric Laurent8f42ea12018-08-08 09:08:25 -07002598 audio_session_t session = client->session();
2599
Eric Laurent4eb58f12018-12-07 16:41:02 -08002600 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002601
Eric Laurent4eb58f12018-12-07 16:41:02 -08002602 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002603
Eric Laurent4eb58f12018-12-07 16:41:02 -08002604 status_t status = inputDesc->start();
2605 if (status != NO_ERROR) {
2606 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002607 }
Eric Laurente552edb2014-03-10 17:42:56 -07002608
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002609 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002610 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002611 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002612
Eric Laurent8f42ea12018-08-08 09:08:25 -07002613 // indicate active capture to sound trigger service if starting capture from a mic on
2614 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002615 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002616 if (device != nullptr) {
2617 status = setInputDevice(input, device, true /* force */);
2618 } else {
2619 ALOGW("%s no new input device can be found for descriptor %d",
2620 __FUNCTION__, inputDesc->getId());
2621 status = BAD_VALUE;
2622 }
Eric Laurente552edb2014-03-10 17:42:56 -07002623
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002624 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002625 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002626 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002627 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002628 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2629 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002630 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002631 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002632
François Gaffie11d30102018-11-02 16:09:09 +01002633 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2634 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002635 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002636 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002637 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002638
Eric Laurent8f42ea12018-08-08 09:08:25 -07002639 // automatically enable the remote submix output when input is started if not
2640 // used by a policy mix of type MIX_TYPE_RECORDERS
2641 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002642 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002643 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002644 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002645 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002646 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2647 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002648 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002649 if (address != "") {
2650 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2651 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002652 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002653 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002654 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002655 } else if (status != NO_ERROR) {
2656 // Restore client activity state.
2657 inputDesc->setClientActive(client, false);
2658 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002659 }
2660
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002661 ALOGV("%s input %d source = %d status = %d exit",
2662 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002663
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002664 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002665}
2666
Eric Laurent8fc147b2018-07-22 19:13:55 -07002667status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002668{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002669 ALOGV("%s portId %d", __FUNCTION__, portId);
2670
2671 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2672 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002673 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002674 return BAD_VALUE;
2675 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002676 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002677 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002678 if (!client->active()) {
2679 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002680 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002681 }
Carter Hsue6139d52021-07-08 10:30:20 +08002682 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002683 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002684
Eric Laurent8f42ea12018-08-08 09:08:25 -07002685 inputDesc->stop();
2686 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002687 auto current_source = inputDesc->source();
2688 setInputDevice(input, getNewInputDevice(inputDesc),
2689 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002690 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002691 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002692 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002693 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002694 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2695 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002696 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002697 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002698
2699 // automatically disable the remote submix output when input is stopped if not
2700 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002701 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002702 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002703 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002704 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002705 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2706 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002707 }
2708 if (address != "") {
2709 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2710 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002711 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002712 }
2713 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002714 resetInputDevice(input);
2715
2716 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2717 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002718 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2719 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002720 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002721 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002722 }
2723 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002724 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002725 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002726}
2727
Eric Laurent8fc147b2018-07-22 19:13:55 -07002728void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002729{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002730 ALOGV("%s portId %d", __FUNCTION__, portId);
2731
2732 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2733 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002734 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002735 return;
2736 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002737 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002738 audio_io_handle_t input = inputDesc->mIoHandle;
2739
Eric Laurent8f42ea12018-08-08 09:08:25 -07002740 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002741
Andy Hung39efb7a2018-09-26 15:39:28 -07002742 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002743
Andy Hung39efb7a2018-09-26 15:39:28 -07002744 if (inputDesc->getClientCount() > 0) {
2745 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002746 return;
2747 }
2748
Eric Laurent05b90f82014-08-27 15:32:29 -07002749 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002750 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002751 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002752}
2753
Eric Laurent8f42ea12018-08-08 09:08:25 -07002754void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002755{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002756 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002757
2758 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002759 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002760 }
2761}
2762
Eric Laurent8f42ea12018-08-08 09:08:25 -07002763void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2764{
2765 stopInput(portId);
2766 releaseInput(portId);
2767}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002768
Eric Laurent0dd51852019-04-19 18:18:58 -07002769void AudioPolicyManager::checkCloseInputs() {
2770 // After connecting or disconnecting an input device, close input if:
2771 // - it has no client (was just opened to check profile) OR
2772 // - none of its supported devices are connected anymore OR
2773 // - one of its clients cannot be routed to one of its supported
2774 // devices anymore. Otherwise update device selection
2775 std::vector<audio_io_handle_t> inputsToClose;
2776 for (size_t i = 0; i < mInputs.size(); i++) {
2777 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2778 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002779 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002780 inputsToClose.push_back(mInputs.keyAt(i));
2781 } else {
2782 bool close = false;
2783 for (const auto& client : input->clientsList()) {
2784 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002785 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002786 if (!input->supportedDevices().contains(device)) {
2787 close = true;
2788 break;
2789 }
2790 }
2791 if (close) {
2792 inputsToClose.push_back(mInputs.keyAt(i));
2793 } else {
2794 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2795 }
2796 }
2797 }
2798
2799 for (const audio_io_handle_t handle : inputsToClose) {
2800 ALOGV("%s closing input %d", __func__, handle);
2801 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002802 }
Eric Laurentd4692962014-05-05 18:13:44 -07002803}
2804
François Gaffie251c7f02018-11-07 10:41:08 +01002805void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002806{
2807 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002808 if (indexMin < 0 || indexMax < 0) {
2809 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2810 return;
2811 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002812 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002813
2814 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002815 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2816 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002817 continue;
2818 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002819 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002820 }
Eric Laurente552edb2014-03-10 17:42:56 -07002821}
2822
Eric Laurente0720872014-03-11 09:30:41 -07002823status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002824 int index,
2825 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002826{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002827 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002828 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2829 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2830 return NO_ERROR;
2831 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002832 ALOGV("%s: stream %s attributes=%s", __func__,
2833 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002834 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002835}
2836
Eric Laurente0720872014-03-11 09:30:41 -07002837status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002838 int *index,
2839 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002840{
François Gaffiec005e562018-11-06 15:04:49 +01002841 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2842 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002843 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002844 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002845 deviceTypes = mEngine->getOutputDevicesForStream(
2846 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002847 }
jiabin9a3361e2019-10-01 09:38:30 -07002848 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002849}
2850
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002851status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002852 int index,
2853 audio_devices_t device)
2854{
2855 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002856 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2857 if (group == VOLUME_GROUP_NONE) {
2858 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002859 return BAD_VALUE;
2860 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002861 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002862 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002863 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002864 VolumeSource vs = toVolumeSource(group);
2865 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2866
2867 status = setVolumeCurveIndex(index, device, curves);
2868 if (status != NO_ERROR) {
2869 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2870 return status;
2871 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002872
jiabin9a3361e2019-10-01 09:38:30 -07002873 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002874 auto curCurvAttrs = curves.getAttributes();
2875 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2876 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002877 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002878 } else if (!curves.getStreamTypes().empty()) {
2879 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002880 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002881 } else {
2882 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2883 return BAD_VALUE;
2884 }
jiabin9a3361e2019-10-01 09:38:30 -07002885 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2886 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002887
François Gaffiecfe17322018-11-07 13:41:29 +01002888 // update volume on all outputs and streams matching the following:
2889 // - The requested stream (or a stream matching for volume control) is active on the output
2890 // - The device (or devices) selected by the engine for this stream includes
2891 // the requested device
2892 // - For non default requested device, currently selected device on the output is either the
2893 // requested device or one of the devices selected by the engine for this stream
2894 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2895 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002896 for (size_t i = 0; i < mOutputs.size(); i++) {
2897 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002898 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002899
jiabin9a3361e2019-10-01 09:38:30 -07002900 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2901 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002902 }
François Gaffieed91f582020-01-31 10:35:37 +01002903 if (!(desc->isActive(vs) || isInCall())) {
2904 continue;
2905 }
2906 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2907 curDevices.find(device) == curDevices.end()) {
2908 continue;
2909 }
2910 bool applyVolume = false;
2911 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2912 curSrcDevices.insert(device);
2913 applyVolume = (curSrcDevices.find(
2914 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2915 } else {
2916 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2917 }
2918 if (!applyVolume) {
2919 continue; // next output
2920 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002921 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2922 // If a higher priority strategy is active, and the output is routed to a device with a
2923 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002924 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002925 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02002926 // If the volume source is active with higher priority source, ensure at least Sw Muted
2927 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002928 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2929 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2930 false /*preferredDevice*/);
2931 if (activeClients.empty()) {
2932 continue;
2933 }
2934 bool isPreempted = false;
2935 bool isHigherPriority = productStrategy < strategy;
2936 for (const auto &client : activeClients) {
2937 if (isHigherPriority && (client->volumeSource() != vs)) {
2938 ALOGV("%s: Strategy=%d (\nrequester:\n"
2939 " group %d, volumeGroup=%d attributes=%s)\n"
2940 " higher priority source active:\n"
2941 " volumeGroup=%d attributes=%s) \n"
2942 " on output %zu, bailing out", __func__, productStrategy,
2943 group, group, toString(attributes).c_str(),
2944 client->volumeSource(), toString(client->attributes()).c_str(), i);
2945 applyVolume = false;
2946 isPreempted = true;
2947 break;
2948 }
2949 // However, continue for loop to ensure no higher prio clients running on output
2950 if (client->volumeSource() == vs) {
2951 applyVolume = true;
2952 }
2953 }
2954 if (isPreempted || applyVolume) {
2955 break;
2956 }
2957 }
2958 if (!applyVolume) {
2959 continue; // next output
2960 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002961 }
François Gaffieed91f582020-01-31 10:35:37 +01002962 //FIXME: workaround for truncated touch sounds
2963 // delayed volume change for system stream to be removed when the problem is
2964 // handled by system UI
2965 status_t volStatus = checkAndSetVolume(
2966 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002967 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01002968 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2969 if (volStatus != NO_ERROR) {
2970 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002971 }
2972 }
François Gaffiecfe17322018-11-07 13:41:29 +01002973 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2974 return status;
2975}
2976
François Gaffieaaac0fd2018-11-22 17:56:39 +01002977status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002978 audio_devices_t device,
2979 IVolumeCurves &volumeCurves)
2980{
2981 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2982 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002983 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2984 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002985 (index > volumeCurves.getVolumeIndexMax())) {
2986 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2987 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2988 return BAD_VALUE;
2989 }
2990 if (!audio_is_output_device(device)) {
2991 return BAD_VALUE;
2992 }
2993
2994 // Force max volume if stream cannot be muted
2995 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2996
François Gaffieaaac0fd2018-11-22 17:56:39 +01002997 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002998 volumeCurves.addCurrentVolumeIndex(device, index);
2999 return NO_ERROR;
3000}
3001
3002status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3003 int &index,
3004 audio_devices_t device)
3005{
3006 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3007 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003008 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003009 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003010 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3011 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003012 }
jiabin9a3361e2019-10-01 09:38:30 -07003013 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003014}
3015
3016status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3017 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003018 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003019{
jiabin9a3361e2019-10-01 09:38:30 -07003020 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003021 return BAD_VALUE;
3022 }
jiabin9a3361e2019-10-01 09:38:30 -07003023 index = curves.getVolumeIndex(deviceTypes);
3024 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003025 return NO_ERROR;
3026}
3027
3028status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3029 int &index)
3030{
3031 index = getVolumeCurves(attr).getVolumeIndexMin();
3032 return NO_ERROR;
3033}
3034
3035status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3036 int &index)
3037{
3038 index = getVolumeCurves(attr).getVolumeIndexMax();
3039 return NO_ERROR;
3040}
3041
Eric Laurent36829f92017-04-07 19:04:42 -07003042audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003043{
3044 // select one output among several suitable for global effects.
3045 // The priority is as follows:
3046 // 1: An offloaded output. If the effect ends up not being offloadable,
3047 // AudioFlinger will invalidate the track and the offloaded output
3048 // will be closed causing the effect to be moved to a PCM output.
3049 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003050 // 3: The primary output
3051 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003052
François Gaffiec005e562018-11-06 15:04:49 +01003053 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3054 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003055 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003056
Eric Laurent36829f92017-04-07 19:04:42 -07003057 if (outputs.size() == 0) {
3058 return AUDIO_IO_HANDLE_NONE;
3059 }
Eric Laurente552edb2014-03-10 17:42:56 -07003060
Eric Laurent36829f92017-04-07 19:04:42 -07003061 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3062 bool activeOnly = true;
3063
3064 while (output == AUDIO_IO_HANDLE_NONE) {
3065 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3066 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3067 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3068
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003069 for (audio_io_handle_t output : outputs) {
3070 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003071 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003072 continue;
3073 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003074 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3075 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003076 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003077 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003078 }
3079 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003080 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003081 }
3082 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003083 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003084 }
3085 }
3086 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3087 output = outputOffloaded;
3088 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3089 output = outputDeepBuffer;
3090 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3091 output = outputPrimary;
3092 } else {
3093 output = outputs[0];
3094 }
3095 activeOnly = false;
3096 }
3097
3098 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003099 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003100 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3101 mMusicEffectOutput = output;
3102 }
3103
3104 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003105 return output;
3106}
3107
Eric Laurent36829f92017-04-07 19:04:42 -07003108audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3109{
3110 return selectOutputForMusicEffects();
3111}
3112
Eric Laurente0720872014-03-11 09:30:41 -07003113status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003114 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003115 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003116 int session,
3117 int id)
3118{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003119 if (session != AUDIO_SESSION_DEVICE) {
3120 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003121 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003122 index = mInputs.indexOfKey(io);
3123 if (index < 0) {
3124 ALOGW("registerEffect() unknown io %d", io);
3125 return INVALID_OPERATION;
3126 }
Eric Laurente552edb2014-03-10 17:42:56 -07003127 }
3128 }
François Gaffiec005e562018-11-06 15:04:49 +01003129 return mEffects.registerEffect(desc, io, session, id,
3130 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3131 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003132}
3133
Eric Laurentc241b0d2018-11-28 09:08:49 -08003134status_t AudioPolicyManager::unregisterEffect(int id)
3135{
3136 if (mEffects.getEffect(id) == nullptr) {
3137 return INVALID_OPERATION;
3138 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003139 if (mEffects.isEffectEnabled(id)) {
3140 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3141 setEffectEnabled(id, false);
3142 }
3143 return mEffects.unregisterEffect(id);
3144}
3145
3146status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3147{
3148 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3149 if (effect == nullptr) {
3150 return INVALID_OPERATION;
3151 }
3152
3153 status_t status = mEffects.setEffectEnabled(id, enabled);
3154 if (status == NO_ERROR) {
3155 mInputs.trackEffectEnabled(effect, enabled);
3156 }
3157 return status;
3158}
3159
Eric Laurent6c796322019-04-09 14:13:17 -07003160
3161status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3162{
3163 mEffects.moveEffects(ids, io);
3164 return NO_ERROR;
3165}
3166
Eric Laurentc75307b2015-03-17 15:29:32 -07003167bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3168{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003169 auto vs = toVolumeSource(stream, false);
3170 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003171}
3172
3173bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3174{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003175 auto vs = toVolumeSource(stream, false);
3176 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003177}
3178
Eric Laurente0720872014-03-11 09:30:41 -07003179bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003180{
3181 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003182 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003183 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003184 return true;
3185 }
3186 }
3187 return false;
3188}
3189
Eric Laurent275e8e92014-11-30 15:14:47 -08003190// Register a list of custom mixes with their attributes and format.
3191// When a mix is registered, corresponding input and output profiles are
3192// added to the remote submix hw module. The profile contains only the
3193// parameters (sampling rate, format...) specified by the mix.
3194// The corresponding input remote submix device is also connected.
3195//
3196// When a remote submix device is connected, the address is checked to select the
3197// appropriate profile and the corresponding input or output stream is opened.
3198//
3199// When capture starts, getInputForAttr() will:
3200// - 1 look for a mix matching the address passed in attribtutes tags if any
3201// - 2 if none found, getDeviceForInputSource() will:
3202// - 2.1 look for a mix matching the attributes source
3203// - 2.2 if none found, default to device selection by policy rules
3204// At this time, the corresponding output remote submix device is also connected
3205// and active playback use cases can be transferred to this mix if needed when reconnecting
3206// after AudioTracks are invalidated
3207//
3208// When playback starts, getOutputForAttr() will:
3209// - 1 look for a mix matching the address passed in attribtutes tags if any
3210// - 2 if none found, look for a mix matching the attributes usage
3211// - 3 if none found, default to device and output selection by policy rules.
3212
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003213status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003214{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003215 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3216 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003217 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003218 sp<HwModule> rSubmixModule;
3219 // examine each mix's route type
3220 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003221 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003222 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3223 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3224 ALOGE("Unsupported Policy Mix %zu of %zu: "
3225 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3226 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003227 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003228 break;
3229 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003230 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3231 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003232 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003233 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3234 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003235 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003236 rSubmixModule = mHwModules.getModuleFromName(
3237 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3238 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003239 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003240 i);
3241 res = INVALID_OPERATION;
3242 break;
3243 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003244 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003245
Eric Laurent97ac8712018-07-27 18:59:02 -07003246 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003247 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003248 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003249 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003250 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3251 } else {
3252 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3253 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003254 }
François Gaffie036e1e92015-03-19 10:16:24 +01003255
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003256 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003257 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003258 res = INVALID_OPERATION;
3259 break;
3260 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003261 audio_config_t outputConfig = mix.mFormat;
3262 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003263 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3264 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003265 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3266 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003267 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003268 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003269 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003270 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003271
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003272 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003273 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3274 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3275 ALOGE("Failed to set remote submix device available, type %u, address %s",
3276 mix.mDeviceType, address.string());
3277 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003278 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003279 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3280 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003281 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003282 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003283 i, mixes.size(), type, address.string());
3284
3285 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3286 mix.mDeviceType, mix.mDeviceAddress,
3287 String8(), AUDIO_FORMAT_DEFAULT);
3288 if (device == nullptr) {
3289 res = INVALID_OPERATION;
3290 break;
3291 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003292
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003293 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003294 // First try to find an already opened output supporting the device
3295 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003296 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003297
Eric Laurentc529cf62020-04-17 18:19:10 -07003298 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003299 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003300 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3301 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003302 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003303 } else {
3304 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003305 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003306 }
3307 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003308 // If no output found, try to find a direct output profile supporting the device
3309 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3310 sp<HwModule> module = mHwModules[i];
3311 for (size_t j = 0;
3312 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3313 j++) {
3314 sp<IOProfile> profile = module->getOutputProfiles()[j];
3315 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3316 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3317 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3318 address.string());
3319 res = INVALID_OPERATION;
3320 } else {
3321 foundOutput = true;
3322 }
3323 }
3324 }
3325 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003326 if (res != NO_ERROR) {
3327 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003328 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003329 res = INVALID_OPERATION;
3330 break;
3331 } else if (!foundOutput) {
3332 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003333 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003334 res = INVALID_OPERATION;
3335 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003336 } else {
3337 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003338 }
Eric Laurentc722f302014-12-10 11:21:49 -08003339 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003340 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003341 if (res != NO_ERROR) {
3342 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003343 } else if (checkOutputs) {
3344 checkForDeviceAndOutputChanges();
3345 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003346 }
3347 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003348}
3349
3350status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3351{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003352 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003353 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003354 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003355 sp<HwModule> rSubmixModule;
3356 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003357 for (const auto& mix : mixes) {
3358 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003359
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003360 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003361 rSubmixModule = mHwModules.getModuleFromName(
3362 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3363 if (rSubmixModule == 0) {
3364 res = INVALID_OPERATION;
3365 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003366 }
3367 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003368
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003369 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003370
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003371 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003372 res = INVALID_OPERATION;
3373 continue;
3374 }
3375
Kevin Rocard04ed0462019-05-02 17:53:24 -07003376 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3377 if (getDeviceConnectionState(device, address.string()) ==
3378 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3379 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3380 address.string(), "remote-submix",
3381 AUDIO_FORMAT_DEFAULT);
3382 if (res != OK) {
3383 ALOGE("Error making RemoteSubmix device unavailable for mix "
3384 "with type %d, address %s", device, address.string());
3385 }
3386 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003387 }
jiabin5740f082019-08-19 15:08:30 -07003388 rSubmixModule->removeOutputProfile(address.c_str());
3389 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003390
Kevin Rocard153f92d2018-12-18 18:33:28 -08003391 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003392 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003393 res = INVALID_OPERATION;
3394 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003395 } else {
3396 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003397 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003398 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003399 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003400 if (res == NO_ERROR && checkOutputs) {
3401 checkForDeviceAndOutputChanges();
3402 updateCallAndOutputRouting();
3403 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003404 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003405}
3406
Mikhail Naganov100f0122018-11-29 11:22:16 -08003407void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3408{
3409 size_t i = 0;
3410 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3411 for (const auto& fmt : mManualSurroundFormats) {
3412 if (i++ != 0) dst->append(", ");
3413 std::string sfmt;
3414 FormatConverter::toString(fmt, sfmt);
3415 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3416 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3417 }
3418}
3419
Eric Laurentc529cf62020-04-17 18:19:10 -07003420// Returns true if all devices types match the predicate and are supported by one HW module
3421bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003422 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003423 std::function<bool(audio_devices_t)> predicate,
3424 const char *context) {
3425 for (size_t i = 0; i < devices.size(); i++) {
3426 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003427 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003428 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003429 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003430 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003431 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003432 return false;
3433 }
3434 }
3435 return true;
3436}
3437
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003438status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003439 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003440 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003441 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3442 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003443 }
3444 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003445 if (res != NO_ERROR) {
3446 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3447 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003448 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003449
3450 checkForDeviceAndOutputChanges();
3451 updateCallAndOutputRouting();
3452
3453 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003454}
3455
3456status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3457 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003458 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3459 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003460 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003461 __FUNCTION__, uid);
3462 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003463 }
3464
Eric Laurentc529cf62020-04-17 18:19:10 -07003465 checkForDeviceAndOutputChanges();
3466 updateCallAndOutputRouting();
3467
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003468 return res;
3469}
3470
Eric Laurent2517af32020-11-25 15:31:27 +01003471
jiabin0a488932020-08-07 17:32:40 -07003472status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3473 device_role_t role,
3474 const AudioDeviceTypeAddrVector &devices) {
3475 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3476 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003477
Eric Laurentc529cf62020-04-17 18:19:10 -07003478 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003479 return BAD_VALUE;
3480 }
jiabin0a488932020-08-07 17:32:40 -07003481 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003482 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003483 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3484 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003485 return status;
3486 }
3487
3488 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003489
3490 bool forceVolumeReeval = false;
3491 // FIXME: workaround for truncated touch sounds
3492 // to be removed when the problem is handled by system UI
3493 uint32_t delayMs = 0;
3494 if (strategy == mCommunnicationStrategy) {
3495 forceVolumeReeval = true;
3496 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3497 updateInputRouting();
3498 }
3499 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003500
3501 return NO_ERROR;
3502}
3503
3504void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3505{
3506 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003507 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003508 // Only apply special touch sound delay once
3509 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003510 }
3511 for (size_t i = 0; i < mOutputs.size(); i++) {
3512 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3513 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3514 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3515 // As done in setDeviceConnectionState, we could also fix default device issue by
3516 // preventing the force re-routing in case of default dev that distinguishes on address.
3517 // Let's give back to engine full device choice decision however.
3518 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003519 // Only apply special touch sound delay once
3520 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003521 }
3522 if (forceVolumeReeval && !newDevices.isEmpty()) {
3523 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3524 }
3525 }
3526}
3527
Eric Laurent2517af32020-11-25 15:31:27 +01003528void AudioPolicyManager::updateInputRouting() {
3529 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303530 // Skip for hotword recording as the input device switch
3531 // is handled within sound trigger HAL
3532 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3533 continue;
3534 }
Eric Laurent2517af32020-11-25 15:31:27 +01003535 auto newDevice = getNewInputDevice(activeDesc);
3536 // Force new input selection if the new device can not be reached via current input
3537 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3538 setInputDevice(activeDesc->mIoHandle, newDevice);
3539 } else {
3540 closeInput(activeDesc->mIoHandle);
3541 }
3542 }
3543}
3544
jiabin0a488932020-08-07 17:32:40 -07003545status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3546 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003547{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003548 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003549
jiabin0a488932020-08-07 17:32:40 -07003550 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003551 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003552 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3553 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003554 return status;
3555 }
3556
3557 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003558
3559 bool forceVolumeReeval = false;
3560 // FIXME: workaround for truncated touch sounds
3561 // to be removed when the problem is handled by system UI
3562 uint32_t delayMs = 0;
3563 if (strategy == mCommunnicationStrategy) {
3564 forceVolumeReeval = true;
3565 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3566 updateInputRouting();
3567 }
3568 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003569
3570 return NO_ERROR;
3571}
3572
jiabin0a488932020-08-07 17:32:40 -07003573status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3574 device_role_t role,
3575 AudioDeviceTypeAddrVector &devices) {
3576 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003577}
3578
Jiabin Huang3b98d322020-09-03 17:54:16 +00003579status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3580 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3581 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3582 dumpAudioDeviceTypeAddrVector(devices).c_str());
3583
Mikhail Naganov55773032020-10-01 15:08:13 -07003584 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003585 return BAD_VALUE;
3586 }
3587 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3588 ALOGW_IF(status != NO_ERROR,
3589 "Engine could not set preferred devices %s for audio source %d role %d",
3590 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3591
3592 return status;
3593}
3594
3595status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3596 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3597 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3598 dumpAudioDeviceTypeAddrVector(devices).c_str());
3599
Mikhail Naganov55773032020-10-01 15:08:13 -07003600 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003601 return BAD_VALUE;
3602 }
3603 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3604 ALOGW_IF(status != NO_ERROR,
3605 "Engine could not add preferred devices %s for audio source %d role %d",
3606 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3607
Eric Laurent2517af32020-11-25 15:31:27 +01003608 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003609 return status;
3610}
3611
3612status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3613 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3614{
3615 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3616 dumpAudioDeviceTypeAddrVector(devices).c_str());
3617
Mikhail Naganov55773032020-10-01 15:08:13 -07003618 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003619 return BAD_VALUE;
3620 }
3621
3622 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3623 audioSource, role, devices);
3624 ALOGW_IF(status != NO_ERROR,
3625 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3626
Eric Laurent2517af32020-11-25 15:31:27 +01003627 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003628 return status;
3629}
3630
3631status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3632 device_role_t role) {
3633 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3634
3635 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3636 ALOGW_IF(status != NO_ERROR,
3637 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3638
Eric Laurent2517af32020-11-25 15:31:27 +01003639 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003640 return status;
3641}
3642
3643status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3644 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3645 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3646}
3647
Oscar Azucena90e77632019-11-27 17:12:28 -08003648status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003649 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003650 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003651 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3652 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003653 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003654 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3655 if (status != NO_ERROR) {
3656 ALOGE("%s() could not set device affinity for userId %d",
3657 __FUNCTION__, userId);
3658 return status;
3659 }
3660
3661 // reevaluate outputs for all devices
3662 checkForDeviceAndOutputChanges();
3663 updateCallAndOutputRouting();
3664
3665 return NO_ERROR;
3666}
3667
3668status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003669 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003670 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3671 if (status != NO_ERROR) {
3672 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3673 __FUNCTION__, userId);
3674 return status;
3675 }
3676
3677 // reevaluate outputs for all devices
3678 checkForDeviceAndOutputChanges();
3679 updateCallAndOutputRouting();
3680
3681 return NO_ERROR;
3682}
3683
Andy Hungc29d82b2018-10-05 12:23:17 -07003684void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003685{
Andy Hungc29d82b2018-10-05 12:23:17 -07003686 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003687 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003688 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003689 std::string stateLiteral;
3690 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003691 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003692 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3693 "communications", "media", "record", "dock", "system",
3694 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3695 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3696 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003697 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3698 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3699 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3700 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3701 dst->append(" (MANUAL: ");
3702 dumpManualSurroundFormats(dst);
3703 dst->append(")");
3704 }
3705 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003706 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003707 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3708 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003709 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003710 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003711
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003712 dst->append("\n");
3713 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3714 dst->append("\n");
3715 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003716 mHwModulesAll.dump(dst);
3717 mOutputs.dump(dst);
3718 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003719 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003720 mAudioPatches.dump(dst);
3721 mPolicyMixes.dump(dst);
3722 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003723
Kevin Rocardb99cc752019-03-21 20:52:24 -07003724 dst->appendFormat(" AllowedCapturePolicies:\n");
3725 for (auto& policy : mAllowedCapturePolicies) {
3726 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3727 }
3728
François Gaffiec005e562018-11-06 15:04:49 +01003729 dst->appendFormat("\nPolicy Engine dump:\n");
3730 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003731}
3732
3733status_t AudioPolicyManager::dump(int fd)
3734{
3735 String8 result;
3736 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003737 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003738 return NO_ERROR;
3739}
3740
Kevin Rocardb99cc752019-03-21 20:52:24 -07003741status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3742{
3743 mAllowedCapturePolicies[uid] = capturePolicy;
3744 return NO_ERROR;
3745}
3746
Eric Laurente552edb2014-03-10 17:42:56 -07003747// This function checks for the parameters which can be offloaded.
3748// This can be enhanced depending on the capability of the DSP and policy
3749// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003750audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003751{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003752 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003753 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003754 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003755 offloadInfo.format,
3756 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3757 offloadInfo.has_video);
3758
jiabin2b9d5a12021-12-10 01:06:29 +00003759 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003760 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003761 }
3762
3763 // See if there is a profile to support this.
3764 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003765 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003766 offloadInfo.sample_rate,
3767 offloadInfo.format,
3768 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003769 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3770 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003771 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3772 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3773 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003774 if (profile == nullptr) {
3775 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3776 }
3777 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3778 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3779 }
3780 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003781}
3782
Michael Chana94fbb22018-04-24 14:31:19 +10003783bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3784 const audio_attributes_t& attributes) {
3785 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003786 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003787 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3788 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003789 config.sample_rate,
3790 config.format,
3791 config.channel_mask,
3792 output_flags,
3793 true /* directOnly */);
3794 ALOGV("%s() profile %sfound with name: %s, "
3795 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3796 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003797 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003798 config.sample_rate, config.format, config.channel_mask, output_flags);
3799 return (profile != 0);
3800}
3801
jiabin2b9d5a12021-12-10 01:06:29 +00003802bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3803 bool durationIgnored) {
3804 if (mMasterMono) {
3805 return false; // no offloading if mono is set.
3806 }
3807
3808 // Check if offload has been disabled
3809 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3810 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3811 return false;
3812 }
3813
3814 // Check if stream type is music, then only allow offload as of now.
3815 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3816 {
3817 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3818 return false;
3819 }
3820
3821 //TODO: enable audio offloading with video when ready
3822 const bool allowOffloadWithVideo =
3823 property_get_bool("audio.offload.video", false /* default_value */);
3824 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3825 ALOGV("%s: has_video == true, returning false", __func__);
3826 return false;
3827 }
3828
3829 //If duration is less than minimum value defined in property, return false
3830 const int min_duration_secs = property_get_int32(
3831 "audio.offload.min.duration.secs", -1 /* default_value */);
3832 if (!durationIgnored) {
3833 if (min_duration_secs >= 0) {
3834 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3835 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3836 __func__, min_duration_secs);
3837 return false;
3838 }
3839 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3840 ALOGV("%s: Offload denied by duration < default min(=%u)",
3841 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3842 return false;
3843 }
3844 }
3845
3846 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3847 // creating an offloaded track and tearing it down immediately after start when audioflinger
3848 // detects there is an active non offloadable effect.
3849 // FIXME: We should check the audio session here but we do not have it in this context.
3850 // This may prevent offloading in rare situations where effects are left active by apps
3851 // in the background.
3852 if (mEffects.isNonOffloadableEffectEnabled()) {
3853 return false;
3854 }
3855
3856 return true;
3857}
3858
3859audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
3860 const audio_config_t *config) {
3861 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
3862 offloadInfo.format = config->format;
3863 offloadInfo.sample_rate = config->sample_rate;
3864 offloadInfo.channel_mask = config->channel_mask;
3865 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
3866 offloadInfo.has_video = false;
3867 offloadInfo.is_streaming = false;
3868 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
3869
3870 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
3871 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3872 audio_flags_to_audio_output_flags(attr->flags, &flags);
3873 // only retain flags that will drive compressed offload or passthrough
3874 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
3875 if (offloadPossible) {
3876 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
3877 }
3878 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
3879
jiabinc8f7dfc2022-01-06 18:42:08 +00003880 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00003881 for (const auto& hwModule : mHwModules) {
3882 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00003883 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00003884 config->sample_rate, nullptr /*updatedSamplingRate*/,
3885 config->format, nullptr /*updatedFormat*/,
3886 config->channel_mask, nullptr /*updatedChannelMask*/,
3887 flags)) {
3888 continue;
3889 }
3890 // reject profiles not corresponding to a device currently available
3891 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
3892 continue;
3893 }
3894 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
3895 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00003896 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00003897 != AUDIO_DIRECT_NOT_SUPPORTED) {
3898 // Already reports offload gapless supported. No need to report offload support.
3899 continue;
3900 }
3901 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
3902 != AUDIO_OUTPUT_FLAG_NONE) {
3903 // If offload gapless is reported, no need to report offload support.
3904 directMode = (audio_direct_mode_t) ((directMode &
3905 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
3906 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
3907 } else {
3908 directMode = (audio_direct_mode_t)(directMode |AUDIO_DIRECT_OFFLOAD_SUPPORTED);
3909 }
3910 } else {
3911 directMode = (audio_direct_mode_t) (directMode |
3912 AUDIO_DIRECT_BITSTREAM_SUPPORTED);
3913 }
3914 }
3915 }
3916 return directMode;
3917}
3918
Dorin Drimusf2196d82022-01-03 12:11:18 +01003919status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
3920 AudioProfileVector& audioProfilesVector) {
3921 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08003922 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01003923 if (status != OK) {
3924 return status;
3925 }
3926 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
3927 if (devices.empty()) {
3928 return OK; // no output devices for the attributes
3929 }
3930
3931 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01003932 // the MSD module checks for different conditions
3933 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
3934 continue;
3935 }
3936 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
3937 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01003938 continue;
3939 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003940 // allow only profiles that support all the available and routed devices
3941 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01003942 != devices.size()) {
3943 continue;
3944 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003945 audioProfilesVector.addAllValidProfiles(
3946 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01003947 }
3948 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003949
3950 // add the direct profiles from MSD if present and has audio patches to all the output(s)
3951 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
3952 if (msdModule != nullptr) {
3953 if (msdHasPatchesToAllDevices(devices)) {
3954 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
3955 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
3956 if (!outputProfile->asAudioPort()->isDirectOutput()) {
3957 continue;
3958 }
3959 audioProfilesVector.addAllValidProfiles(
3960 outputProfile->asAudioPort()->getAudioProfiles());
3961 }
3962 } else {
3963 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
3964 }
3965 }
3966
Dorin Drimusf2196d82022-01-03 12:11:18 +01003967 return NO_ERROR;
3968}
3969
Eric Laurent6a94d692014-05-20 11:18:06 -07003970status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3971 audio_port_type_t type,
3972 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003973 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003974 unsigned int *generation)
3975{
jiabin19cdba52020-11-24 11:28:58 -08003976 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3977 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003978 return BAD_VALUE;
3979 }
3980 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003981 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003982 *num_ports = 0;
3983 }
3984
3985 size_t portsWritten = 0;
3986 size_t portsMax = *num_ports;
3987 *num_ports = 0;
3988 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003989 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3990 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003991 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003992 for (const auto& dev : mAvailableOutputDevices) {
3993 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003994 continue;
3995 }
3996 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003997 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003998 }
3999 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004000 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004001 }
4002 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004003 for (const auto& dev : mAvailableInputDevices) {
4004 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004005 continue;
4006 }
4007 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004008 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004009 }
4010 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004011 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004012 }
4013 }
4014 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4015 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4016 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4017 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4018 }
4019 *num_ports += mInputs.size();
4020 }
4021 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004022 size_t numOutputs = 0;
4023 for (size_t i = 0; i < mOutputs.size(); i++) {
4024 if (!mOutputs[i]->isDuplicated()) {
4025 numOutputs++;
4026 if (portsWritten < portsMax) {
4027 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4028 }
4029 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004030 }
Eric Laurent84c70242014-06-23 08:46:27 -07004031 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004032 }
4033 }
4034 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004035 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004036 return NO_ERROR;
4037}
4038
jiabin19cdba52020-11-24 11:28:58 -08004039status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004040{
Eric Laurent99fcae42018-05-17 16:59:18 -07004041 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4042 return BAD_VALUE;
4043 }
4044 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4045 if (dev != 0) {
4046 dev->toAudioPort(port);
4047 return NO_ERROR;
4048 }
4049 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4050 if (dev != 0) {
4051 dev->toAudioPort(port);
4052 return NO_ERROR;
4053 }
4054 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4055 if (out != 0) {
4056 out->toAudioPort(port);
4057 return NO_ERROR;
4058 }
4059 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4060 if (in != 0) {
4061 in->toAudioPort(port);
4062 return NO_ERROR;
4063 }
4064 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004065}
4066
François Gaffieafd4cea2019-11-18 15:50:22 +01004067status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4068 audio_patch_handle_t *handle,
4069 uid_t uid, uint32_t delayMs,
4070 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07004071{
François Gaffieafd4cea2019-11-18 15:50:22 +01004072 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004073 if (handle == NULL || patch == NULL) {
4074 return BAD_VALUE;
4075 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004076 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004077
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004078 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004079 return BAD_VALUE;
4080 }
4081 // only one source per audio patch supported for now
4082 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004083 return INVALID_OPERATION;
4084 }
Eric Laurent874c42872014-08-08 15:13:39 -07004085
4086 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004087 return INVALID_OPERATION;
4088 }
Eric Laurent874c42872014-08-08 15:13:39 -07004089 for (size_t i = 0; i < patch->num_sinks; i++) {
4090 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4091 return INVALID_OPERATION;
4092 }
4093 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004094
4095 sp<AudioPatch> patchDesc;
4096 ssize_t index = mAudioPatches.indexOfKey(*handle);
4097
François Gaffieafd4cea2019-11-18 15:50:22 +01004098 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4099 patch->sources[0].role,
4100 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004101#if LOG_NDEBUG == 0
4102 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004103 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4104 patch->sinks[i].role,
4105 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004106 }
4107#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004108
4109 if (index >= 0) {
4110 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004111 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4112 __func__, mUidCached, patchDesc->getUid(), uid);
4113 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004114 return INVALID_OPERATION;
4115 }
4116 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004117 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004118 }
4119
4120 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004121 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004122 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004123 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004124 return BAD_VALUE;
4125 }
Eric Laurent84c70242014-06-23 08:46:27 -07004126 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4127 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004128 if (patchDesc != 0) {
4129 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004130 ALOGV("%s source id differs for patch current id %d new id %d",
4131 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004132 return BAD_VALUE;
4133 }
4134 }
Eric Laurent874c42872014-08-08 15:13:39 -07004135 DeviceVector devices;
4136 for (size_t i = 0; i < patch->num_sinks; i++) {
4137 // Only support mix to devices connection
4138 // TODO add support for mix to mix connection
4139 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004140 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004141 return INVALID_OPERATION;
4142 }
4143 sp<DeviceDescriptor> devDesc =
4144 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4145 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004146 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004147 return BAD_VALUE;
4148 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004149
François Gaffie11d30102018-11-02 16:09:09 +01004150 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004151 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004152 NULL, // updatedSamplingRate
4153 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004154 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004155 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004156 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004157 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004158 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004159 return INVALID_OPERATION;
4160 }
4161 devices.add(devDesc);
4162 }
4163 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004164 return INVALID_OPERATION;
4165 }
Eric Laurent874c42872014-08-08 15:13:39 -07004166
Eric Laurent6a94d692014-05-20 11:18:06 -07004167 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004168 ALOGV("%s setting device %s on output %d",
4169 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004170 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004171 index = mAudioPatches.indexOfKey(*handle);
4172 if (index >= 0) {
4173 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004174 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004175 }
4176 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004177 patchDesc->setUid(uid);
4178 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004179 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004180 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004181 return INVALID_OPERATION;
4182 }
4183 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4184 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4185 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004186 // only one sink supported when connecting an input device to a mix
4187 if (patch->num_sinks > 1) {
4188 return INVALID_OPERATION;
4189 }
François Gaffie53615e22015-03-19 09:24:12 +01004190 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004191 if (inputDesc == NULL) {
4192 return BAD_VALUE;
4193 }
4194 if (patchDesc != 0) {
4195 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4196 return BAD_VALUE;
4197 }
4198 }
François Gaffie11d30102018-11-02 16:09:09 +01004199 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004200 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004201 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004202 return BAD_VALUE;
4203 }
4204
François Gaffie11d30102018-11-02 16:09:09 +01004205 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004206 patch->sinks[0].sample_rate,
4207 NULL, /*updatedSampleRate*/
4208 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004209 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004210 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004211 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004212 // FIXME for the parameter type,
4213 // and the NONE
4214 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004215 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004216 return INVALID_OPERATION;
4217 }
4218 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004219 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004220 device->toString().c_str(), inputDesc->mIoHandle);
4221 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004222 index = mAudioPatches.indexOfKey(*handle);
4223 if (index >= 0) {
4224 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004225 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004226 }
4227 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004228 patchDesc->setUid(uid);
4229 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004230 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004231 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004232 return INVALID_OPERATION;
4233 }
4234 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4235 // device to device connection
4236 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004237 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004238 return BAD_VALUE;
4239 }
4240 }
François Gaffie11d30102018-11-02 16:09:09 +01004241 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004242 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004243 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004244 return BAD_VALUE;
4245 }
Eric Laurent874c42872014-08-08 15:13:39 -07004246
Eric Laurent6a94d692014-05-20 11:18:06 -07004247 //update source and sink with our own data as the data passed in the patch may
4248 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004249 PatchBuilder patchBuilder;
4250 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004251
4252 // if first sink is to MSD, establish single MSD patch
4253 if (getMsdAudioOutDevices().contains(
4254 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4255 ALOGV("%s patching to MSD", __FUNCTION__);
4256 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4257 goto installPatch;
4258 }
4259
François Gaffieafd4cea2019-11-18 15:50:22 +01004260 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4261 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004262
Eric Laurent874c42872014-08-08 15:13:39 -07004263 for (size_t i = 0; i < patch->num_sinks; i++) {
4264 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004265 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004266 return INVALID_OPERATION;
4267 }
François Gaffie11d30102018-11-02 16:09:09 +01004268 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004269 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004270 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004271 return BAD_VALUE;
4272 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004273 audio_port_config sinkPortConfig = {};
4274 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4275 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004276
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004277 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4278 // volume management purpose (tracking activity)
4279 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4280 // in config XML to reach the sink so that is can be declared as available.
4281 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4282 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4283 if (sourceDesc != nullptr) {
4284 // take care of dynamic routing for SwOutput selection,
4285 audio_attributes_t attributes = sourceDesc->attributes();
4286 audio_stream_type_t stream = sourceDesc->stream();
4287 audio_attributes_t resultAttr;
4288 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4289 config.sample_rate = sourceDesc->config().sample_rate;
4290 config.channel_mask = sourceDesc->config().channel_mask;
4291 config.format = sourceDesc->config().format;
4292 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4293 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4294 bool isRequestedDeviceForExclusiveUse = false;
4295 output_type_t outputType;
4296 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4297 &stream, sourceDesc->uid(), &config, &flags,
4298 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4299 nullptr, &outputType);
4300 if (output == AUDIO_IO_HANDLE_NONE) {
4301 ALOGV("%s no output for device %s",
4302 __FUNCTION__, sinkDevice->toString().c_str());
4303 return INVALID_OPERATION;
4304 }
4305 outputDesc = mOutputs.valueFor(output);
4306 if (outputDesc->isDuplicated()) {
4307 ALOGE("%s output is duplicated", __func__);
4308 return INVALID_OPERATION;
4309 }
4310 sourceDesc->setSwOutput(outputDesc);
4311 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004312 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004313 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004314 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004315 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004316 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4317 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004318 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4319 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004320 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4321 (sourceDesc != nullptr &&
4322 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004323 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004324 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004325 return INVALID_OPERATION;
4326 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004327 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004328 SortedVector<audio_io_handle_t> outputs =
4329 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4330 // if the sink device is reachable via an opened output stream, request to
4331 // go via this output stream by adding a second source to the patch
4332 // description
4333 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004334 if (output != AUDIO_IO_HANDLE_NONE) {
4335 outputDesc = mOutputs.valueFor(output);
4336 if (outputDesc->isDuplicated()) {
4337 ALOGV("%s output for device %s is duplicated",
4338 __FUNCTION__, sinkDevice->toString().c_str());
4339 return INVALID_OPERATION;
4340 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004341 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004342 }
4343 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004344 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004345 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004346 // for volume control, we may need a valid stream
4347 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4348 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4349 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004350 }
Eric Laurent83b88082014-06-20 18:31:16 -07004351 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004352 }
4353 // TODO: check from routing capabilities in config file and other conflicting patches
4354
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004355installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004356 status_t status = installPatch(
4357 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004358 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004359 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004360 return INVALID_OPERATION;
4361 }
4362 } else {
4363 return BAD_VALUE;
4364 }
4365 } else {
4366 return BAD_VALUE;
4367 }
4368 return NO_ERROR;
4369}
4370
4371status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4372 uid_t uid)
4373{
4374 ALOGV("releaseAudioPatch() patch %d", handle);
4375
4376 ssize_t index = mAudioPatches.indexOfKey(handle);
4377
4378 if (index < 0) {
4379 return BAD_VALUE;
4380 }
4381 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004382 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4383 __func__, mUidCached, patchDesc->getUid(), uid);
4384 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004385 return INVALID_OPERATION;
4386 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004387 return releaseAudioPatchInternal(handle);
4388}
Eric Laurent6a94d692014-05-20 11:18:06 -07004389
François Gaffieafd4cea2019-11-18 15:50:22 +01004390status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4391 uint32_t delayMs)
4392{
4393 ALOGV("%s patch %d", __func__, handle);
4394 if (mAudioPatches.indexOfKey(handle) < 0) {
4395 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4396 return BAD_VALUE;
4397 }
4398 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004399 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004400 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004401 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004402 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004403 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004404 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004405 return BAD_VALUE;
4406 }
4407
François Gaffie11d30102018-11-02 16:09:09 +01004408 setOutputDevices(outputDesc,
4409 getNewOutputDevices(outputDesc, true /*fromCache*/),
4410 true,
4411 0,
4412 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004413 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4414 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004415 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004416 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004417 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004418 return BAD_VALUE;
4419 }
4420 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004421 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004422 true,
4423 NULL);
4424 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004425 status_t status =
4426 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4427 ALOGV("%s patch panel returned %d patchHandle %d",
4428 __func__, status, patchDesc->getAfHandle());
4429 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004430 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004431 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004432 // SW Bridge
4433 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4434 sp<SwAudioOutputDescriptor> outputDesc =
4435 mOutputs.getOutputFromId(patch->sources[1].id);
4436 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004437 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4438 // releaseOutput has already called closeOuput in case of direct output
4439 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004440 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004441 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4442 // force SwOutput patch removal as AF counter part patch has already gone.
4443 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4444 removeAudioPatch(outputDesc->getPatchHandle());
4445 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004446 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4447 setOutputDevices(outputDesc,
4448 getNewOutputDevices(outputDesc, true /*fromCache*/),
4449 true, /*force*/
4450 0,
4451 NULL);
4452 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004453 } else {
4454 return BAD_VALUE;
4455 }
4456 } else {
4457 return BAD_VALUE;
4458 }
4459 return NO_ERROR;
4460}
4461
4462status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4463 struct audio_patch *patches,
4464 unsigned int *generation)
4465{
François Gaffie53615e22015-03-19 09:24:12 +01004466 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004467 return BAD_VALUE;
4468 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004469 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004470 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004471}
4472
Eric Laurente1715a42014-05-20 11:30:42 -07004473status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004474{
Eric Laurente1715a42014-05-20 11:30:42 -07004475 ALOGV("setAudioPortConfig()");
4476
4477 if (config == NULL) {
4478 return BAD_VALUE;
4479 }
4480 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4481 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004482 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4483 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004484 }
4485
Eric Laurenta121f902014-06-03 13:32:54 -07004486 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004487 if (config->type == AUDIO_PORT_TYPE_MIX) {
4488 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004489 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004490 if (outputDesc == NULL) {
4491 return BAD_VALUE;
4492 }
Eric Laurent84c70242014-06-23 08:46:27 -07004493 ALOG_ASSERT(!outputDesc->isDuplicated(),
4494 "setAudioPortConfig() called on duplicated output %d",
4495 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004496 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004497 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004498 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004499 if (inputDesc == NULL) {
4500 return BAD_VALUE;
4501 }
Eric Laurenta121f902014-06-03 13:32:54 -07004502 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004503 } else {
4504 return BAD_VALUE;
4505 }
4506 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4507 sp<DeviceDescriptor> deviceDesc;
4508 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4509 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4510 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4511 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4512 } else {
4513 return BAD_VALUE;
4514 }
4515 if (deviceDesc == NULL) {
4516 return BAD_VALUE;
4517 }
Eric Laurenta121f902014-06-03 13:32:54 -07004518 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004519 } else {
4520 return BAD_VALUE;
4521 }
4522
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004523 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004524 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4525 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004526 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004527 audioPortConfig->toAudioPortConfig(&newConfig, config);
4528 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004529 }
Eric Laurenta121f902014-06-03 13:32:54 -07004530 if (status != NO_ERROR) {
4531 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004532 }
Eric Laurente1715a42014-05-20 11:30:42 -07004533
4534 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004535}
4536
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004537void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4538{
Eric Laurentd60560a2015-04-10 11:31:20 -07004539 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004540 clearAudioPatches(uid);
4541 clearSessionRoutes(uid);
4542}
4543
Eric Laurent6a94d692014-05-20 11:18:06 -07004544void AudioPolicyManager::clearAudioPatches(uid_t uid)
4545{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004546 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004547 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004548 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004549 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004550 }
4551 }
4552}
4553
François Gaffiec005e562018-11-06 15:04:49 +01004554void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004555{
François Gaffiec005e562018-11-06 15:04:49 +01004556 // Take the first attributes following the product strategy as it is used to retrieve the routed
4557 // device. All attributes wihin a strategy follows the same "routing strategy"
4558 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4559 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004560 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004561 for (size_t j = 0; j < mOutputs.size(); j++) {
4562 if (mOutputs.keyAt(j) == ouptutToSkip) {
4563 continue;
4564 }
4565 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004566 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004567 continue;
4568 }
4569 // If the default device for this strategy is on another output mix,
4570 // invalidate all tracks in this strategy to force re connection.
4571 // Otherwise select new device on the output mix.
4572 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004573 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4574 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004575 }
4576 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004577 setOutputDevices(
4578 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004579 }
4580 }
4581}
4582
4583void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4584{
4585 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004586 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004587 for (size_t i = 0; i < mOutputs.size(); i++) {
4588 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004589 for (const auto& client : outputDesc->getClientIterable()) {
4590 if (client->hasPreferredDevice() && client->uid() == uid) {
4591 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004592 auto clientStrategy = client->strategy();
4593 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4594 end(affectedStrategies)) {
4595 continue;
4596 }
4597 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004598 }
4599 }
4600 }
4601 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004602 for (const auto& strategy : affectedStrategies) {
4603 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004604 }
4605
4606 // remove input routes associated with this uid
4607 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004608 for (size_t i = 0; i < mInputs.size(); i++) {
4609 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004610 for (const auto& client : inputDesc->getClientIterable()) {
4611 if (client->hasPreferredDevice() && client->uid() == uid) {
4612 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4613 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004614 }
4615 }
4616 }
4617 // reroute inputs if necessary
4618 SortedVector<audio_io_handle_t> inputsToClose;
4619 for (size_t i = 0; i < mInputs.size(); i++) {
4620 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004621 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004622 inputsToClose.add(inputDesc->mIoHandle);
4623 }
4624 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004625 for (const auto& input : inputsToClose) {
4626 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004627 }
4628}
4629
Eric Laurentd60560a2015-04-10 11:31:20 -07004630void AudioPolicyManager::clearAudioSources(uid_t uid)
4631{
4632 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004633 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4634 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004635 stopAudioSource(mAudioSources.keyAt(i));
4636 }
4637 }
4638}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004639
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004640status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4641 audio_io_handle_t *ioHandle,
4642 audio_devices_t *device)
4643{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004644 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4645 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004646 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004647 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004648
François Gaffiedf372692015-03-19 10:43:27 +01004649 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004650}
4651
Eric Laurentd60560a2015-04-10 11:31:20 -07004652status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004653 const audio_attributes_t *attributes,
4654 audio_port_handle_t *portId,
4655 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004656{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004657 ALOGV("%s", __FUNCTION__);
4658 *portId = AUDIO_PORT_HANDLE_NONE;
4659
4660 if (source == NULL || attributes == NULL || portId == NULL) {
4661 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4662 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004663 return BAD_VALUE;
4664 }
4665
Eric Laurentd60560a2015-04-10 11:31:20 -07004666 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4667 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004668 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4669 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004670 return INVALID_OPERATION;
4671 }
4672
François Gaffie11d30102018-11-02 16:09:09 +01004673 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004674 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004675 String8(source->ext.device.address),
4676 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004677 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004678 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004679 return BAD_VALUE;
4680 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004681
jiabin4ef93452019-09-10 14:29:54 -07004682 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004683
François Gaffieaaac0fd2018-11-22 17:56:39 +01004684 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004685 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004686 mEngine->getStreamTypeForAttributes(*attributes),
4687 mEngine->getProductStrategyForAttributes(*attributes),
4688 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004689
4690 status_t status = connectAudioSource(sourceDesc);
4691 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004692 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004693 }
4694 return status;
4695}
4696
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004697status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004698{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004699 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004700
4701 // make sure we only have one patch per source.
4702 disconnectAudioSource(sourceDesc);
4703
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004704 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004705 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4706 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4707 sourceDesc->srcDevice()->type(),
4708 String8(sourceDesc->srcDevice()->address().c_str()),
4709 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004710 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004711 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004712 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004713 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004714 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4715 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4716 return INVALID_OPERATION;
4717 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004718 PatchBuilder patchBuilder;
4719 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4720 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4721 status_t status =
4722 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4723 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4724 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4725 return INVALID_OPERATION;
4726 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004727 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004728 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4729 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4730 if (swOutput != 0) {
4731 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004732 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004733 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004734 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004735 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004736 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004737 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004738 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004739 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004740 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004741 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004742 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004743 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4744 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004745 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004746 if (delayMs != 0) {
4747 usleep(delayMs * 1000);
4748 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004749 } else {
4750 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4751 if (hwOutputDesc != 0) {
4752 // create Hwoutput and add to mHwOutputs
4753 } else {
4754 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4755 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004756 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004757 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004758
4759FailureSourceActive:
4760 swOutput->stop();
4761 releaseOutput(sourceDesc->portId());
4762FailureSourceAdded:
4763 sourceDesc->setSwOutput(nullptr);
4764FailureReleasePatch:
4765 releaseAudioPatchInternal(handle);
4766 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004767}
4768
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004769status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004770{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004771 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4772 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004773 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004774 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004775 return BAD_VALUE;
4776 }
4777 status_t status = disconnectAudioSource(sourceDesc);
4778
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004779 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004780 return status;
4781}
4782
Andy Hung2ddee192015-12-18 17:34:44 -08004783status_t AudioPolicyManager::setMasterMono(bool mono)
4784{
4785 if (mMasterMono == mono) {
4786 return NO_ERROR;
4787 }
4788 mMasterMono = mono;
4789 // if enabling mono we close all offloaded devices, which will invalidate the
4790 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4791 // for recreating the new AudioTrack as non-offloaded PCM.
4792 //
4793 // If disabling mono, we leave all tracks as is: we don't know which clients
4794 // and tracks are able to be recreated as offloaded. The next "song" should
4795 // play back offloaded.
4796 if (mMasterMono) {
4797 Vector<audio_io_handle_t> offloaded;
4798 for (size_t i = 0; i < mOutputs.size(); ++i) {
4799 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4800 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4801 offloaded.push(desc->mIoHandle);
4802 }
4803 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004804 for (const auto& handle : offloaded) {
4805 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004806 }
4807 }
4808 // update master mono for all remaining outputs
4809 for (size_t i = 0; i < mOutputs.size(); ++i) {
4810 updateMono(mOutputs.keyAt(i));
4811 }
4812 return NO_ERROR;
4813}
4814
4815status_t AudioPolicyManager::getMasterMono(bool *mono)
4816{
4817 *mono = mMasterMono;
4818 return NO_ERROR;
4819}
4820
Eric Laurentac9cef52017-06-09 15:46:26 -07004821float AudioPolicyManager::getStreamVolumeDB(
4822 audio_stream_type_t stream, int index, audio_devices_t device)
4823{
jiabin9a3361e2019-10-01 09:38:30 -07004824 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004825}
4826
jiabin81772902018-04-02 17:52:27 -07004827status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4828 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004829 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004830{
Kriti Dang6537def2021-03-02 13:46:59 +01004831 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4832 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004833 return BAD_VALUE;
4834 }
Kriti Dang6537def2021-03-02 13:46:59 +01004835 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4836 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004837
4838 size_t formatsWritten = 0;
4839 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004840
Kriti Dang6537def2021-03-02 13:46:59 +01004841 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004842 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4843 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004844 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004845 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004846 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004847 bool formatEnabled = true;
4848 switch (forceUse) {
4849 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004850 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004851 break;
4852 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4853 formatEnabled = false;
4854 break;
4855 default: // AUTO or ALWAYS => true
4856 break;
jiabin81772902018-04-02 17:52:27 -07004857 }
4858 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4859 }
jiabin81772902018-04-02 17:52:27 -07004860 }
4861 return NO_ERROR;
4862}
4863
Kriti Dang6537def2021-03-02 13:46:59 +01004864status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4865 audio_format_t *surroundFormats) {
4866 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4867 return BAD_VALUE;
4868 }
4869 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4870 __func__, *numSurroundFormats, surroundFormats);
4871
4872 size_t formatsWritten = 0;
4873 size_t formatsMax = *numSurroundFormats;
4874 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4875
4876 // Return formats from all device profiles that have already been resolved by
4877 // checkOutputsForDevice().
4878 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4879 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4880 audio_devices_t deviceType = device->type();
4881 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4882 // returns formats reported by HDMI devices.
4883 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4884 continue;
4885 }
4886 // Formats reported by sink devices
4887 std::unordered_set<audio_format_t> formatset;
4888 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4889 formatset.insert(it->second.begin(), it->second.end());
4890 }
4891
4892 // Formats hard-coded in the in policy configuration file (if any).
4893 FormatVector encodedFormats = device->encodedFormats();
4894 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4895 // Filter the formats which are supported by the vendor hardware.
4896 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4897 if (mConfig.getSurroundFormats().count(*it) != 0) {
4898 formats.insert(*it);
4899 } else {
4900 for (const auto& pair : mConfig.getSurroundFormats()) {
4901 if (pair.second.count(*it) != 0) {
4902 formats.insert(pair.first);
4903 break;
4904 }
4905 }
4906 }
4907 }
4908 }
4909 *numSurroundFormats = formats.size();
4910 for (const auto& format: formats) {
4911 if (formatsWritten < formatsMax) {
4912 surroundFormats[formatsWritten++] = format;
4913 }
4914 }
4915 return NO_ERROR;
4916}
4917
jiabin81772902018-04-02 17:52:27 -07004918status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4919{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004920 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004921 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4922 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004923 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004924 return BAD_VALUE;
4925 }
4926
Mikhail Naganov100f0122018-11-29 11:22:16 -08004927 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4928 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004929 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004930 return INVALID_OPERATION;
4931 }
4932
Mikhail Naganov100f0122018-11-29 11:22:16 -08004933 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004934 return NO_ERROR;
4935 }
4936
Mikhail Naganov100f0122018-11-29 11:22:16 -08004937 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004938 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004939 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004940 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004941 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004942 }
4943 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004944 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004945 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004946 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004947 }
4948 }
4949
4950 sp<SwAudioOutputDescriptor> outputDesc;
4951 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004952 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4953 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004954 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4955 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004956 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004957 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004958 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4959 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4960 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004961 name.c_str(),
4962 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004963 if (status != NO_ERROR) {
4964 continue;
4965 }
4966 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4967 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4968 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004969 name.c_str(),
4970 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004971 profileUpdated |= (status == NO_ERROR);
4972 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004973 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004974 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004975 AUDIO_DEVICE_IN_HDMI);
4976 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4977 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004978 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004979 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004980 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4981 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4982 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004983 name.c_str(),
4984 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004985 if (status != NO_ERROR) {
4986 continue;
4987 }
4988 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4989 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4990 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004991 name.c_str(),
4992 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004993 profileUpdated |= (status == NO_ERROR);
4994 }
4995
jiabin81772902018-04-02 17:52:27 -07004996 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004997 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004998 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004999 }
5000
5001 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5002}
5003
Eric Laurent5ada82e2019-08-29 17:53:54 -07005004void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005005{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005006 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005007 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005008 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005009 }
5010}
5011
jiabin6012f912018-11-02 17:06:30 -07005012bool AudioPolicyManager::isHapticPlaybackSupported()
5013{
5014 for (const auto& hwModule : mHwModules) {
5015 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5016 for (const auto &outProfile : outputProfiles) {
5017 struct audio_port audioPort;
5018 outProfile->toAudioPort(&audioPort);
5019 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5020 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5021 return true;
5022 }
5023 }
5024 }
5025 }
5026 return false;
5027}
5028
Carter Hsu325a8eb2022-01-19 19:56:51 +08005029bool AudioPolicyManager::isUltrasoundSupported()
5030{
5031 bool hasUltrasoundOutput = false;
5032 bool hasUltrasoundInput = false;
5033 for (const auto& hwModule : mHwModules) {
5034 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5035 if (!hasUltrasoundOutput) {
5036 for (const auto &outProfile : outputProfiles) {
5037 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5038 hasUltrasoundOutput = true;
5039 break;
5040 }
5041 }
5042 }
5043
5044 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5045 if (!hasUltrasoundInput) {
5046 for (const auto &inputProfile : inputProfiles) {
5047 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5048 hasUltrasoundInput = true;
5049 break;
5050 }
5051 }
5052 }
5053
5054 if (hasUltrasoundOutput && hasUltrasoundInput)
5055 return true;
5056 }
5057 return false;
5058}
5059
Eric Laurent8340e672019-11-06 11:01:08 -08005060bool AudioPolicyManager::isCallScreenModeSupported()
5061{
5062 return getConfig().isCallScreenModeSupported();
5063}
5064
5065
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005066status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005067{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005068 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005069 if (!sourceDesc->isConnected()) {
5070 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5071 return NO_ERROR;
5072 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005073 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5074 if (swOutput != 0) {
5075 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005076 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005077 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005078 }
jiabinbce0c1d2020-10-05 11:20:18 -07005079 if (releaseOutput(sourceDesc->portId())) {
5080 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5081 // no need to release audio patch here but just return NO_ERROR.
5082 return NO_ERROR;
5083 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005084 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005085 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005086 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005087 // close Hwoutput and remove from mHwOutputs
5088 } else {
5089 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5090 }
5091 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005092 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
5093 sourceDesc->disconnect();
5094 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005095}
5096
François Gaffiec005e562018-11-06 15:04:49 +01005097sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5098 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005099{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005100 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005101 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005102 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005103 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005104 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5105 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005106 source = sourceDesc;
5107 break;
5108 }
5109 }
5110 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005111}
5112
Eric Laurent39095982021-08-24 18:29:27 +02005113/* static */
5114bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
5115 switch (channels) {
5116 case AUDIO_CHANNEL_OUT_5POINT1:
5117 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
5118 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
5119 case AUDIO_CHANNEL_OUT_7POINT1:
5120 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
5121 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
5122 return true;
5123 default:
5124 return false;
5125 }
5126}
5127
Eric Laurentb4f42a92022-01-17 17:37:31 +01005128bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005129 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005130 const AudioDeviceTypeAddrVector &devices,
5131 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005132{
5133 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5134 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005135 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005136 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005137 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5138 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5139 return false;
5140 }
5141 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5142 return false;
5143 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005144 }
5145
5146 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005147 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5148 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005149 // to the specified devices must exist.
5150 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005151 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005152 if (profile == nullptr) {
5153 return false;
5154 }
5155
5156 // The caller can have the audio config criteria ignored by either passing a null ptr or
5157 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005158 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005159 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005160 // If the spatializer output is already opened, only channel masks included in the
5161 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005162
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005163 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005164 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005165 return false;
5166 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005167 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5168 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005169 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005170 != config->channel_mask) {
5171 return false;
5172 }
5173 }
5174 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005175 return true;
5176}
5177
5178void AudioPolicyManager::checkVirtualizerClientRoutes() {
5179 std::set<audio_stream_type_t> streamsToInvalidate;
5180 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005181 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5182 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005183 audio_attributes_t attr = client->attributes();
5184 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5185 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5186 audio_config_base_t clientConfig = client->config();
5187 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005188 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005189 && canBeSpatializedInt(&attr, &config,
5190 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005191 streamsToInvalidate.insert(client->stream());
5192 }
5193 }
5194 }
5195
5196 for (audio_stream_type_t stream : streamsToInvalidate) {
5197 mpClientInterface->invalidateStream(stream);
5198 }
5199}
5200
Eric Laurentfa0f6742021-08-17 18:39:44 +02005201status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005202 const audio_attributes_t *attr,
5203 audio_io_handle_t *output) {
5204 *output = AUDIO_IO_HANDLE_NONE;
5205
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005206 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5207 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5208 audio_config_t *configPtr = nullptr;
5209 audio_config_t config;
5210 if (mixerConfig != nullptr) {
5211 config = audio_config_initializer(mixerConfig);
5212 configPtr = &config;
5213 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005214 if (!canBeSpatializedInt(
5215 attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02005216 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005217 return BAD_VALUE;
5218 }
5219
5220 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005221 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005222 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005223 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005224 return BAD_VALUE;
5225 }
5226
Eric Laurent39095982021-08-24 18:29:27 +02005227 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
5228 && configPtr != nullptr
5229 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
5230 *output = mSpatializerOutput->mIoHandle;
5231 ALOGV("%s returns current spatializer output %d", __func__, *output);
5232 return NO_ERROR;
5233 }
5234 mSpatializerOutput.clear();
5235 for (size_t i = 0; i < mOutputs.size(); i++) {
5236 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5237 if (!desc->isDuplicated() && desc->mProfile == profile) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005238 ALOGV("%s found output %d for spatializer profile", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005239 mSpatializerOutput = desc;
5240 break;
5241 }
5242 }
5243 if (mSpatializerOutput == nullptr) {
5244 ALOGW("%s no opened spatializer output for profile %s",
5245 __func__, profile->getName().c_str());
5246 return BAD_VALUE;
5247 }
5248
5249 if (configPtr != nullptr
5250 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5251 audio_config_base_t savedMixerConfig = {
5252 .sample_rate = mSpatializerOutput->getSamplingRate(),
5253 .format = mSpatializerOutput->getFormat(),
5254 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5255 };
5256 DeviceVector savedDevices = mSpatializerOutput->devices();
5257
Eric Laurentb4f42a92022-01-17 17:37:31 +01005258 ALOGV("%s reopening spatializer output to match channel mask %#x (current mask %#x)",
5259 __func__, configPtr->channel_mask, mSpatializerOutput->mMixerChannelMask);
Eric Laurent39095982021-08-24 18:29:27 +02005260
Eric Laurentb4f42a92022-01-17 17:37:31 +01005261 closeOutput(mSpatializerOutput->mIoHandle);
5262 //from now on mSpatializerOutput is null
5263
5264 sp<SwAudioOutputDescriptor> desc =
5265 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
5266 if (desc == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005267 // re open the spatializer output with previous channel mask
Eric Laurentb4f42a92022-01-17 17:37:31 +01005268 desc = openOutputWithProfileAndDevice(profile, savedDevices, &savedMixerConfig);
5269 if (desc == nullptr) {
5270 ALOGE("%s failed to restore mSpatializerOutput with previous config", __func__);
Eric Laurent39095982021-08-24 18:29:27 +02005271 } else {
5272 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005273 }
5274 mPreviousOutputs = mOutputs;
5275 mpClientInterface->onAudioPortListUpdate();
5276 *output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005277 ALOGW("%s could not open spatializer output with requested config", __func__);
5278 return BAD_VALUE;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005279 }
Eric Laurent39095982021-08-24 18:29:27 +02005280 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005281 mPreviousOutputs = mOutputs;
5282 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005283 }
5284
5285 checkVirtualizerClientRoutes();
5286
Eric Laurent39095982021-08-24 18:29:27 +02005287 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005288 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005289 return NO_ERROR;
5290}
5291
Eric Laurentfa0f6742021-08-17 18:39:44 +02005292status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5293 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005294 return INVALID_OPERATION;
5295 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005296 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005297 return BAD_VALUE;
5298 }
Eric Laurent39095982021-08-24 18:29:27 +02005299
Eric Laurentfa0f6742021-08-17 18:39:44 +02005300 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005301
5302 checkVirtualizerClientRoutes();
5303
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005304 return NO_ERROR;
5305}
5306
Eric Laurente552edb2014-03-10 17:42:56 -07005307// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005308// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005309// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005310uint32_t AudioPolicyManager::nextAudioPortGeneration()
5311{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005312 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005313}
5314
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005315static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005316 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5317 !audioPolicyXmlConfigFile.empty()) {
5318 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5319 if (ret == NO_ERROR) {
5320 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005321 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005322 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005323 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005324 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005325}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005326
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005327AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5328 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005329 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005330 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005331 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005332 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005333 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005334 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005335 mAudioPortGeneration(1),
5336 mBeaconMuteRefCount(0),
5337 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005338 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005339 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005340 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005341 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005342{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005343}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005344
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005345AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5346 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5347{
5348 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005349}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005350
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005351void AudioPolicyManager::loadConfig() {
5352 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005353 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005354 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005355 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005356}
5357
5358status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005359 {
5360 auto engLib = EngineLibrary::load(
5361 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5362 if (!engLib) {
5363 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5364 return NO_INIT;
5365 }
5366 mEngine = engLib->createEngine();
5367 if (mEngine == nullptr) {
5368 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5369 return NO_INIT;
5370 }
François Gaffie2110e042015-03-24 08:41:51 +01005371 }
5372 mEngine->setObserver(this);
5373 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005374 if (status != NO_ERROR) {
5375 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5376 return status;
5377 }
François Gaffie2110e042015-03-24 08:41:51 +01005378
Eric Laurent1d69c872021-01-11 18:53:01 +01005379 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5380 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5381
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005382 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005383 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005384 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005385
Eric Laurent3a4311c2014-03-17 12:00:47 -07005386 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005387 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5388 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5389 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005390 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005391 }
jiabin9ff780e2018-03-19 18:19:52 -07005392 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005393 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005394 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005395 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005396 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005397 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005398 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005399 }
5400 }
5401 }
Eric Laurente552edb2014-03-10 17:42:56 -07005402
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005403 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005404
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005405 // Silence ALOGV statements
5406 property_set("log.tag." LOG_TAG, "D");
5407
Eric Laurente552edb2014-03-10 17:42:56 -07005408 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005409 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005410}
5411
Eric Laurente0720872014-03-11 09:30:41 -07005412AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005413{
Eric Laurente552edb2014-03-10 17:42:56 -07005414 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005415 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005416 }
5417 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005418 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005419 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005420 mAvailableOutputDevices.clear();
5421 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005422 mOutputs.clear();
5423 mInputs.clear();
5424 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005425 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005426 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005427}
5428
Eric Laurente0720872014-03-11 09:30:41 -07005429status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005430{
Eric Laurent87ffa392015-05-22 10:32:38 -07005431 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005432}
5433
Eric Laurente552edb2014-03-10 17:42:56 -07005434// ---
5435
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005436void AudioPolicyManager::onNewAudioModulesAvailable()
5437{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005438 DeviceVector newDevices;
5439 onNewAudioModulesAvailableInt(&newDevices);
5440 if (!newDevices.empty()) {
5441 nextAudioPortGeneration();
5442 mpClientInterface->onAudioPortListUpdate();
5443 }
5444}
5445
5446void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5447{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005448 for (const auto& hwModule : mHwModulesAll) {
5449 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5450 continue;
5451 }
5452 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5453 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5454 ALOGW("could not open HW module %s", hwModule->getName());
5455 continue;
5456 }
5457 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005458 // open all output streams needed to access attached devices.
5459 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005460 // This also validates mAvailableOutputDevices list
5461 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5462 if (!outProfile->canOpenNewIo()) {
5463 ALOGE("Invalid Output profile max open count %u for profile %s",
5464 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5465 continue;
5466 }
5467 if (!outProfile->hasSupportedDevices()) {
5468 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5469 continue;
5470 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005471 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5472 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005473 mTtsOutputAvailable = true;
5474 }
5475
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005476 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5477 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5478 sp<DeviceDescriptor> supportedDevice = 0;
5479 if (supportedDevices.contains(mDefaultOutputDevice)) {
5480 supportedDevice = mDefaultOutputDevice;
5481 } else {
5482 // choose first device present in profile's SupportedDevices also part of
5483 // mAvailableOutputDevices.
5484 if (availProfileDevices.isEmpty()) {
5485 continue;
5486 }
5487 supportedDevice = availProfileDevices.itemAt(0);
5488 }
5489 if (!mOutputDevicesAll.contains(supportedDevice)) {
5490 continue;
5491 }
5492 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5493 mpClientInterface);
5494 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005495 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5496 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005497 AUDIO_STREAM_DEFAULT,
5498 AUDIO_OUTPUT_FLAG_NONE, &output);
5499 if (status != NO_ERROR) {
5500 ALOGW("Cannot open output stream for devices %s on hw module %s",
5501 supportedDevice->toString().c_str(), hwModule->getName());
5502 continue;
5503 }
5504 for (const auto &device : availProfileDevices) {
5505 // give a valid ID to an attached device once confirmed it is reachable
5506 if (!device->isAttached()) {
5507 device->attach(hwModule);
5508 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005509 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005510 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005511 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5512 }
5513 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005514 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005515 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5516 mPrimaryOutput = outputDesc;
5517 }
Eric Laurent39095982021-08-24 18:29:27 +02005518 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005519 outputDesc->close();
5520 } else {
5521 addOutput(output, outputDesc);
5522 setOutputDevices(outputDesc,
5523 DeviceVector(supportedDevice),
5524 true,
5525 0,
5526 NULL);
5527 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005528 }
5529 // open input streams needed to access attached devices to validate
5530 // mAvailableInputDevices list
5531 for (const auto& inProfile : hwModule->getInputProfiles()) {
5532 if (!inProfile->canOpenNewIo()) {
5533 ALOGE("Invalid Input profile max open count %u for profile %s",
5534 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5535 continue;
5536 }
5537 if (!inProfile->hasSupportedDevices()) {
5538 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5539 continue;
5540 }
5541 // chose first device present in profile's SupportedDevices also part of
5542 // available input devices
5543 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5544 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5545 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005546 ALOGV("%s: Input device list is empty! for profile %s",
5547 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005548 continue;
5549 }
5550 sp<AudioInputDescriptor> inputDesc =
5551 new AudioInputDescriptor(inProfile, mpClientInterface);
5552
5553 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5554 status_t status = inputDesc->open(nullptr,
5555 availProfileDevices.itemAt(0),
5556 AUDIO_SOURCE_MIC,
5557 AUDIO_INPUT_FLAG_NONE,
5558 &input);
5559 if (status != NO_ERROR) {
5560 ALOGW("Cannot open input stream for device %s on hw module %s",
5561 availProfileDevices.toString().c_str(),
5562 hwModule->getName());
5563 continue;
5564 }
5565 for (const auto &device : availProfileDevices) {
5566 // give a valid ID to an attached device once confirmed it is reachable
5567 if (!device->isAttached()) {
5568 device->attach(hwModule);
5569 device->importAudioPortAndPickAudioProfile(inProfile, true);
5570 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005571 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005572 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5573 }
5574 }
5575 inputDesc->close();
5576 }
5577 }
5578}
5579
Eric Laurent98e38192018-02-15 18:31:53 -08005580void AudioPolicyManager::addOutput(audio_io_handle_t output,
5581 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005582{
Eric Laurent1c333e22014-05-20 10:48:17 -07005583 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005584 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005585 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005586 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005587 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005588}
5589
François Gaffie53615e22015-03-19 09:24:12 +01005590void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5591{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005592 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5593 ALOGV("%s: removing primary output", __func__);
5594 mPrimaryOutput = nullptr;
5595 }
François Gaffie53615e22015-03-19 09:24:12 +01005596 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005597 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005598}
5599
Eric Laurent98e38192018-02-15 18:31:53 -08005600void AudioPolicyManager::addInput(audio_io_handle_t input,
5601 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005602{
Eric Laurent1c333e22014-05-20 10:48:17 -07005603 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005604 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005605}
Eric Laurente552edb2014-03-10 17:42:56 -07005606
François Gaffie11d30102018-11-02 16:09:09 +01005607status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005608 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005609 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005610{
François Gaffie11d30102018-11-02 16:09:09 +01005611 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005612 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005613 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005614
François Gaffie11d30102018-11-02 16:09:09 +01005615 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005616 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005617 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005618 }
Eric Laurente552edb2014-03-10 17:42:56 -07005619
Eric Laurent3b73df72014-03-11 09:06:29 -07005620 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005621 // first call getAudioPort to get the supported attributes from the HAL
5622 struct audio_port_v7 port = {};
5623 device->toAudioPort(&port);
5624 status_t status = mpClientInterface->getAudioPort(&port);
5625 if (status == NO_ERROR) {
5626 device->importAudioPort(port);
5627 }
5628
5629 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005630 for (size_t i = 0; i < mOutputs.size(); i++) {
5631 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005632 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005633 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005634 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5635 mOutputs.keyAt(i), device->toString().c_str());
5636 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005637 }
5638 }
5639 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005640 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005641 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005642 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5643 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005644 if (profile->supportsDevice(device)) {
5645 profiles.add(profile);
5646 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5647 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005648 }
5649 }
5650 }
5651
Eric Laurent7b279bb2015-12-14 10:18:23 -08005652 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005653
Eric Laurente552edb2014-03-10 17:42:56 -07005654 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005655 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005656 return BAD_VALUE;
5657 }
5658
5659 // open outputs for matching profiles if needed. Direct outputs are also opened to
5660 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5661 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005662 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005663
5664 // nothing to do if one output is already opened for this profile
5665 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005666 for (j = 0; j < outputs.size(); j++) {
5667 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005668 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005669 // matching profile: save the sample rates, format and channel masks supported
5670 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005671 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005672 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005673 }
Eric Laurente552edb2014-03-10 17:42:56 -07005674 break;
5675 }
5676 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005677 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005678 continue;
5679 }
5680
Eric Laurent3974e3b2017-12-07 17:58:43 -08005681 if (!profile->canOpenNewIo()) {
5682 ALOGW("Max Output number %u already opened for this profile %s",
5683 profile->maxOpenCount, profile->getTagName().c_str());
5684 continue;
5685 }
5686
Eric Laurent83efe1c2017-07-09 16:51:08 -07005687 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005688 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005689 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5690 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005691 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005692 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005693 profiles.removeAt(profile_index);
5694 profile_index--;
5695 } else {
5696 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005697 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005698 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005699 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5700 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005701 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005702 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005703
François Gaffie11d30102018-11-02 16:09:09 +01005704 if (device_distinguishes_on_address(deviceType)) {
5705 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5706 device->toString().c_str());
5707 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5708 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005709 }
Eric Laurente552edb2014-03-10 17:42:56 -07005710 ALOGV("checkOutputsForDevice(): adding output %d", output);
5711 }
5712 }
5713
5714 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005715 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005716 return BAD_VALUE;
5717 }
Eric Laurentd4692962014-05-05 18:13:44 -07005718 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005719 // check if one opened output is not needed any more after disconnecting one device
5720 for (size_t i = 0; i < mOutputs.size(); i++) {
5721 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005722 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005723 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005724 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005725 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005726 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005727 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005728 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5729 mOutputs.keyAt(i));
5730 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005731 }
Eric Laurente552edb2014-03-10 17:42:56 -07005732 }
5733 }
Eric Laurentd4692962014-05-05 18:13:44 -07005734 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005735 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005736 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5737 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005738 if (!profile->supportsDevice(device)) {
5739 continue;
5740 }
5741 ALOGV("checkOutputsForDevice(): "
5742 "clearing direct output profile %zu on module %s",
5743 j, hwModule->getName());
5744 profile->clearAudioProfiles();
5745 if (!profile->hasDynamicAudioProfile()) {
5746 continue;
5747 }
5748 // When a device is disconnected, if there is an IOProfile that contains dynamic
5749 // profiles and supports the disconnected device, call getAudioPort to repopulate
5750 // the capabilities of the devices that is supported by the IOProfile.
5751 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5752 if (supportedDevice == device ||
5753 !mAvailableOutputDevices.contains(supportedDevice)) {
5754 continue;
5755 }
5756 struct audio_port_v7 port;
5757 supportedDevice->toAudioPort(&port);
5758 status_t status = mpClientInterface->getAudioPort(&port);
5759 if (status == NO_ERROR) {
5760 supportedDevice->importAudioPort(port);
5761 }
Eric Laurente552edb2014-03-10 17:42:56 -07005762 }
5763 }
5764 }
5765 }
5766 return NO_ERROR;
5767}
5768
François Gaffie11d30102018-11-02 16:09:09 +01005769status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005770 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005771{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005772 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005773
François Gaffie11d30102018-11-02 16:09:09 +01005774 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005775 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005776 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005777 }
5778
Eric Laurentd4692962014-05-05 18:13:44 -07005779 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005780 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005781 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005782 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005783 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005784 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005785 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005786 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005787
François Gaffie11d30102018-11-02 16:09:09 +01005788 if (profile->supportsDevice(device)) {
5789 profiles.add(profile);
5790 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5791 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005792 }
5793 }
5794 }
5795
Eric Laurent0dd51852019-04-19 18:18:58 -07005796 if (profiles.isEmpty()) {
5797 ALOGW("%s: No input profile available for device %s",
5798 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005799 return BAD_VALUE;
5800 }
5801
5802 // open inputs for matching profiles if needed. Direct inputs are also opened to
5803 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5804 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5805
Eric Laurent1c333e22014-05-20 10:48:17 -07005806 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005807
Eric Laurentd4692962014-05-05 18:13:44 -07005808 // nothing to do if one input is already opened for this profile
5809 size_t input_index;
5810 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5811 desc = mInputs.valueAt(input_index);
5812 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005813 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005814 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005815 }
Eric Laurentd4692962014-05-05 18:13:44 -07005816 break;
5817 }
5818 }
5819 if (input_index != mInputs.size()) {
5820 continue;
5821 }
5822
Eric Laurent3974e3b2017-12-07 17:58:43 -08005823 if (!profile->canOpenNewIo()) {
5824 ALOGW("Max Input number %u already opened for this profile %s",
5825 profile->maxOpenCount, profile->getTagName().c_str());
5826 continue;
5827 }
5828
Eric Laurentfe231122017-11-17 17:48:06 -08005829 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005830 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005831 status_t status = desc->open(nullptr,
5832 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005833 AUDIO_SOURCE_MIC,
5834 AUDIO_INPUT_FLAG_NONE,
5835 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005836
Eric Laurentcf2c0212014-07-25 16:20:43 -07005837 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005838 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005839 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005840 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005841 mpClientInterface->setParameters(input, String8(param));
5842 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005843 }
François Gaffie11d30102018-11-02 16:09:09 +01005844 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005845 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005846 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005847 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005848 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005849 }
5850
Eric Laurent0dd51852019-04-19 18:18:58 -07005851 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005852 addInput(input, desc);
5853 }
5854 } // endif input != 0
5855
Eric Laurentcf2c0212014-07-25 16:20:43 -07005856 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08005857 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005858 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005859 profiles.removeAt(profile_index);
5860 profile_index--;
5861 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005862 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005863 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005864 }
Eric Laurentd4692962014-05-05 18:13:44 -07005865 ALOGV("checkInputsForDevice(): adding input %d", input);
5866 }
5867 } // end scan profiles
5868
5869 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005870 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005871 return BAD_VALUE;
5872 }
5873 } else {
5874 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005875 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005876 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005877 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005878 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005879 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005880 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005881 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005882 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5883 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005884 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005885 }
5886 }
5887 }
5888 } // end disconnect
5889
5890 return NO_ERROR;
5891}
5892
5893
Eric Laurente0720872014-03-11 09:30:41 -07005894void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005895{
5896 ALOGV("closeOutput(%d)", output);
5897
François Gaffie1c878552018-11-22 16:53:21 +01005898 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5899 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005900 ALOGW("closeOutput() unknown output %d", output);
5901 return;
5902 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005903 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005904 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005905
Eric Laurente552edb2014-03-10 17:42:56 -07005906 // look for duplicated outputs connected to the output being removed.
5907 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005908 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5909 if (dupOutput->isDuplicated() &&
5910 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5911 sp<SwAudioOutputDescriptor> remainingOutput =
5912 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005913 // As all active tracks on duplicated output will be deleted,
5914 // and as they were also referenced on the other output, the reference
5915 // count for their stream type must be adjusted accordingly on
5916 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005917 const bool wasActive = remainingOutput->isActive();
5918 // Note: no-op on the closing output where all clients has already been set inactive
5919 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005920 // stop() will be a no op if the output is still active but is needed in case all
5921 // active streams refcounts where cleared above
5922 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005923 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005924 }
Eric Laurente552edb2014-03-10 17:42:56 -07005925 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5926 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5927
5928 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005929 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005930 }
5931 }
5932
Eric Laurent05b90f82014-08-27 15:32:29 -07005933 nextAudioPortGeneration();
5934
François Gaffie1c878552018-11-22 16:53:21 +01005935 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005936 if (index >= 0) {
5937 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005938 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5939 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005940 mAudioPatches.removeItemsAt(index);
5941 mpClientInterface->onAudioPatchListUpdate();
5942 }
5943
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005944 if (closingOutputWasActive) {
5945 closingOutput->stop();
5946 }
François Gaffie1c878552018-11-22 16:53:21 +01005947 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005948
François Gaffie53615e22015-03-19 09:24:12 +01005949 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005950 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005951 if (closingOutput == mSpatializerOutput) {
5952 mSpatializerOutput.clear();
5953 }
Dean Wheatley3023b382018-08-09 07:42:40 +10005954
5955 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5956 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005957 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005958 bool directOutputOpen = false;
5959 for (size_t i = 0; i < mOutputs.size(); i++) {
5960 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5961 directOutputOpen = true;
5962 break;
5963 }
5964 }
5965 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005966 ALOGV("no direct outputs open, reset MSD patches");
5967 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5968 // how output devices for patching are resolved. Avoid by caching and reusing the
5969 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5970 // devices to patch to. This may be complicated by the fact that devices may become
5971 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005972 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005973 }
5974 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005975}
5976
5977void AudioPolicyManager::closeInput(audio_io_handle_t input)
5978{
5979 ALOGV("closeInput(%d)", input);
5980
5981 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5982 if (inputDesc == NULL) {
5983 ALOGW("closeInput() unknown input %d", input);
5984 return;
5985 }
5986
Eric Laurent6a94d692014-05-20 11:18:06 -07005987 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005988
François Gaffie11d30102018-11-02 16:09:09 +01005989 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005990 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005991 if (index >= 0) {
5992 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005993 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5994 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005995 mAudioPatches.removeItemsAt(index);
5996 mpClientInterface->onAudioPatchListUpdate();
5997 }
5998
Eric Laurentfe231122017-11-17 17:48:06 -08005999 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006000 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006001
François Gaffie11d30102018-11-02 16:09:09 +01006002 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6003 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006004 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006005 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006006 }
Eric Laurente552edb2014-03-10 17:42:56 -07006007}
6008
François Gaffie11d30102018-11-02 16:09:09 +01006009SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6010 const DeviceVector &devices,
6011 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006012{
6013 SortedVector<audio_io_handle_t> outputs;
6014
François Gaffie11d30102018-11-02 16:09:09 +01006015 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006016 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006017 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006018 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006019 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006020 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006021 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006022 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006023 outputs.add(openOutputs.keyAt(i));
6024 }
6025 }
6026 return outputs;
6027}
6028
Mikhail Naganov37977152018-07-11 15:54:44 -07006029void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6030{
6031 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6032 // output is suspended before any tracks are moved to it
6033 checkA2dpSuspend();
6034 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006035 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006036 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006037 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006038 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006039 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6040 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6041 // configuration changes will ultimately be rerouted correctly. We can still avoid
6042 // unnecessary rerouting by caching and reusing the arguments to
6043 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6044 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006045 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006046 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006047 // an event that changed routing likely occurred, inform upper layers
6048 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006049}
6050
François Gaffiec005e562018-11-06 15:04:49 +01006051bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6052 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006053{
François Gaffiec005e562018-11-06 15:04:49 +01006054 return mEngine->getProductStrategyForAttributes(lAttr) ==
6055 mEngine->getProductStrategyForAttributes(rAttr);
6056}
6057
Francois Gaffieff1eb522020-05-06 18:37:04 +02006058void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6059{
6060 for (size_t i = 0; i < mAudioSources.size(); i++) {
6061 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6062 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006063 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
6064 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006065 connectAudioSource(sourceDesc);
6066 }
6067 }
6068}
6069
6070void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6071{
6072 for (size_t i = 0; i < mAudioSources.size(); i++) {
6073 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6074 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6075 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6076 disconnectAudioSource(sourceDesc);
6077 }
6078 }
6079}
6080
François Gaffiec005e562018-11-06 15:04:49 +01006081void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6082{
6083 auto psId = mEngine->getProductStrategyForAttributes(attr);
6084
6085 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6086 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006087
François Gaffie11d30102018-11-02 16:09:09 +01006088 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6089 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006090
Eric Laurentc209fe42020-06-05 18:11:23 -07006091 uint32_t maxLatency = 0;
6092 bool invalidate = false;
6093 // take into account dynamic audio policies related changes: if a client is now associated
6094 // to a different policy mix than at creation time, invalidate corresponding stream
6095 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6096 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6097 if (desc->isDuplicated()) {
6098 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006099 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006100 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6101 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6102 continue;
6103 }
6104 sp<AudioPolicyMix> primaryMix;
6105 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
6106 client->flags(), primaryMix, nullptr);
6107 if (status != OK) {
6108 continue;
6109 }
yucliuf4de36d2020-09-14 14:57:56 -07006110 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006111 invalidate = true;
6112 if (desc->isStrategyActive(psId)) {
6113 maxLatency = desc->latency();
6114 }
6115 break;
6116 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006117 }
6118 }
6119
Eric Laurentc209fe42020-06-05 18:11:23 -07006120 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006121 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6122 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006123 for (audio_io_handle_t srcOut : srcOutputs) {
6124 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006125 if (desc == nullptr) continue;
6126
6127 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006128 maxLatency = desc->latency();
6129 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006130
6131 if (invalidate) continue;
6132
6133 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006134 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006135 // a client on a non direct outputs has necessarily a linear PCM format
6136 // so we can call selectOutput() safely
6137 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6138 client->flags(),
6139 client->config().format,
6140 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006141 client->config().sample_rate,
6142 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006143 if (newOutput != srcOut) {
6144 invalidate = true;
6145 break;
6146 }
6147 } else {
6148 sp<IOProfile> profile = getProfileForOutput(newDevices,
6149 client->config().sample_rate,
6150 client->config().format,
6151 client->config().channel_mask,
6152 client->flags(),
6153 true /* directOnly */);
6154 if (profile != desc->mProfile) {
6155 invalidate = true;
6156 break;
6157 }
6158 }
6159 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006160 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006161
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006162 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006163 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006164 std::to_string(srcOutputs[0]).c_str(),
6165 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006166 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006167 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006168 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006169 if (desc == nullptr) continue;
6170
6171 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006172 setStrategyMute(psId, true, desc);
6173 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006174 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006175 }
François Gaffiec005e562018-11-06 15:04:49 +01006176 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006177 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006178 connectAudioSource(source);
6179 }
Eric Laurente552edb2014-03-10 17:42:56 -07006180 }
6181
François Gaffiec005e562018-11-06 15:04:49 +01006182 // Move effects associated to this stream from previous output to new output
6183 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006184 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006185 }
François Gaffiec005e562018-11-06 15:04:49 +01006186 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006187 if (invalidate) {
6188 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6189 mpClientInterface->invalidateStream(stream);
6190 }
jiabin49256852022-03-09 11:21:35 -08006191 for (audio_io_handle_t srcOut : srcOutputs) {
6192 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6193 if (desc == nullptr) continue;
6194
6195 desc->setTracksInvalidatedStatusByStrategy(psId);
6196 }
Eric Laurente552edb2014-03-10 17:42:56 -07006197 }
6198 }
6199}
6200
Eric Laurente0720872014-03-11 09:30:41 -07006201void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006202{
François Gaffiec005e562018-11-06 15:04:49 +01006203 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6204 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6205 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006206 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006207 }
Eric Laurente552edb2014-03-10 17:42:56 -07006208}
6209
Kevin Rocard153f92d2018-12-18 18:33:28 -08006210void AudioPolicyManager::checkSecondaryOutputs() {
6211 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006212 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006213 for (size_t i = 0; i < mOutputs.size(); i++) {
6214 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6215 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006216 sp<AudioPolicyMix> primaryMix;
6217 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006218 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006219 client->flags(), primaryMix, &secondaryMixes);
6220 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6221 for (auto &secondaryMix : secondaryMixes) {
6222 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6223 if (outputDesc != nullptr &&
6224 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6225 secondaryDescs.push_back(outputDesc);
6226 }
6227 }
6228
jiabin10a03f12021-05-07 23:46:28 +00006229 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006230 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006231 } else if (!std::equal(
6232 client->getSecondaryOutputs().begin(),
6233 client->getSecondaryOutputs().end(),
6234 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006235 if (!audio_is_linear_pcm(client->config().format)) {
6236 // If the format is not PCM, the tracks should be invalidated to get correct
6237 // behavior when the secondary output is changed.
6238 streamsToInvalidate.insert(client->stream());
6239 } else {
6240 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6241 std::vector<audio_io_handle_t> secondaryOutputIds;
6242 for (const auto &secondaryDesc: secondaryDescs) {
6243 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6244 weakSecondaryDescs.push_back(secondaryDesc);
6245 }
6246 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6247 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006248 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006249 }
6250 }
6251 }
jiabin10a03f12021-05-07 23:46:28 +00006252 if (!trackSecondaryOutputs.empty()) {
6253 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6254 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006255 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006256 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006257 mpClientInterface->invalidateStream(stream);
6258 }
6259}
6260
Eric Laurent2517af32020-11-25 15:31:27 +01006261bool AudioPolicyManager::isScoRequestedForComm() const {
6262 AudioDeviceTypeAddrVector devices;
6263 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6264 for (const auto &device : devices) {
6265 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6266 return true;
6267 }
6268 }
6269 return false;
6270}
6271
Eric Laurente0720872014-03-11 09:30:41 -07006272void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006273{
François Gaffie53615e22015-03-19 09:24:12 +01006274 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006275 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006276 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006277 return;
6278 }
6279
Eric Laurent3a4311c2014-03-17 12:00:47 -07006280 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006281 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6282 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006283 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006284
6285 // if suspended, restore A2DP output if:
6286 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006287 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006288 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006289 //
Eric Laurentf732e072016-08-03 19:30:28 -07006290 // if not suspended, suspend A2DP output if:
6291 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006292 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006293 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006294 //
6295 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006296 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006297 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006298 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006299 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006300
6301 mpClientInterface->restoreOutput(a2dpOutput);
6302 mA2dpSuspended = false;
6303 }
6304 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006305 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006306 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006307 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006308 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006309
6310 mpClientInterface->suspendOutput(a2dpOutput);
6311 mA2dpSuspended = true;
6312 }
6313 }
6314}
6315
François Gaffie11d30102018-11-02 16:09:09 +01006316DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6317 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006318{
François Gaffie11d30102018-11-02 16:09:09 +01006319 DeviceVector devices;
6320
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006321 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006322 if (index >= 0) {
6323 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006324 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006325 ALOGV("%s device %s forced by patch %d", __func__,
6326 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6327 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006328 }
6329 }
6330
Dean Wheatley514b4312020-06-17 21:45:00 +10006331 // Do not retrieve engine device for outputs through MSD
6332 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6333 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6334 return outputDesc->devices();
6335 }
6336
Eric Laurent97ac8712018-07-27 18:59:02 -07006337 // Honor explicit routing requests only if no client using default routing is active on this
6338 // input: a specific app can not force routing for other apps by setting a preferred device.
6339 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006340 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006341 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006342 if (device != nullptr) {
6343 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006344 }
6345
François Gaffiea807ef92018-11-05 10:44:33 +01006346 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6347 // of setForceUse / Default Bus device here
6348 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6349 if (device != nullptr) {
6350 return DeviceVector(device);
6351 }
6352
François Gaffiec005e562018-11-06 15:04:49 +01006353 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6354 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6355 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306356 auto hasStreamActive = [&](auto stream) {
6357 return hasStream(streams, stream) && isStreamActive(stream, 0);
6358 };
Eric Laurent484e9272018-06-07 17:29:23 -07006359
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306360 auto doGetOutputDevicesForVoice = [&]() {
6361 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006362 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306363 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006364 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6365 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306366 };
6367
6368 // With low-latency playing on speaker, music on WFD, when the first low-latency
6369 // output is stopped, getNewOutputDevices checks for a product strategy
6370 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006371 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306372 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6373 // stream is associated to the output descriptor.
6374 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6375 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6376 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6377 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006378 // Retrieval of devices for voice DL is done on primary output profile, cannot
6379 // check the route (would force modifying configuration file for this profile)
6380 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6381 break;
6382 }
Eric Laurente552edb2014-03-10 17:42:56 -07006383 }
François Gaffiec005e562018-11-06 15:04:49 +01006384 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006385 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006386}
6387
François Gaffie11d30102018-11-02 16:09:09 +01006388sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6389 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006390{
François Gaffie11d30102018-11-02 16:09:09 +01006391 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006392
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006393 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006394 if (index >= 0) {
6395 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006396 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006397 ALOGV("getNewInputDevice() device %s forced by patch %d",
6398 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6399 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006400 }
6401 }
6402
Eric Laurent97ac8712018-07-27 18:59:02 -07006403 // Honor explicit routing requests only if no client using default routing is active on this
6404 // input: a specific app can not force routing for other apps by setting a preferred device.
6405 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006406 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6407 if (device != nullptr) {
6408 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006409 }
6410
Eric Laurentdc95a252018-04-12 12:46:56 -07006411 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006412 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006413 audio_attributes_t attributes;
6414 uid_t uid;
6415 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6416 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006417 attributes = topClient->attributes();
6418 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006419 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006420 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6421 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006422 }
6423
Francois Gaffie716e1432019-01-14 16:58:59 +01006424 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6425 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006426 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006427 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006428 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006429 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006430
Eric Laurente552edb2014-03-10 17:42:56 -07006431 return device;
6432}
6433
Eric Laurent794fde22016-03-11 09:50:45 -08006434bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6435 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006436 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006437}
6438
Dorin Drimusf2196d82022-01-03 12:11:18 +01006439// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006440status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006441 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006442 if (devices == nullptr) {
6443 return BAD_VALUE;
6444 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006445
6446 // Devices are determined in the following precedence:
6447 //
6448 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6449 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6450 //
6451 // If no such dynamic policy then
6452 // 2) Devices containing an active client using setPreferredDevice
6453 // with same strategy as the attributes.
6454 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6455 //
6456 // If no corresponding active client with setPreferredDevice then
6457 // 3) Devices associated with the strategy determined by the attributes
6458 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6459 //
6460 // See related getOutputForAttrInt().
6461
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006462 // check dynamic policies but only for primary descriptors (secondary not used for audible
6463 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006464 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006465 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Andy Hung6d23c0f2022-02-16 09:37:15 -08006466 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr /* secondaryMixes */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006467 if (status != OK) {
6468 return status;
6469 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006470
6471 DeviceVector curDevices;
6472 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6473 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6474 // as they are unaffected by device/stream volume
6475 // (per SwAudioOutputDescriptor::isFixedVolume()).
6476 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6477 ) {
6478 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6479 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6480 curDevices.add(deviceDesc);
6481 } else {
6482 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6483 // which selects setPreferredDevice if active. This means forVolume call
6484 // will take an active setPreferredDevice, if such exists.
6485
6486 curDevices = mEngine->getOutputDevicesForAttributes(
6487 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006488 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006489
6490 if (forVolume) {
6491 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6492 // for single volume control in AudioService (such relationship should exist if
6493 // SPEAKER_SAFE is present).
6494 //
6495 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6496 DeviceVector speakerSafeDevices =
6497 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6498 if (!speakerSafeDevices.isEmpty()) {
6499 curDevices.merge(
6500 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6501 curDevices.remove(speakerSafeDevices);
6502 }
6503 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006504 for (const auto& device : curDevices) {
6505 devices->push_back(device->getDeviceTypeAddr());
6506 }
6507 return NO_ERROR;
6508}
6509
Eric Laurente0720872014-03-11 09:30:41 -07006510void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006511 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006512 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006513 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006514 updateDevicesAndOutputs();
6515 break;
6516 default:
6517 break;
6518 }
6519}
6520
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006521uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006522
6523 // skip beacon mute management if a dedicated TTS output is available
6524 if (mTtsOutputAvailable) {
6525 return 0;
6526 }
6527
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006528 switch(event) {
6529 case STARTING_OUTPUT:
6530 mBeaconMuteRefCount++;
6531 break;
6532 case STOPPING_OUTPUT:
6533 if (mBeaconMuteRefCount > 0) {
6534 mBeaconMuteRefCount--;
6535 }
6536 break;
6537 case STARTING_BEACON:
6538 mBeaconPlayingRefCount++;
6539 break;
6540 case STOPPING_BEACON:
6541 if (mBeaconPlayingRefCount > 0) {
6542 mBeaconPlayingRefCount--;
6543 }
6544 break;
6545 }
6546
6547 if (mBeaconMuteRefCount > 0) {
6548 // any playback causes beacon to be muted
6549 return setBeaconMute(true);
6550 } else {
6551 // no other playback: unmute when beacon starts playing, mute when it stops
6552 return setBeaconMute(mBeaconPlayingRefCount == 0);
6553 }
6554}
6555
6556uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6557 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6558 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6559 // keep track of muted state to avoid repeating mute/unmute operations
6560 if (mBeaconMuted != mute) {
6561 // mute/unmute AUDIO_STREAM_TTS on all outputs
6562 ALOGV("\t muting %d", mute);
6563 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006564 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6565 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6566 ALOGV("\t no tts volume source available");
6567 return 0;
6568 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006569 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006570 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006571 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006572 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006573 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006574 maxLatency = latency;
6575 }
6576 }
6577 mBeaconMuted = mute;
6578 return maxLatency;
6579 }
6580 return 0;
6581}
6582
Eric Laurente0720872014-03-11 09:30:41 -07006583void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006584{
François Gaffiec005e562018-11-06 15:04:49 +01006585 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006586 mPreviousOutputs = mOutputs;
6587}
6588
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006589uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006590 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006591 uint32_t delayMs)
6592{
6593 // mute/unmute strategies using an incompatible device combination
6594 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6595 // if unmuting, unmute only after the specified delay
6596 if (outputDesc->isDuplicated()) {
6597 return 0;
6598 }
6599
6600 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006601 DeviceVector devices = outputDesc->devices();
6602 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006603
François Gaffiec005e562018-11-06 15:04:49 +01006604 auto productStrategies = mEngine->getOrderedProductStrategies();
6605 for (const auto &productStrategy : productStrategies) {
6606 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6607 DeviceVector curDevices =
6608 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6609 curDevices = curDevices.filter(outputDesc->supportedDevices());
6610 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006611 bool doMute = false;
6612
François Gaffiec005e562018-11-06 15:04:49 +01006613 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006614 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006615 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6616 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006617 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006618 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006619 }
Eric Laurent99401132014-05-07 19:48:15 -07006620 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006621 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006622 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006623 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006624 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006625 continue;
6626 }
François Gaffiec005e562018-11-06 15:04:49 +01006627 ALOGVV("%s() %s (curDevice %s)", __func__,
6628 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6629 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6630 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006631 if (mute) {
6632 // FIXME: should not need to double latency if volume could be applied
6633 // immediately by the audioflinger mixer. We must account for the delay
6634 // between now and the next time the audioflinger thread for this output
6635 // will process a buffer (which corresponds to one buffer size,
6636 // usually 1/2 or 1/4 of the latency).
6637 if (muteWaitMs < desc->latency() * 2) {
6638 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006639 }
6640 }
6641 }
6642 }
6643 }
6644 }
6645
Eric Laurent99401132014-05-07 19:48:15 -07006646 // temporary mute output if device selection changes to avoid volume bursts due to
6647 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006648 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006649 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006650
Eric Laurentdc462862016-07-19 12:29:53 -07006651 if (muteWaitMs < tempMuteWaitMs) {
6652 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006653 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006654
6655 // If recommended duration is defined, replace temporary mute duration to avoid
6656 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6657 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6658 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6659 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6660 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6661
François Gaffieaaac0fd2018-11-22 17:56:39 +01006662 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6663 // make sure that we do not start the temporary mute period too early in case of
6664 // delayed device change
6665 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6666 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006667 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006668 }
6669 }
6670
Eric Laurente552edb2014-03-10 17:42:56 -07006671 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6672 if (muteWaitMs > delayMs) {
6673 muteWaitMs -= delayMs;
6674 usleep(muteWaitMs * 1000);
6675 return muteWaitMs;
6676 }
6677 return 0;
6678}
6679
François Gaffie11d30102018-11-02 16:09:09 +01006680uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6681 const DeviceVector &devices,
6682 bool force,
6683 int delayMs,
6684 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006685 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006686{
François Gaffie11d30102018-11-02 16:09:09 +01006687 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006688 uint32_t muteWaitMs;
6689
6690 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006691 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6692 nullptr /* patchHandle */, requiresMuteCheck);
6693 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6694 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006695 return muteWaitMs;
6696 }
Eric Laurente552edb2014-03-10 17:42:56 -07006697
6698 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006699 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006700 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006701 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006702
François Gaffie11d30102018-11-02 16:09:09 +01006703 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6704
6705 if (!filteredDevices.isEmpty()) {
6706 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006707 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006708
6709 // if the outputs are not materially active, there is no need to mute.
6710 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006711 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006712 } else {
6713 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6714 muteWaitMs = 0;
6715 }
Eric Laurente552edb2014-03-10 17:42:56 -07006716
Eric Laurent79ea9582020-06-11 18:49:24 -07006717 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6718 // output profile or if new device is not supported AND previous device(s) is(are) still
6719 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006720 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006721 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6722 // restore previous device after evaluating strategy mute state
6723 outputDesc->setDevices(prevDevices);
6724 return muteWaitMs;
6725 }
6726
Eric Laurente552edb2014-03-10 17:42:56 -07006727 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006728 // the requested device is AUDIO_DEVICE_NONE
6729 // OR the requested device is the same as current device
6730 // AND force is not specified
6731 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006732 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006733 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
Francois Gaffie3523ab32021-06-22 13:24:34 +02006734 !force && outputDesc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006735 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6736 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006737 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6738 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6739 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6740 }
Eric Laurente552edb2014-03-10 17:42:56 -07006741 return muteWaitMs;
6742 }
6743
François Gaffie11d30102018-11-02 16:09:09 +01006744 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006745
Eric Laurente552edb2014-03-10 17:42:56 -07006746 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006747 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006748 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006749 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006750 PatchBuilder patchBuilder;
6751 patchBuilder.addSource(outputDesc);
6752 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6753 for (const auto &filteredDevice : filteredDevices) {
6754 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006755 }
6756
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006757 // Add half reported latency to delayMs when muteWaitMs is null in order
6758 // to avoid disordered sequence of muting volume and changing devices.
6759 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6760 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006761 }
Eric Laurente552edb2014-03-10 17:42:56 -07006762
6763 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006764 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006765
6766 return muteWaitMs;
6767}
6768
Eric Laurentc75307b2015-03-17 15:29:32 -07006769status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006770 int delayMs,
6771 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006772{
Eric Laurent6a94d692014-05-20 11:18:06 -07006773 ssize_t index;
6774 if (patchHandle) {
6775 index = mAudioPatches.indexOfKey(*patchHandle);
6776 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006777 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006778 }
6779 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006780 return INVALID_OPERATION;
6781 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006782 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006783 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006784 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006785 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006786 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006787 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006788 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006789 return status;
6790}
6791
6792status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006793 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006794 bool force,
6795 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006796{
6797 status_t status = NO_ERROR;
6798
Eric Laurent1f2f2232014-06-02 12:01:23 -07006799 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006800 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6801 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006802
François Gaffie11d30102018-11-02 16:09:09 +01006803 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006804 PatchBuilder patchBuilder;
6805 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006806 // AUDIO_SOURCE_HOTWORD is for internal use only:
6807 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006808 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6809 auto result = usecase;
6810 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6811 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6812 }
6813 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006814 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006815 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006816 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006817 }
6818 }
6819 return status;
6820}
6821
Eric Laurent6a94d692014-05-20 11:18:06 -07006822status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6823 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006824{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006825 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006826 ssize_t index;
6827 if (patchHandle) {
6828 index = mAudioPatches.indexOfKey(*patchHandle);
6829 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006830 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006831 }
6832 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006833 return INVALID_OPERATION;
6834 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006835 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006836 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006837 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006838 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006839 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006840 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006841 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006842 return status;
6843}
6844
François Gaffie11d30102018-11-02 16:09:09 +01006845sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006846 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006847 audio_format_t& format,
6848 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006849 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006850{
6851 // Choose an input profile based on the requested capture parameters: select the first available
6852 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006853 //
6854 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6855 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006856
Glenn Kasten730b9262018-03-29 15:01:26 -07006857 sp<IOProfile> firstInexact;
6858 uint32_t updatedSamplingRate = 0;
6859 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6860 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006861 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006862 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006863 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006864 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006865 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006866 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006867 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006868 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006869 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006870 &channelMask /*updatedChannelMask*/,
6871 // FIXME ugly cast
6872 (audio_output_flags_t) flags,
6873 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006874 return profile;
6875 }
François Gaffie11d30102018-11-02 16:09:09 +01006876 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006877 samplingRate,
6878 &updatedSamplingRate,
6879 format,
6880 &updatedFormat,
6881 channelMask,
6882 &updatedChannelMask,
6883 // FIXME ugly cast
6884 (audio_output_flags_t) flags,
6885 false /*exactMatchRequiredForInputFlags*/)) {
6886 firstInexact = profile;
6887 }
6888
Eric Laurente552edb2014-03-10 17:42:56 -07006889 }
6890 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006891 if (firstInexact != nullptr) {
6892 samplingRate = updatedSamplingRate;
6893 format = updatedFormat;
6894 channelMask = updatedChannelMask;
6895 return firstInexact;
6896 }
Eric Laurente552edb2014-03-10 17:42:56 -07006897 return NULL;
6898}
6899
François Gaffieaaac0fd2018-11-22 17:56:39 +01006900float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6901 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006902 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006903 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006904{
jiabin9a3361e2019-10-01 09:38:30 -07006905 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006906
6907 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6908 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6909 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6910 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006911 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
6912 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
6913 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
6914 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
6915 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006916
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006917 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006918 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6919 mOutputs.isActive(ringVolumeSrc, 0)) {
6920 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006921 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006922 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006923 }
6924
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006925 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006926 if ((volumeSource != callVolumeSrc && (isInCall() ||
6927 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006928 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006929 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6930 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006931 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
6932 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
6933 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006934 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006935 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006936 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006937 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006938 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006939 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006940 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6941 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6942 // programmatically muted.
6943 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6944 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6945 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006946 bool exemptFromCapping =
6947 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6948 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006949 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6950 volumeSource, volumeDb);
6951 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006952 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6953 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6954 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006955 }
6956 }
Eric Laurente552edb2014-03-10 17:42:56 -07006957 // if a headset is connected, apply the following rules to ring tones and notifications
6958 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006959 // - always attenuate notifications volume by 6dB
6960 // - attenuate ring tones volume by 6dB unless music is not playing and
6961 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006962 // - if music is playing, always limit the volume to current music volume,
6963 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006964 if (!Intersection(deviceTypes,
6965 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6966 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006967 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6968 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006969 ((volumeSource == alarmVolumeSrc ||
6970 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006971 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
6972 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
6973 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006974 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6975 curves.canBeMuted()) {
6976
Eric Laurente552edb2014-03-10 17:42:56 -07006977 // when the phone is ringing we must consider that music could have been paused just before
6978 // by the music application and behave as if music was active if the last music track was
6979 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006980 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006981 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006982 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006983 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006984 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6985 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006986 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006987 float musicVolDb = computeVolume(musicCurves,
6988 musicVolumeSrc,
6989 musicCurves.getVolumeIndex(musicDevice),
6990 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006991 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6992 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6993 if (volumeDb > minVolDb) {
6994 volumeDb = minVolDb;
6995 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006996 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006997 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6998 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6999 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007000 // on A2DP, also ensure notification volume is not too low compared to media when
7001 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007002 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007003 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007004 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7005 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007006 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7007 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007008 }
7009 }
jiabin9a3361e2019-10-01 09:38:30 -07007010 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007011 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007012 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007013 }
7014 }
7015
François Gaffie43c73442018-11-08 08:21:55 +01007016 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007017}
7018
Eric Laurent3839bc02018-07-10 18:33:34 -07007019int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007020 VolumeSource fromVolumeSource,
7021 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007022{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007023 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007024 return srcIndex;
7025 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007026 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7027 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007028 float minSrc = (float)srcCurves.getVolumeIndexMin();
7029 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7030 float minDst = (float)dstCurves.getVolumeIndexMin();
7031 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007032
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007033 // preserve mute request or correct range
7034 if (srcIndex < minSrc) {
7035 if (srcIndex == 0) {
7036 return 0;
7037 }
7038 srcIndex = minSrc;
7039 } else if (srcIndex > maxSrc) {
7040 srcIndex = maxSrc;
7041 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007042 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7043}
7044
François Gaffieaaac0fd2018-11-22 17:56:39 +01007045status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7046 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007047 int index,
7048 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007049 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007050 int delayMs,
7051 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007052{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007053 // do not change actual attributes volume if the attributes is muted
7054 if (outputDesc->isMuted(volumeSource)) {
7055 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7056 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007057 return NO_ERROR;
7058 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007059 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7060 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7061 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7062 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007063
Eric Laurent2517af32020-11-25 15:31:27 +01007064 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07007065 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007066 // if sco and call follow same curves, bypass forceUseForComm
7067 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007068 ((isVoiceVolSrc && isScoRequested) ||
7069 (isBtScoVolSrc && !isScoRequested))) {
7070 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
7071 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07007072 // Do not return an error here as AudioService will always set both voice call
7073 // and bluetooth SCO volumes due to stream aliasing.
7074 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007075 }
jiabin9a3361e2019-10-01 09:38:30 -07007076 if (deviceTypes.empty()) {
7077 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007078 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007079
jiabin9a3361e2019-10-01 09:38:30 -07007080 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7081 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007082 // Force VoIP volume to max for bluetooth SCO device except if muted
7083 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007084 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007085 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007086 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007087 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007088 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007089 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007090
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007091 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007092 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007093 // 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 +01007094 if (isVoiceVolSrc) {
7095 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007096 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007097 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007098 }
Eric Laurent18fba842016-03-31 14:41:26 -07007099 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007100 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7101 mLastVoiceVolume = voiceVolume;
7102 }
7103 }
Eric Laurente552edb2014-03-10 17:42:56 -07007104 return NO_ERROR;
7105}
7106
Eric Laurentc75307b2015-03-17 15:29:32 -07007107void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007108 const DeviceTypeSet& deviceTypes,
7109 int delayMs,
7110 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007111{
jiabincd510522020-01-22 09:40:55 -08007112 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007113 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7114 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7115 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007116 curves.getVolumeIndex(deviceTypes),
7117 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007118 }
7119}
7120
François Gaffiec005e562018-11-06 15:04:49 +01007121void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7122 bool on,
7123 const sp<AudioOutputDescriptor>& outputDesc,
7124 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007125 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007126{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007127 std::vector<VolumeSource> sourcesToMute;
7128 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7129 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7130 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007131 VolumeSource source = toVolumeSource(attributes, false);
7132 if ((source != VOLUME_SOURCE_NONE) &&
7133 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7134 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007135 sourcesToMute.push_back(source);
7136 }
Eric Laurente552edb2014-03-10 17:42:56 -07007137 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007138 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007139 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007140 }
7141
Eric Laurente552edb2014-03-10 17:42:56 -07007142}
7143
François Gaffieaaac0fd2018-11-22 17:56:39 +01007144void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7145 bool on,
7146 const sp<AudioOutputDescriptor>& outputDesc,
7147 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007148 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007149{
jiabin9a3361e2019-10-01 09:38:30 -07007150 if (deviceTypes.empty()) {
7151 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007152 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007153 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007154 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007155 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007156 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007157 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007158 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7159 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007160 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007161 }
7162 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007163 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7164 // ignored
7165 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007166 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007167 if (!outputDesc->isMuted(volumeSource)) {
7168 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007169 return;
7170 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007171 if (outputDesc->decMuteCount(volumeSource) == 0) {
7172 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007173 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007174 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007175 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007176 delayMs);
7177 }
7178 }
7179}
7180
François Gaffie53615e22015-03-19 09:24:12 +01007181bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7182{
François Gaffiec005e562018-11-06 15:04:49 +01007183 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007184 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7185 return true;
7186 }
7187
7188 // has known usage?
7189 switch (paa->usage) {
7190 case AUDIO_USAGE_UNKNOWN:
7191 case AUDIO_USAGE_MEDIA:
7192 case AUDIO_USAGE_VOICE_COMMUNICATION:
7193 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7194 case AUDIO_USAGE_ALARM:
7195 case AUDIO_USAGE_NOTIFICATION:
7196 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7197 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7198 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7199 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7200 case AUDIO_USAGE_NOTIFICATION_EVENT:
7201 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7202 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7203 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7204 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007205 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007206 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007207 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007208 case AUDIO_USAGE_EMERGENCY:
7209 case AUDIO_USAGE_SAFETY:
7210 case AUDIO_USAGE_VEHICLE_STATUS:
7211 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007212 break;
7213 default:
7214 return false;
7215 }
7216 return true;
7217}
7218
François Gaffie2110e042015-03-24 08:41:51 +01007219audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7220{
7221 return mEngine->getForceUse(usage);
7222}
7223
7224bool AudioPolicyManager::isInCall()
7225{
7226 return isStateInCall(mEngine->getPhoneState());
7227}
7228
7229bool AudioPolicyManager::isStateInCall(int state)
7230{
7231 return is_state_in_call(state);
7232}
7233
Eric Laurent74b71512019-11-06 17:21:57 -08007234bool AudioPolicyManager::isCallAudioAccessible()
7235{
7236 audio_mode_t mode = mEngine->getPhoneState();
7237 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007238 || (mode == AUDIO_MODE_CALL_SCREEN)
7239 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007240}
7241
Eric Laurentd60560a2015-04-10 11:31:20 -07007242void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7243{
7244 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007245 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007246 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007247 sourceDesc->sinkDevice()->equals(deviceDesc))
7248 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007249 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007250 }
7251 }
7252
7253 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7254 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7255 bool release = false;
7256 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7257 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7258 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7259 source->ext.device.type == deviceDesc->type()) {
7260 release = true;
7261 }
7262 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007263 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007264 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7265 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7266 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007267 sink->ext.device.type == deviceDesc->type() &&
7268 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7269 || strncmp(sink->ext.device.address, address,
7270 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007271 release = true;
7272 }
7273 }
7274 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007275 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7276 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007277 }
7278 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007279
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007280 mInputs.clearSessionRoutesForDevice(deviceDesc);
7281
Francois Gaffie716e1432019-01-14 16:58:59 +01007282 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007283}
7284
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007285void AudioPolicyManager::modifySurroundFormats(
7286 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007287 std::unordered_set<audio_format_t> enforcedSurround(
7288 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007289 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7290 for (const auto& pair : mConfig.getSurroundFormats()) {
7291 allSurround.insert(pair.first);
7292 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7293 }
Phil Burk09bc4612016-02-24 15:58:15 -08007294
7295 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7296 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007297 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007298 // This is the resulting set of formats depending on the surround mode:
7299 // 'all surround' = allSurround
7300 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7301 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7302 // 'manual surround' = mManualSurroundFormats
7303 // AUTO: formats v 'enforced surround'
7304 // ALWAYS: formats v 'all surround' v 'enforced surround'
7305 // NEVER: formats ^ 'non-surround'
7306 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007307
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007308 std::unordered_set<audio_format_t> formatSet;
7309 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7310 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007311 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007312 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007313 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007314 formatSet.insert(*formatIter);
7315 }
7316 }
7317 } else {
7318 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7319 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007320 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007321
jiabin81772902018-04-02 17:52:27 -07007322 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007323 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007324 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7325 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7326 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007327 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007328 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7329 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7330 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007331 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007332 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007333 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007334 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007335 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007336 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007337}
7338
jiabin06e4bab2019-07-29 10:13:34 -07007339void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7340 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007341 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7342 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7343
7344 // If NEVER, then remove support for channelMasks > stereo.
7345 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007346 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7347 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007348 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007349 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007350 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007351 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007352 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007353 }
7354 }
jiabin81772902018-04-02 17:52:27 -07007355 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7356 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7357 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007358 bool supports5dot1 = false;
7359 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007360 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007361 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7362 supports5dot1 = true;
7363 break;
7364 }
7365 }
7366 // If not then add 5.1 support.
7367 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007368 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007369 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007370 }
Phil Burk09bc4612016-02-24 15:58:15 -08007371 }
7372}
7373
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007374void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007375 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007376 AudioProfileVector &profiles)
7377{
7378 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007379 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007380
François Gaffie112b0af2015-11-19 16:13:25 +01007381 // Format MUST be checked first to update the list of AudioProfile
7382 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007383 reply = mpClientInterface->getParameters(
7384 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007385 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007386 AudioParameter repliedParameters(reply);
7387 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007388 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007389 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7390 return;
7391 }
Phil Burk09bc4612016-02-24 15:58:15 -08007392 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007393 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007394 if (device == AUDIO_DEVICE_OUT_HDMI
7395 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007396 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007397 }
jiabin3e277cc2019-09-10 14:27:34 -07007398 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007399 }
François Gaffie112b0af2015-11-19 16:13:25 +01007400
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007401 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007402 ChannelMaskSet channelMasks;
7403 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007404 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007405 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007406
7407 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007408 reply = mpClientInterface->getParameters(
7409 ioHandle,
7410 requestedParameters.toString() + ";" +
7411 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007412 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007413 AudioParameter repliedParameters(reply);
7414 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007415 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007416 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007417 }
7418 }
7419 if (profiles.hasDynamicChannelsFor(format)) {
7420 reply = mpClientInterface->getParameters(ioHandle,
7421 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007422 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007423 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007424 AudioParameter repliedParameters(reply);
7425 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007426 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007427 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007428 if (device == AUDIO_DEVICE_OUT_HDMI
7429 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007430 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007431 }
François Gaffie112b0af2015-11-19 16:13:25 +01007432 }
7433 }
jiabin3e277cc2019-09-10 14:27:34 -07007434 addDynamicAudioProfileAndSort(
7435 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007436 }
7437}
Eric Laurentd60560a2015-04-10 11:31:20 -07007438
Mikhail Naganovdc769682018-05-04 15:34:08 -07007439status_t AudioPolicyManager::installPatch(const char *caller,
7440 audio_patch_handle_t *patchHandle,
7441 AudioIODescriptorInterface *ioDescriptor,
7442 const struct audio_patch *patch,
7443 int delayMs)
7444{
7445 ssize_t index = mAudioPatches.indexOfKey(
7446 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7447 *patchHandle : ioDescriptor->getPatchHandle());
7448 sp<AudioPatch> patchDesc;
7449 status_t status = installPatch(
7450 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7451 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007452 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007453 }
7454 return status;
7455}
7456
7457status_t AudioPolicyManager::installPatch(const char *caller,
7458 ssize_t index,
7459 audio_patch_handle_t *patchHandle,
7460 const struct audio_patch *patch,
7461 int delayMs,
7462 uid_t uid,
7463 sp<AudioPatch> *patchDescPtr)
7464{
7465 sp<AudioPatch> patchDesc;
7466 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7467 if (index >= 0) {
7468 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007469 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007470 }
7471
7472 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7473 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7474 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7475 if (status == NO_ERROR) {
7476 if (index < 0) {
7477 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007478 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007479 } else {
7480 patchDesc->mPatch = *patch;
7481 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007482 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007483 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007484 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007485 }
7486 nextAudioPortGeneration();
7487 mpClientInterface->onAudioPatchListUpdate();
7488 }
7489 if (patchDescPtr) *patchDescPtr = patchDesc;
7490 return status;
7491}
7492
jiabinbce0c1d2020-10-05 11:20:18 -07007493bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7494{
7495 const TrackClientVector activeClients = output->getActiveClients();
7496 if (activeClients.empty()) {
7497 return true;
7498 }
7499 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7500 if (index < 0) {
7501 ALOGE("%s, no audio patch found while there are active clients on output %d",
7502 __func__, output->getId());
7503 return false;
7504 }
7505 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7506 DeviceVector routedDevices;
7507 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7508 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7509 patchDesc->mPatch.sinks[i].id);
7510 if (device == nullptr) {
7511 ALOGE("%s, no audio device found with id(%d)",
7512 __func__, patchDesc->mPatch.sinks[i].id);
7513 return false;
7514 }
7515 routedDevices.add(device);
7516 }
7517 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007518 if (client->isInvalid()) {
7519 // No need to take care about invalidated clients.
7520 continue;
7521 }
jiabinbce0c1d2020-10-05 11:20:18 -07007522 sp<DeviceDescriptor> preferredDevice =
7523 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7524 if (mEngine->getOutputDevicesForAttributes(
7525 client->attributes(), preferredDevice, false) == routedDevices) {
7526 return false;
7527 }
7528 }
7529 return true;
7530}
7531
7532sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007533 const sp<IOProfile>& profile, const DeviceVector& devices,
7534 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007535{
7536 for (const auto& device : devices) {
7537 // TODO: This should be checking if the profile supports the device combo.
7538 if (!profile->supportsDevice(device)) {
7539 return nullptr;
7540 }
7541 }
7542 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7543 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007544 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007545 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7546 if (status != NO_ERROR) {
7547 return nullptr;
7548 }
7549
7550 // Here is where the out_set_parameters() for card & device gets called
7551 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7552 const audio_devices_t deviceType = device->type();
7553 const String8 &address = String8(device->address().c_str());
7554 if (!address.isEmpty()) {
7555 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7556 mpClientInterface->setParameters(output, String8(param));
7557 free(param);
7558 }
7559 updateAudioProfiles(device, output, profile->getAudioProfiles());
7560 if (!profile->hasValidAudioProfile()) {
7561 ALOGW("%s() missing param", __func__);
7562 desc->close();
7563 return nullptr;
7564 } else if (profile->hasDynamicAudioProfile()) {
7565 desc->close();
7566 output = AUDIO_IO_HANDLE_NONE;
7567 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7568 profile->pickAudioProfile(
7569 config.sample_rate, config.channel_mask, config.format);
7570 config.offload_info.sample_rate = config.sample_rate;
7571 config.offload_info.channel_mask = config.channel_mask;
7572 config.offload_info.format = config.format;
7573
Eric Laurentb4f42a92022-01-17 17:37:31 +01007574 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007575 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7576 if (status != NO_ERROR) {
7577 return nullptr;
7578 }
7579 }
7580
7581 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007582
jiabinbce0c1d2020-10-05 11:20:18 -07007583 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7584 sp<AudioPolicyMix> policyMix;
7585 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7586 policyMix->setOutput(desc);
7587 desc->mPolicyMix = policyMix;
7588 } else {
7589 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7590 address.string());
7591 }
7592
Eric Laurentb4f42a92022-01-17 17:37:31 +01007593 } else if (hasPrimaryOutput() && profile->getModule()
7594 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7595 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7596 // no duplicated output for:
7597 // - direct outputs
7598 // - outputs used by dynamic policy mixes
7599 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007600 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7601
7602 //TODO: configure audio effect output stage here
7603
7604 // open a duplicating output thread for the new output and the primary output
7605 sp<SwAudioOutputDescriptor> dupOutputDesc =
7606 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7607 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7608 if (status == NO_ERROR) {
7609 // add duplicated output descriptor
7610 addOutput(duplicatedOutput, dupOutputDesc);
7611 } else {
7612 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7613 mPrimaryOutput->mIoHandle, output);
7614 desc->close();
7615 removeOutput(output);
7616 nextAudioPortGeneration();
7617 return nullptr;
7618 }
7619 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007620 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7621 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7622 mPrimaryOutput = desc;
7623 }
jiabinbce0c1d2020-10-05 11:20:18 -07007624 return desc;
7625}
7626
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007627} // namespace android