blob: 9bbc1acf4f4d7b7afb8a5cc7acb1657b5b0214d8 [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
Dorin Drimusecc9f422022-03-09 17:57:40 +0100938// Find an MSD output profile compatible with the parameters passed.
939// When "directOnly" is set, restrict search to profiles for direct outputs.
940sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
941 const DeviceVector& devices,
942 uint32_t samplingRate,
943 audio_format_t format,
944 audio_channel_mask_t channelMask,
945 audio_output_flags_t flags,
946 bool directOnly)
947{
948 flags = getRelevantFlags(flags, directOnly);
949
950 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
951 if (msdModule != nullptr) {
952 // for the msd module check if there are patches to the output devices
953 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
954 HwModuleCollection modules;
955 modules.add(msdModule);
956 return searchCompatibleProfileHwModules(
957 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
958 flags, directOnly);
959 }
960 }
961 return nullptr;
962}
963
Michael Chana94fbb22018-04-24 14:31:19 +1000964// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
965// search to profiles for direct outputs.
966sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100967 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000968 uint32_t samplingRate,
969 audio_format_t format,
970 audio_channel_mask_t channelMask,
971 audio_output_flags_t flags,
972 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700973{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100974 flags = getRelevantFlags(flags, directOnly);
975
976 return searchCompatibleProfileHwModules(
977 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
978}
979
980audio_output_flags_t AudioPolicyManager::getRelevantFlags (
981 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000982 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100983 // only retain flags that will drive the direct output profile selection
984 // if explicitly requested
985 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000986 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100987 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
988 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +1000989 }
Dorin Drimusecc9f422022-03-09 17:57:40 +0100990 return flags;
991}
Eric Laurent861a6282015-05-18 15:40:16 -0700992
Dorin Drimusecc9f422022-03-09 17:57:40 +0100993sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
994 const HwModuleCollection& hwModules,
995 const DeviceVector& devices,
996 uint32_t samplingRate,
997 audio_format_t format,
998 audio_channel_mask_t channelMask,
999 audio_output_flags_t flags,
1000 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001001 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001002 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001003 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001004 if (!curProfile->isCompatibleProfile(devices,
1005 samplingRate, NULL /*updatedSamplingRate*/,
1006 format, NULL /*updatedFormat*/,
1007 channelMask, NULL /*updatedChannelMask*/,
1008 flags)) {
1009 continue;
1010 }
1011 // reject profiles not corresponding to a device currently available
1012 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1013 continue;
1014 }
1015 // reject profiles if connected device does not support codec
1016 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1017 continue;
1018 }
1019 if (!directOnly) {
1020 return curProfile;
1021 }
1022
1023 // when searching for direct outputs, if several profiles are compatible, give priority
1024 // to one with offload capability
1025 if (profile != 0 &&
1026 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001027 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001028 }
1029 profile = curProfile;
1030 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1031 break;
1032 }
Eric Laurente552edb2014-03-10 17:42:56 -07001033 }
1034 }
Eric Laurent861a6282015-05-18 15:40:16 -07001035 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001036}
1037
Eric Laurentfa0f6742021-08-17 18:39:44 +02001038sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001039 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001040{
1041 for (const auto& hwModule : mHwModules) {
1042 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001043 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001044 continue;
1045 }
1046 // reject profiles not corresponding to a device currently available
1047 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1048 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1049 continue;
1050 }
1051 if (!devices.empty()) {
1052 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1053 != devices.size()) {
1054 continue;
1055 }
1056 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001057 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1058 return curProfile;
1059 }
1060 }
1061 return nullptr;
1062}
1063
Eric Laurentf4e63452017-11-06 19:31:46 +00001064audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001065{
François Gaffiec005e562018-11-06 15:04:49 +01001066 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001067
1068 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1069 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1070 // format, flags, etc. This may result in some discrepancy for functions that utilize
1071 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1072 // and AudioSystem::getOutputSamplingRate().
1073
François Gaffie11d30102018-11-02 16:09:09 +01001074 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001075 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001076
François Gaffie11d30102018-11-02 16:09:09 +01001077 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1078 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001079 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001080}
1081
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001082status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1083 const audio_attributes_t *srcAttr,
1084 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001085{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001086 if (srcAttr != NULL) {
1087 if (!isValidAttributes(srcAttr)) {
1088 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1089 __func__,
1090 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1091 srcAttr->tags);
1092 return BAD_VALUE;
1093 }
1094 *dstAttr = *srcAttr;
1095 } else {
1096 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1097 ALOGE("%s: invalid stream type", __func__);
1098 return BAD_VALUE;
1099 }
François Gaffiec005e562018-11-06 15:04:49 +01001100 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001101 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001102
1103 // Only honor audibility enforced when required. The client will be
1104 // forced to reconnect if the forced usage changes.
1105 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001106 dstAttr->flags = static_cast<audio_flags_mask_t>(
1107 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001108 }
1109
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001110 return NO_ERROR;
1111}
1112
Kevin Rocard153f92d2018-12-18 18:33:28 -08001113status_t AudioPolicyManager::getOutputForAttrInt(
1114 audio_attributes_t *resultAttr,
1115 audio_io_handle_t *output,
1116 audio_session_t session,
1117 const audio_attributes_t *attr,
1118 audio_stream_type_t *stream,
1119 uid_t uid,
1120 const audio_config_t *config,
1121 audio_output_flags_t *flags,
1122 audio_port_handle_t *selectedDeviceId,
1123 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001124 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001125 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001126{
François Gaffiec005e562018-11-06 15:04:49 +01001127 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001128 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001129 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001130 const sp<DeviceDescriptor> requestedDevice =
1131 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1132
Eric Laurent8a1095a2019-11-08 14:44:16 -08001133 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001134 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1135 if (status != NO_ERROR) {
1136 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001137 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001138 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001139 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001140 }
François Gaffiec005e562018-11-06 15:04:49 +01001141 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001142
François Gaffiec005e562018-11-06 15:04:49 +01001143 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1144 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001145
Kevin Rocard153f92d2018-12-18 18:33:28 -08001146 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1147 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1148 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001149 sp<AudioPolicyMix> primaryMix;
1150 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001151 if (status != OK) {
1152 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001153 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001154
Kevin Rocard153f92d2018-12-18 18:33:28 -08001155 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001156 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001157
1158 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001159 if ((usePrimaryOutputFromPolicyMixes
1160 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001161 && !audio_is_linear_pcm(config->format)) {
1162 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001163 return BAD_VALUE;
1164 }
1165 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001166 sp<DeviceDescriptor> deviceDesc =
1167 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1168 primaryMix->mDeviceAddress,
1169 AUDIO_FORMAT_DEFAULT);
1170 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001171 if (deviceDesc != nullptr
1172 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001173 audio_io_handle_t newOutput;
1174 status = openDirectOutput(
1175 *stream, session, config,
1176 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1177 DeviceVector(deviceDesc), &newOutput);
1178 if (status != NO_ERROR) {
1179 policyDesc = nullptr;
1180 } else {
1181 policyDesc = mOutputs.valueFor(newOutput);
1182 primaryMix->setOutput(policyDesc);
1183 }
1184 }
1185 if (policyDesc != nullptr) {
1186 policyDesc->mPolicyMix = primaryMix;
1187 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001188 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001189
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001190 ALOGV("getOutputForAttr() returns output %d", *output);
1191 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1192 *outputType = API_OUT_MIX_PLAYBACK;
1193 } else {
1194 *outputType = API_OUTPUT_LEGACY;
1195 }
1196 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001197 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001198 }
François Gaffiec005e562018-11-06 15:04:49 +01001199 // Virtual sources must always be dynamicaly or explicitly routed
1200 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1201 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1202 return BAD_VALUE;
1203 }
1204 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1205 // in order to let the choice of the order to future vendor engine
1206 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001207
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001208 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001209 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001210 }
1211
Nadav Barb2f18162018-07-18 13:01:53 +03001212 // Set incall music only if device was explicitly set, and fallback to the device which is
1213 // chosen by the engine if not.
1214 // FIXME: provide a more generic approach which is not device specific and move this back
1215 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001216 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001217 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001218 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001219 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001220 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001221 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001222 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001223 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001224 }
1225 }
1226
François Gaffiec005e562018-11-06 15:04:49 +01001227 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1228 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1229 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001230
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001231 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001232 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001233 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001234 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001235 ALOGV("%s() Using MSD devices %s instead of devices %s",
1236 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001237 } else {
1238 *output = AUDIO_IO_HANDLE_NONE;
1239 }
1240 }
1241 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001242 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001243 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001244 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001245 if (*output == AUDIO_IO_HANDLE_NONE) {
1246 return INVALID_OPERATION;
1247 }
Paul McLeanaa981192015-03-21 09:55:15 -07001248
François Gaffiec005e562018-11-06 15:04:49 +01001249 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001250 for (auto &outputDevice : outputDevices) {
1251 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1252 *selectedDeviceId = outputDevice->getId();
1253 break;
1254 }
1255 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001256
Eric Laurent8a1095a2019-11-08 14:44:16 -08001257 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1258 *outputType = API_OUTPUT_TELEPHONY_TX;
1259 } else {
1260 *outputType = API_OUTPUT_LEGACY;
1261 }
1262
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001263 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1264
1265 return NO_ERROR;
1266}
1267
1268status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1269 audio_io_handle_t *output,
1270 audio_session_t session,
1271 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001272 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001273 const audio_config_t *config,
1274 audio_output_flags_t *flags,
1275 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001276 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001277 std::vector<audio_io_handle_t> *secondaryOutputs,
1278 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001279{
1280 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1281 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1282 return INVALID_OPERATION;
1283 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001284 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001285 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001286 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001287 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001288 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001289 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001290 const sp<DeviceDescriptor> requestedDevice =
1291 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1292
1293 // Prevent from storing invalid requested device id in clients
1294 const audio_port_handle_t sanitizedRequestedPortId =
1295 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1296 *selectedDeviceId = sanitizedRequestedPortId;
1297
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001298 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001299 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001300 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001301 if (status != NO_ERROR) {
1302 return status;
1303 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001304 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001305 if (secondaryOutputs != nullptr) {
1306 for (auto &secondaryMix : secondaryMixes) {
1307 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1308 if (outputDesc != nullptr &&
1309 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1310 secondaryOutputs->push_back(outputDesc->mIoHandle);
1311 weakSecondaryOutputDescs.push_back(outputDesc);
1312 }
1313 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001314 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001315
Eric Laurent8fc147b2018-07-22 19:13:55 -07001316 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001317 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001318 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001319 };
jiabin4ef93452019-09-10 14:29:54 -07001320 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001321
Eric Laurentc209fe42020-06-05 18:11:23 -07001322 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001323 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001324 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001325 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001326 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001327 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001328 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001329 std::move(weakSecondaryOutputDescs),
1330 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001331 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001332
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001333 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1334 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001335
Eric Laurente83b55d2014-11-14 10:06:21 -08001336 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001337}
1338
Eric Laurentc529cf62020-04-17 18:19:10 -07001339status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1340 audio_session_t session,
1341 const audio_config_t *config,
1342 audio_output_flags_t flags,
1343 const DeviceVector &devices,
1344 audio_io_handle_t *output) {
1345
1346 *output = AUDIO_IO_HANDLE_NONE;
1347
1348 // skip direct output selection if the request can obviously be attached to a mixed output
1349 // and not explicitly requested
1350 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1351 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1352 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1353 return NAME_NOT_FOUND;
1354 }
1355
1356 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1357 // This prevents creating an offloaded track and tearing it down immediately after start
1358 // when audioflinger detects there is an active non offloadable effect.
1359 // FIXME: We should check the audio session here but we do not have it in this context.
1360 // This may prevent offloading in rare situations where effects are left active by apps
1361 // in the background.
1362 sp<IOProfile> profile;
1363 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1364 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1365 profile = getProfileForOutput(
1366 devices, config->sample_rate, config->format, config->channel_mask,
1367 flags, true /* directOnly */);
1368 }
1369
1370 if (profile == nullptr) {
1371 return NAME_NOT_FOUND;
1372 }
1373
1374 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1375 for (size_t i = 0; i < mOutputs.size(); i++) {
1376 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1377 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1378 // reuse direct output if currently open by the same client
1379 // and configured with same parameters
1380 if ((config->sample_rate == desc->getSamplingRate()) &&
1381 (config->format == desc->getFormat()) &&
1382 (config->channel_mask == desc->getChannelMask()) &&
1383 (session == desc->mDirectClientSession)) {
1384 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001385 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001386 mOutputs.keyAt(i), session);
1387 *output = mOutputs.keyAt(i);
1388 return NO_ERROR;
1389 }
1390 }
1391 }
1392
1393 if (!profile->canOpenNewIo()) {
1394 return NAME_NOT_FOUND;
1395 }
1396
1397 sp<SwAudioOutputDescriptor> outputDesc =
1398 new SwAudioOutputDescriptor(profile, mpClientInterface);
1399
Michael Chan6fb34492020-12-08 15:44:49 +11001400 // An MSD patch may be using the only output stream that can service this request. Release
1401 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001402 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001403
Eric Laurentf1f22e72021-07-13 14:04:14 +02001404 status_t status =
1405 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001406
1407 // only accept an output with the requested parameters
1408 if (status != NO_ERROR ||
1409 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1410 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1411 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1412 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1413 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1414 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1415 config->channel_mask, outputDesc->getChannelMask());
1416 if (*output != AUDIO_IO_HANDLE_NONE) {
1417 outputDesc->close();
1418 }
1419 // fall back to mixer output if possible when the direct output could not be open
1420 if (audio_is_linear_pcm(config->format) &&
1421 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1422 return NAME_NOT_FOUND;
1423 }
1424 *output = AUDIO_IO_HANDLE_NONE;
1425 return BAD_VALUE;
1426 }
1427 outputDesc->mDirectOpenCount = 1;
1428 outputDesc->mDirectClientSession = session;
1429
1430 addOutput(*output, outputDesc);
1431 mPreviousOutputs = mOutputs;
1432 ALOGV("%s returns new direct output %d", __func__, *output);
1433 mpClientInterface->onAudioPortListUpdate();
1434 return NO_ERROR;
1435}
1436
François Gaffie11d30102018-11-02 16:09:09 +01001437audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1438 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001439 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001440 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001441 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001442 audio_output_flags_t *flags,
1443 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001444{
Andy Hungc88b0642018-04-27 15:42:35 -07001445 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001446
jiabine375d412019-02-26 12:54:53 -08001447 // Discard haptic channel mask when forcing muting haptic channels.
1448 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001449 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1450 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001451
Eric Laurente552edb2014-03-10 17:42:56 -07001452 // open a direct output if required by specified parameters
1453 //force direct flag if offload flag is set: offloading implies a direct output stream
1454 // and all common behaviors are driven by checking only the direct flag
1455 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001456 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1457 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001458 }
Nadav Bar766fb022018-01-07 12:18:03 +02001459 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1460 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001461 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001462
1463 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1464
Eric Laurente83b55d2014-11-14 10:06:21 -08001465 // only allow deep buffering for music stream type
1466 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001467 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001468 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001469 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001470 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1471 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001472 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001473 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001474 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001475 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001476 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001477 audio_is_linear_pcm(config->format) &&
1478 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001479 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001480 AUDIO_OUTPUT_FLAG_DIRECT);
1481 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001482 }
Eric Laurente552edb2014-03-10 17:42:56 -07001483
Carter Hsua3abb402021-10-26 11:11:20 +08001484 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1485 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1486 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1487 }
1488
Eric Laurentfa0f6742021-08-17 18:39:44 +02001489 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001490 && canBeSpatializedInt(attr, config,
1491 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02001492 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001493 }
1494
Eric Laurentc529cf62020-04-17 18:19:10 -07001495 audio_config_t directConfig = *config;
1496 directConfig.channel_mask = channelMask;
1497 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1498 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001499 return output;
1500 }
1501
Eric Laurent14cbfca2016-03-17 09:42:16 -07001502 // A request for HW A/V sync cannot fallback to a mixed output because time
1503 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001504 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001505 return AUDIO_IO_HANDLE_NONE;
1506 }
1507
Eric Laurente552edb2014-03-10 17:42:56 -07001508 // ignoring channel mask due to downmix capability in mixer
1509
1510 // open a non direct output
1511
1512 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001513 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001514 // get which output is suitable for the specified stream. The actual
1515 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001516 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001517
Eric Laurent8838a382014-09-08 16:44:28 -07001518 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001519 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001520 output = selectOutput(
1521 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001522 }
François Gaffie11d30102018-11-02 16:09:09 +01001523 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001524 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001525 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001526
Eric Laurente552edb2014-03-10 17:42:56 -07001527 return output;
1528}
1529
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001530sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001531 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1532 mAvailableInputDevices);
1533 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1534}
1535
1536DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1537 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1538 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001539}
1540
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001541const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001542 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001543 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1544 if (msdModule != 0) {
1545 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1546 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1547 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1548 const struct audio_port_config *source = &patch->mPatch.sources[j];
1549 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1550 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001551 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001552 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001553 }
1554 }
1555 }
1556 return msdPatches;
1557}
1558
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001559status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1560 const InputProfileCollection &inputProfiles,
1561 const OutputProfileCollection &outputProfiles,
1562 const sp<DeviceDescriptor> &sourceDevice,
1563 const sp<DeviceDescriptor> &sinkDevice,
1564 AudioProfileVector& sourceProfiles,
1565 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001566 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001567 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001568 return NO_INIT;
1569 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001570 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001571 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001572 return NO_INIT;
1573 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001574 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001575 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1576 inProfile->supportsDevice(sourceDevice)) {
1577 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001578 }
1579 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001580 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001581 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001582 outProfile->supportsDevice(sinkDevice)) {
1583 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001584 }
1585 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001586 return NO_ERROR;
1587}
1588
1589status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1590 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1591 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1592{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001593 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001594 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1595 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1596 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001597 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001598 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1599 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001600 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001601 }
1602 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1603 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1604 sinkConfig->format = bestSinkConfig.format;
1605 // For encoded streams force direct flag to prevent downstream mixing.
1606 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1607 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001608 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1609 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001610 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001611 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1612 // raw and IEC61937 framed streams.
1613 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1614 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1615 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001616 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1617 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1618 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1619 sourceConfig->format = bestSinkConfig.format;
1620 // Copy input stream directly without any processing (e.g. resampling).
1621 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1622 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1623 if (hwAvSync) {
1624 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1625 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1626 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1627 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1628 }
1629 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1630 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1631 sinkConfig->config_mask |= config_mask;
1632 sourceConfig->config_mask |= config_mask;
1633 return NO_ERROR;
1634}
1635
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001636PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1637 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001638{
1639 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001640 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1641 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1642 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1643 if (deviceModule == nullptr) {
1644 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1645 return patchBuilder;
1646 }
1647 const InputProfileCollection inputProfiles = msdIsSource ?
1648 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1649 const OutputProfileCollection outputProfiles = msdIsSource ?
1650 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1651
1652 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1653 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1654 device : getMsdAudioOutDevices().itemAt(0);
1655 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1656
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001657 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1658 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001659 AudioProfileVector sourceProfiles;
1660 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001661 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1662 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001663 for (auto hwAvSync : { true, false }) {
1664 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1665 sourceProfiles, sinkProfiles) != NO_ERROR) {
1666 continue;
1667 }
1668 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1669 &sinkConfig) == NO_ERROR) {
1670 // Found a matching config. Re-create PatchBuilder with this config.
1671 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1672 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001673 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001674 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001675 " supporting PCM format conversion.", __func__);
1676 return patchBuilder;
1677}
1678
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001679status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001680 DeviceVector devices;
1681 if (outputDevices != nullptr && outputDevices->size() > 0) {
1682 devices.add(*outputDevices);
1683 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001684 // Use media strategy for unspecified output device. This should only
1685 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1686 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001687 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001688 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001689 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001690 }
Michael Chan6fb34492020-12-08 15:44:49 +11001691 std::vector<PatchBuilder> patchesToCreate;
1692 for (auto i = 0u; i < devices.size(); ++i) {
1693 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001694 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001695 }
1696 // Retain only the MSD patches associated with outputDevices request.
1697 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001698 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001699 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1700 auto retainedPatch = false;
1701 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1702 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1703 patchesToRemove.removeItemsAt(i);
1704 retainedPatch = true;
1705 break;
1706 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001707 }
Michael Chan6fb34492020-12-08 15:44:49 +11001708 if (retainedPatch) {
1709 it = patchesToCreate.erase(it);
1710 continue;
1711 }
1712 ++it;
1713 }
1714 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1715 return NO_ERROR;
1716 }
1717 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1718 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001719 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001720 }
Michael Chan6fb34492020-12-08 15:44:49 +11001721 status_t status = NO_ERROR;
1722 for (const auto &p : patchesToCreate) {
1723 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1724 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1725 char message[256];
1726 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1727 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1728 currStatus == NO_ERROR ? "Success" : "Error",
1729 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1730 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1731 if (currStatus == NO_ERROR) {
1732 ALOGD("%s", message);
1733 } else {
1734 ALOGE("%s", message);
1735 if (status == NO_ERROR) {
1736 status = currStatus;
1737 }
1738 }
1739 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001740 return status;
1741}
1742
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001743void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1744 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001745 for (size_t i = 0; i < msdPatches.size(); i++) {
1746 const auto& patch = msdPatches[i];
1747 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1748 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1749 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1750 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1751 releaseAudioPatch(patch->getHandle(), mUidCached);
1752 break;
1753 }
1754 }
1755 }
1756}
1757
Dorin Drimus94d94412022-02-02 09:05:02 +01001758bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1759 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1760 AudioPatchCollection msdPatches = getMsdOutputPatches();
1761 for (size_t i = 0; i < msdPatches.size(); i++) {
1762 const auto& patch = msdPatches[i];
1763 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1764 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1765 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1766 const auto& foundDevice = devicesToCheck.getDevice(
1767 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1768 if (foundDevice != nullptr) {
1769 devicesToCheck.remove(foundDevice);
1770 if (devicesToCheck.isEmpty()) {
1771 return true;
1772 }
1773 }
1774 }
1775 }
1776 }
1777 return false;
1778}
1779
Eric Laurente0720872014-03-11 09:30:41 -07001780audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001781 audio_output_flags_t flags,
1782 audio_format_t format,
1783 audio_channel_mask_t channelMask,
1784 uint32_t samplingRate,
1785 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001786{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001787 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1788 "%s called with format %#x", __func__, format);
1789
jiabinebb6af42020-06-09 17:31:17 -07001790 // Return the output that haptic-generating attached to when 1) session id is specified,
1791 // 2) haptic-generating effect exists for given session id and 3) the output that
1792 // haptic-generating effect attached to is in given outputs.
1793 if (sessionId != AUDIO_SESSION_NONE) {
1794 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1795 sessionId, FX_IID_HAPTICGENERATOR);
1796 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1797 return hapticGeneratingOutput;
1798 }
1799 }
1800
Eric Laurent16c66dd2019-05-01 17:54:10 -07001801 // Flags disqualifying an output: the match must happen before calling selectOutput()
1802 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1803 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1804
1805 // Flags expressing a functional request: must be honored in priority over
1806 // other criteria
1807 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1808 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001809 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1810 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001811 // Flags expressing a performance request: have lower priority than serving
1812 // requested sampling rate or channel mask
1813 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1814 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1815 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1816
1817 const audio_output_flags_t functionalFlags =
1818 (audio_output_flags_t)(flags & kFunctionalFlags);
1819 const audio_output_flags_t performanceFlags =
1820 (audio_output_flags_t)(flags & kPerformanceFlags);
1821
1822 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1823
Eric Laurente552edb2014-03-10 17:42:56 -07001824 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001825 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001826 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001827 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001828 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001829 // with tiebreak preferring the minimum number of extra functional flags
1830 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001831 // 3: the output supporting the exact channel mask
1832 // 4: the output with a higher channel count than requested
1833 // 5: the output with a higher sampling rate than requested
1834 // 6: the output with the highest number of requested performance flags
1835 // 7: the output with the bit depth the closest to the requested one
1836 // 8: the primary output
1837 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001838
Eric Laurent16c66dd2019-05-01 17:54:10 -07001839 // matching criteria values in priority order for best matching output so far
1840 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001841
Eric Laurent16c66dd2019-05-01 17:54:10 -07001842 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1843 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1844 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001845
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001846 for (audio_io_handle_t output : outputs) {
1847 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001848 // matching criteria values in priority order for current output
1849 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001850
Eric Laurent16c66dd2019-05-01 17:54:10 -07001851 if (outputDesc->isDuplicated()) {
1852 continue;
1853 }
1854 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1855 continue;
1856 }
Eric Laurent8838a382014-09-08 16:44:28 -07001857
Eric Laurent16c66dd2019-05-01 17:54:10 -07001858 // If haptic channel is specified, use the haptic output if present.
1859 // When using haptic output, same audio format and sample rate are required.
1860 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001861 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001862 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1863 continue;
1864 }
1865 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001866 && format == outputDesc->getFormat()
1867 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001868 currentMatchCriteria[0] = outputHapticChannelCount;
1869 }
1870
1871 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001872 const int matchingFunctionalFlags =
1873 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1874 const int totalFunctionalFlags =
1875 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1876 // Prefer matching functional flags, but subtract unnecessary functional flags.
1877 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001878
1879 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001880 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1881 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001882 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1883 channelCount <= outputChannelCount) {
1884 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001885 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1886 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001887 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001888 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001889 currentMatchCriteria[3] = outputChannelCount;
1890 }
1891
1892 // sampling rate match
1893 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001894 samplingRate <= outputDesc->getSamplingRate()) {
1895 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001896 }
1897
1898 // performance flags match
1899 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1900
1901 // format match
1902 if (format != AUDIO_FORMAT_INVALID) {
1903 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001904 PolicyAudioPort::kFormatDistanceMax -
1905 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001906 }
1907
1908 // primary output match
1909 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1910
1911 // compare match criteria by priority then value
1912 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1913 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1914 bestMatchCriteria = currentMatchCriteria;
1915 bestOutput = output;
1916
1917 std::stringstream result;
1918 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1919 std::ostream_iterator<int>(result, " "));
1920 ALOGV("%s new bestOutput %d criteria %s",
1921 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001922 }
1923 }
1924
Eric Laurent16c66dd2019-05-01 17:54:10 -07001925 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001926}
1927
Eric Laurent8fc147b2018-07-22 19:13:55 -07001928status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001929{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001930 ALOGV("%s portId %d", __FUNCTION__, portId);
1931
1932 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1933 if (outputDesc == 0) {
1934 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001935 return BAD_VALUE;
1936 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001937 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001938
Eric Laurent8fc147b2018-07-22 19:13:55 -07001939 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001940 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001941
Eric Laurent733ce942017-12-07 12:18:25 -08001942 status_t status = outputDesc->start();
1943 if (status != NO_ERROR) {
1944 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001945 }
1946
Eric Laurent97ac8712018-07-27 18:59:02 -07001947 uint32_t delayMs;
1948 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001949
1950 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001951 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001952 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001953 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001954 if (delayMs != 0) {
1955 usleep(delayMs * 1000);
1956 }
1957
1958 return status;
1959}
1960
Eric Laurent97ac8712018-07-27 18:59:02 -07001961status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1962 const sp<TrackClientDescriptor>& client,
1963 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001964{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001965 // cannot start playback of STREAM_TTS if any other output is being used
1966 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001967
1968 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001969 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001970 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001971 auto clientStrategy = client->strategy();
1972 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001973 if (stream == AUDIO_STREAM_TTS) {
1974 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001975 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01001976 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001977 return INVALID_OPERATION;
1978 } else {
1979 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1980 }
1981 } else {
1982 // some playback other than beacon starts
1983 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1984 }
1985
Eric Laurent77305a62016-07-25 16:39:22 -07001986 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001987 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001988 bool force = !outputDesc->isActive() &&
1989 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001990
François Gaffie11d30102018-11-02 16:09:09 +01001991 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001992 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001993 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001994 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001995 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001996 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001997 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001998 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001999 } else {
2000 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002001 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002002 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2003 AUDIO_FORMAT_DEFAULT);
2004 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2005 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002006 }
2007
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002008 // requiresMuteCheck is false when we can bypass mute strategy.
2009 // It covers a common case when there is no materially active audio
2010 // and muting would result in unnecessary delay and dropped audio.
2011 const uint32_t outputLatencyMs = outputDesc->latency();
2012 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
2013
Eric Laurente552edb2014-03-10 17:42:56 -07002014 // increment usage count for this stream on the requested output:
2015 // NOTE that the usage count is the same for duplicated output and hardware output which is
2016 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002017 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002018
2019 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002020 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2021 client->isPreferredDeviceForExclusiveUse()) {
2022 // Preferred device may be exclusive, use only if no other active clients on this output
2023 devices = DeviceVector(
2024 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2025 } else {
2026 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2027 }
François Gaffie11d30102018-11-02 16:09:09 +01002028 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002029 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002030 }
2031 }
Eric Laurente552edb2014-03-10 17:42:56 -07002032
François Gaffiec005e562018-11-06 15:04:49 +01002033 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002034 selectOutputForMusicEffects();
2035 }
2036
François Gaffie1c878552018-11-22 16:53:21 +01002037 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002038 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002039 if (devices.isEmpty()) {
2040 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002041 }
François Gaffiec005e562018-11-06 15:04:49 +01002042 bool shouldWait =
2043 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2044 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2045 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002046 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002047 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002048 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002049 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002050 // An output has a shared device if
2051 // - managed by the same hw module
2052 // - supports the currently selected device
2053 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002054 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002055
Eric Laurent77305a62016-07-25 16:39:22 -07002056 // force a device change if any other output is:
2057 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002058 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002059 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002060 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002061 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002062 // change the device currently selected by the other output.
2063 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002064 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002065 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002066 force = true;
2067 }
2068 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002069 // a notification so that audio focus effect can propagate, or that a mute/unmute
2070 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002071 const uint32_t latencyMs = desc->latency();
2072 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2073
2074 if (shouldWait && isActive && (waitMs < latencyMs)) {
2075 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002076 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002077
2078 // Require mute check if another output is on a shared device
2079 // and currently active to have proper drain and avoid pops.
2080 // Note restoring AudioTracks onto this output needs to invoke
2081 // a volume ramp if there is no mute.
2082 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002083 }
2084 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002085
2086 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002087 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002088
Eric Laurente552edb2014-03-10 17:42:56 -07002089 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002090 auto &curves = getVolumeCurves(client->attributes());
2091 checkAndSetVolume(curves, client->volumeSource(),
2092 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002093 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002094 outputDesc->devices().types(), 0 /*delay*/,
2095 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002096
2097 // update the outputs if starting an output with a stream that can affect notification
2098 // routing
2099 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002100
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002101 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002102 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002103 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2104 }
Eric Laurentdc462862016-07-19 12:29:53 -07002105
2106 if (waitMs > muteWaitMs) {
2107 *delayMs = waitMs - muteWaitMs;
2108 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002109
2110 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2111 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2112 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2113 // change occurs after the MixerThread starts and causes a stream volume
2114 // glitch.
2115 //
2116 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002117 }
Eric Laurentdc462862016-07-19 12:29:53 -07002118
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002119 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002120 mEngine->getForceUse(
2121 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002122 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002123 }
2124
Eric Laurent97ac8712018-07-27 18:59:02 -07002125 // Automatically enable the remote submix input when output is started on a re routing mix
2126 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002127 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2128 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002129 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2130 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2131 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002132 "remote-submix",
2133 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002134 }
2135
Eric Laurente552edb2014-03-10 17:42:56 -07002136 return NO_ERROR;
2137}
2138
Eric Laurent8fc147b2018-07-22 19:13:55 -07002139status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002140{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002141 ALOGV("%s portId %d", __FUNCTION__, portId);
2142
2143 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2144 if (outputDesc == 0) {
2145 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002146 return BAD_VALUE;
2147 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002148 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002149
Eric Laurent97ac8712018-07-27 18:59:02 -07002150 ALOGV("stopOutput() output %d, stream %d, session %d",
2151 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002152
Eric Laurent97ac8712018-07-27 18:59:02 -07002153 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002154
Eric Laurent733ce942017-12-07 12:18:25 -08002155 if (status == NO_ERROR ) {
2156 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002157 }
2158 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002159}
2160
Eric Laurent97ac8712018-07-27 18:59:02 -07002161status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2162 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002163{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002164 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002165 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002166 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002167
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002168 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2169
François Gaffie1c878552018-11-22 16:53:21 +01002170 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2171 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002172 // Automatically disable the remote submix input when output is stopped on a
2173 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002174 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002175 if (isSingleDeviceType(
2176 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002177 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002178 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002179 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2180 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002181 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002182 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002183 }
2184 }
2185 bool forceDeviceUpdate = false;
2186 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002187 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002188 forceDeviceUpdate = true;
2189 }
2190
Eric Laurente552edb2014-03-10 17:42:56 -07002191 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002192 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002193
Eric Laurente552edb2014-03-10 17:42:56 -07002194 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002195 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002196 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002197 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002198
2199 // If the routing does not change, if an output is routed on a device using HwGain
2200 // (aka setAudioPortConfig) and there are still active clients following different
2201 // volume group(s), force reapply volume
2202 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2203 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2204
Eric Laurente552edb2014-03-10 17:42:56 -07002205 // delay the device switch by twice the latency because stopOutput() is executed when
2206 // the track stop() command is received and at that time the audio track buffer can
2207 // still contain data that needs to be drained. The latency only covers the audio HAL
2208 // and kernel buffers. Also the latency does not always include additional delay in the
2209 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002210 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2211 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002212
2213 // force restoring the device selection on other active outputs if it differs from the
2214 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002215 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002216 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002217 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002218 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002219 desc->isActive() &&
2220 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002221 (newDevices != desc->devices())) {
2222 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2223 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002224
François Gaffie11d30102018-11-02 16:09:09 +01002225 setOutputDevices(desc, newDevices2, force, delayMs);
2226
Eric Laurent57de36c2016-09-28 16:59:11 -07002227 // re-apply device specific volume if not done by setOutputDevice()
2228 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002229 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002230 }
Eric Laurente552edb2014-03-10 17:42:56 -07002231 }
2232 }
2233 // update the outputs if stopping one with a stream that can affect notification routing
2234 handleNotificationRoutingForStream(stream);
2235 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002236
2237 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2238 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002239 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002240 }
2241
François Gaffiec005e562018-11-06 15:04:49 +01002242 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002243 selectOutputForMusicEffects();
2244 }
Eric Laurente552edb2014-03-10 17:42:56 -07002245 return NO_ERROR;
2246 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002247 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002248 return INVALID_OPERATION;
2249 }
2250}
2251
jiabinbce0c1d2020-10-05 11:20:18 -07002252bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002253{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002254 ALOGV("%s portId %d", __FUNCTION__, portId);
2255
2256 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2257 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002258 // If an output descriptor is closed due to a device routing change,
2259 // then there are race conditions with releaseOutput from tracks
2260 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2261 // destroyed shortly thereafter.
2262 //
2263 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002264 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002265 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002266 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002267
2268 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002269
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302270 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2271 if (outputDesc->isClientActive(client)) {
2272 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2273 stopOutput(portId);
2274 }
2275
Eric Laurent8fc147b2018-07-22 19:13:55 -07002276 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2277 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002278 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002279 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002280 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002281 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002282 if (--outputDesc->mDirectOpenCount == 0) {
2283 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002284 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002285 }
2286 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302287
Andy Hung39efb7a2018-09-26 15:39:28 -07002288 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002289 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2290 // The output is pending reopened to query dynamic profiles and
2291 // there is no active clients
2292 closeOutput(outputDesc->mIoHandle);
2293 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2294 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2295 if (newOutputDesc == nullptr) {
2296 ALOGE("%s failed to open output", __func__);
2297 }
2298 return true;
2299 }
2300 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002301}
2302
Eric Laurentcaf7f482014-11-25 17:50:47 -08002303status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2304 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002305 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002306 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002307 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002308 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002309 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002310 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002311 input_type_t *inputType,
2312 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002313{
François Gaffiec005e562018-11-06 15:04:49 +01002314 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002315 "flags %#x attributes=%s requested device ID %d",
2316 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2317 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002318
Eric Laurentad2e7b92017-09-14 20:06:42 -07002319 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002320 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002321 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002322 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002323 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002324 sp<AudioInputDescriptor> inputDesc;
2325 sp<RecordClientDescriptor> clientDesc;
2326 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002327 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002328 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002329
2330 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2331 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2332 return INVALID_OPERATION;
2333 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002334
Francois Gaffie716e1432019-01-14 16:58:59 +01002335 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2336 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002337 }
2338
Paul McLean466dc8e2015-04-17 13:15:36 -06002339 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002340 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002341 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002342
Eric Laurentad2e7b92017-09-14 20:06:42 -07002343 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2344 // possible
2345 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2346 *input != AUDIO_IO_HANDLE_NONE) {
2347 ssize_t index = mInputs.indexOfKey(*input);
2348 if (index < 0) {
2349 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2350 status = BAD_VALUE;
2351 goto error;
2352 }
2353 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002354 RecordClientVector clients = inputDesc->getClientsForSession(session);
2355 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002356 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2357 status = BAD_VALUE;
2358 goto error;
2359 }
2360 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2361 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002362 // corresponds to a new client and is only permitted from the same UID.
2363 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002364 if (clients.size() > 1) {
2365 for (const auto& client : clients) {
2366 // The client map is ordered by key values (portId) and portIds are allocated
2367 // incrementaly. So the first client in this list is the one opened by audio flinger
2368 // when the mmap stream is created and should be ignored as it does not correspond
2369 // to an actual client
2370 if (client == *clients.cbegin()) {
2371 continue;
2372 }
2373 if (uid != client->uid() && !client->isSilenced()) {
2374 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2375 uid, client->portId(), client->uid());
2376 status = INVALID_OPERATION;
2377 goto error;
2378 }
Eric Laurent331679c2018-04-16 17:03:16 -07002379 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002380 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002381 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002382 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002383
Eric Laurentfecbceb2021-02-09 14:46:43 +01002384 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002385 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002386 }
2387
2388 *input = AUDIO_IO_HANDLE_NONE;
2389 *inputType = API_INPUT_INVALID;
2390
Francois Gaffie716e1432019-01-14 16:58:59 +01002391 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002392
Francois Gaffie716e1432019-01-14 16:58:59 +01002393 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2394 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2395 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002396 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002397 ALOGW("%s could not find input mix for attr %s",
2398 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002399 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002400 }
jiabinc1de2df2019-05-07 14:26:40 -07002401 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2402 String8(attr->tags + strlen("addr=")),
2403 AUDIO_FORMAT_DEFAULT);
2404 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002405 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002406 __func__, attributes.source, attributes.tags);
2407 status = BAD_VALUE;
2408 goto error;
2409 }
2410
Kevin Rocard25f9b052019-02-27 15:08:54 -08002411 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2412 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2413 } else {
2414 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2415 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002416 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002417 if (explicitRoutingDevice != nullptr) {
2418 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002419 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002420 // Prevent from storing invalid requested device id in clients
2421 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002422 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002423 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2424 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002425 }
François Gaffie11d30102018-11-02 16:09:09 +01002426 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002427 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002428 status = BAD_VALUE;
2429 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002430 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002431 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2432 *inputType = API_INPUT_MIX_CAPTURE;
2433 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002434 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2435 // there is an external policy, but this input is attached to a mix of recorders,
2436 // meaning it receives audio injected into the framework, so the recorder doesn't
2437 // know about it and is therefore considered "legacy"
2438 *inputType = API_INPUT_LEGACY;
2439 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002440 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002441 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002442 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002443 } else {
2444 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002445 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002446
Eric Laurent599c7582015-12-07 18:05:55 -08002447 }
2448
François Gaffiec005e562018-11-06 15:04:49 +01002449 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002450 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002451 status = INVALID_OPERATION;
2452 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002453 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002454
Eric Laurent8f42ea12018-08-08 09:08:25 -07002455exit:
2456
François Gaffiec005e562018-11-06 15:04:49 +01002457 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2458 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002459
Francois Gaffie716e1432019-01-14 16:58:59 +01002460 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002461 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002462 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002463
Mikhail Naganov2996f672019-04-18 12:29:59 -07002464 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002465 requestedDeviceId, attributes.source, flags,
2466 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002467 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002468 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002469
2470 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2471 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002472
Eric Laurent599c7582015-12-07 18:05:55 -08002473 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002474
2475error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002476 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002477}
2478
2479
François Gaffie11d30102018-11-02 16:09:09 +01002480audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002481 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002482 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002483 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002484 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002485 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002486{
2487 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002488 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002489 bool isSoundTrigger = false;
2490
François Gaffiec005e562018-11-06 15:04:49 +01002491 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002492 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2493 if (index >= 0) {
2494 input = mSoundTriggerSessions.valueFor(session);
2495 isSoundTrigger = true;
2496 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2497 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2498 } else {
2499 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002500 }
François Gaffiec005e562018-11-06 15:04:49 +01002501 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002502 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002503 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002504 }
2505
Carter Hsua3abb402021-10-26 11:11:20 +08002506 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2507 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2508 }
2509
Andy Hungf129b032015-04-07 13:45:50 -07002510 // find a compatible input profile (not necessarily identical in parameters)
2511 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002512 // sampling rate and flags may be updated by getInputProfile
2513 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2514 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002515 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002516 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002517 audio_input_flags_t profileFlags = flags;
2518 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002519 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002520 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002521 profileFlags);
2522 if (profile != 0) {
2523 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002524 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2525 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002526 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002527 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2528 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002529 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002530 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002531 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002532 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002533 }
Eric Laurente552edb2014-03-10 17:42:56 -07002534 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002535 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002536 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002537 if (samplingRate == 0) {
2538 samplingRate = profileSamplingRate;
2539 }
Eric Laurente552edb2014-03-10 17:42:56 -07002540
Eric Laurent322b4d22015-04-03 15:57:54 -07002541 if (profile->getModuleHandle() == 0) {
2542 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002543 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002544 }
2545
Eric Laurentec376dc2021-04-08 20:41:22 +02002546 // Reuse an already opened input if a client with the same session ID already exists
2547 // on that input
2548 for (size_t i = 0; i < mInputs.size(); i++) {
2549 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2550 if (desc->mProfile != profile) {
2551 continue;
2552 }
2553 RecordClientVector clients = desc->clientsList();
2554 for (const auto &client : clients) {
2555 if (session == client->session()) {
2556 return desc->mIoHandle;
2557 }
2558 }
2559 }
2560
Eric Laurent3974e3b2017-12-07 17:58:43 -08002561 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002562 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002563 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002564 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002565 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002566 continue;
2567 }
2568 // if sound trigger, reuse input if used by other sound trigger on same session
2569 // else
2570 // reuse input if active client app is not in IDLE state
2571 //
2572 RecordClientVector clients = desc->clientsList();
2573 bool doClose = false;
2574 for (const auto& client : clients) {
2575 if (isSoundTrigger != client->isSoundTrigger()) {
2576 continue;
2577 }
2578 if (client->isSoundTrigger()) {
2579 if (session == client->session()) {
2580 return desc->mIoHandle;
2581 }
2582 continue;
2583 }
2584 if (client->active() && client->appState() != APP_STATE_IDLE) {
2585 return desc->mIoHandle;
2586 }
2587 doClose = true;
2588 }
2589 if (doClose) {
2590 closeInput(desc->mIoHandle);
2591 } else {
2592 i++;
2593 }
2594 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002595 }
2596
Eric Laurentfe231122017-11-17 17:48:06 -08002597 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002598
Eric Laurentfe231122017-11-17 17:48:06 -08002599 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2600 lConfig.sample_rate = profileSamplingRate;
2601 lConfig.channel_mask = profileChannelMask;
2602 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002603
François Gaffie11d30102018-11-02 16:09:09 +01002604 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002605
2606 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002607 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002608 (profileSamplingRate != lConfig.sample_rate) ||
2609 !audio_formats_match(profileFormat, lConfig.format) ||
2610 (profileChannelMask != lConfig.channel_mask)) {
2611 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002612 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002613 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002614 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002615 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002616 }
Eric Laurent599c7582015-12-07 18:05:55 -08002617 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002618 }
2619
Eric Laurentc722f302014-12-10 11:21:49 -08002620 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002621
Eric Laurent599c7582015-12-07 18:05:55 -08002622 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002623 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002624
Eric Laurent599c7582015-12-07 18:05:55 -08002625 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002626}
2627
Eric Laurent4eb58f12018-12-07 16:41:02 -08002628status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002629{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002630 ALOGV("%s portId %d", __FUNCTION__, portId);
2631
2632 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2633 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002634 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002635 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002636 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002637 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002638 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002639 if (client->active()) {
2640 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2641 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002642 }
2643
Eric Laurent8f42ea12018-08-08 09:08:25 -07002644 audio_session_t session = client->session();
2645
Eric Laurent4eb58f12018-12-07 16:41:02 -08002646 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002647
Eric Laurent4eb58f12018-12-07 16:41:02 -08002648 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002649
Eric Laurent4eb58f12018-12-07 16:41:02 -08002650 status_t status = inputDesc->start();
2651 if (status != NO_ERROR) {
2652 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002653 }
Eric Laurente552edb2014-03-10 17:42:56 -07002654
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002655 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002656 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002657 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002658
Eric Laurent8f42ea12018-08-08 09:08:25 -07002659 // indicate active capture to sound trigger service if starting capture from a mic on
2660 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002661 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002662 if (device != nullptr) {
2663 status = setInputDevice(input, device, true /* force */);
2664 } else {
2665 ALOGW("%s no new input device can be found for descriptor %d",
2666 __FUNCTION__, inputDesc->getId());
2667 status = BAD_VALUE;
2668 }
Eric Laurente552edb2014-03-10 17:42:56 -07002669
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002670 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002671 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002672 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002673 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002674 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2675 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002676 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002677 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002678
François Gaffie11d30102018-11-02 16:09:09 +01002679 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2680 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002681 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002682 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002683 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002684
Eric Laurent8f42ea12018-08-08 09:08:25 -07002685 // automatically enable the remote submix output when input is started if not
2686 // used by a policy mix of type MIX_TYPE_RECORDERS
2687 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002688 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002689 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002690 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002691 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002692 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2693 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002694 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002695 if (address != "") {
2696 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2697 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002698 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002699 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002700 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002701 } else if (status != NO_ERROR) {
2702 // Restore client activity state.
2703 inputDesc->setClientActive(client, false);
2704 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002705 }
2706
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002707 ALOGV("%s input %d source = %d status = %d exit",
2708 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002709
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002710 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002711}
2712
Eric Laurent8fc147b2018-07-22 19:13:55 -07002713status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002714{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002715 ALOGV("%s portId %d", __FUNCTION__, portId);
2716
2717 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2718 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002719 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002720 return BAD_VALUE;
2721 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002722 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002723 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002724 if (!client->active()) {
2725 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002726 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002727 }
Carter Hsue6139d52021-07-08 10:30:20 +08002728 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002729 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002730
Eric Laurent8f42ea12018-08-08 09:08:25 -07002731 inputDesc->stop();
2732 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002733 auto current_source = inputDesc->source();
2734 setInputDevice(input, getNewInputDevice(inputDesc),
2735 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002736 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002737 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002738 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002739 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002740 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2741 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002742 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002743 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002744
2745 // automatically disable the remote submix output when input is stopped if not
2746 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002747 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002748 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002749 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002750 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002751 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2752 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002753 }
2754 if (address != "") {
2755 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2756 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002757 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002758 }
2759 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002760 resetInputDevice(input);
2761
2762 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2763 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002764 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2765 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002766 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002767 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002768 }
2769 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002770 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002771 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002772}
2773
Eric Laurent8fc147b2018-07-22 19:13:55 -07002774void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002775{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002776 ALOGV("%s portId %d", __FUNCTION__, portId);
2777
2778 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2779 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002780 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002781 return;
2782 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002783 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002784 audio_io_handle_t input = inputDesc->mIoHandle;
2785
Eric Laurent8f42ea12018-08-08 09:08:25 -07002786 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002787
Andy Hung39efb7a2018-09-26 15:39:28 -07002788 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002789
Andy Hung39efb7a2018-09-26 15:39:28 -07002790 if (inputDesc->getClientCount() > 0) {
2791 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002792 return;
2793 }
2794
Eric Laurent05b90f82014-08-27 15:32:29 -07002795 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002796 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002797 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002798}
2799
Eric Laurent8f42ea12018-08-08 09:08:25 -07002800void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002801{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002802 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002803
2804 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002805 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002806 }
2807}
2808
Eric Laurent8f42ea12018-08-08 09:08:25 -07002809void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2810{
2811 stopInput(portId);
2812 releaseInput(portId);
2813}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002814
Eric Laurent0dd51852019-04-19 18:18:58 -07002815void AudioPolicyManager::checkCloseInputs() {
2816 // After connecting or disconnecting an input device, close input if:
2817 // - it has no client (was just opened to check profile) OR
2818 // - none of its supported devices are connected anymore OR
2819 // - one of its clients cannot be routed to one of its supported
2820 // devices anymore. Otherwise update device selection
2821 std::vector<audio_io_handle_t> inputsToClose;
2822 for (size_t i = 0; i < mInputs.size(); i++) {
2823 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2824 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002825 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002826 inputsToClose.push_back(mInputs.keyAt(i));
2827 } else {
2828 bool close = false;
2829 for (const auto& client : input->clientsList()) {
2830 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002831 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002832 if (!input->supportedDevices().contains(device)) {
2833 close = true;
2834 break;
2835 }
2836 }
2837 if (close) {
2838 inputsToClose.push_back(mInputs.keyAt(i));
2839 } else {
2840 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2841 }
2842 }
2843 }
2844
2845 for (const audio_io_handle_t handle : inputsToClose) {
2846 ALOGV("%s closing input %d", __func__, handle);
2847 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002848 }
Eric Laurentd4692962014-05-05 18:13:44 -07002849}
2850
François Gaffie251c7f02018-11-07 10:41:08 +01002851void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002852{
2853 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002854 if (indexMin < 0 || indexMax < 0) {
2855 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2856 return;
2857 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002858 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002859
2860 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002861 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2862 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002863 continue;
2864 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002865 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002866 }
Eric Laurente552edb2014-03-10 17:42:56 -07002867}
2868
Eric Laurente0720872014-03-11 09:30:41 -07002869status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002870 int index,
2871 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002872{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002873 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002874 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2875 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2876 return NO_ERROR;
2877 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002878 ALOGV("%s: stream %s attributes=%s", __func__,
2879 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002880 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002881}
2882
Eric Laurente0720872014-03-11 09:30:41 -07002883status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002884 int *index,
2885 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002886{
François Gaffiec005e562018-11-06 15:04:49 +01002887 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2888 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002889 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002890 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002891 deviceTypes = mEngine->getOutputDevicesForStream(
2892 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002893 }
jiabin9a3361e2019-10-01 09:38:30 -07002894 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002895}
2896
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002897status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002898 int index,
2899 audio_devices_t device)
2900{
2901 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002902 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2903 if (group == VOLUME_GROUP_NONE) {
2904 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002905 return BAD_VALUE;
2906 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002907 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002908 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002909 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002910 VolumeSource vs = toVolumeSource(group);
2911 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2912
2913 status = setVolumeCurveIndex(index, device, curves);
2914 if (status != NO_ERROR) {
2915 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2916 return status;
2917 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002918
jiabin9a3361e2019-10-01 09:38:30 -07002919 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002920 auto curCurvAttrs = curves.getAttributes();
2921 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2922 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002923 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002924 } else if (!curves.getStreamTypes().empty()) {
2925 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002926 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002927 } else {
2928 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2929 return BAD_VALUE;
2930 }
jiabin9a3361e2019-10-01 09:38:30 -07002931 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2932 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002933
François Gaffiecfe17322018-11-07 13:41:29 +01002934 // update volume on all outputs and streams matching the following:
2935 // - The requested stream (or a stream matching for volume control) is active on the output
2936 // - The device (or devices) selected by the engine for this stream includes
2937 // the requested device
2938 // - For non default requested device, currently selected device on the output is either the
2939 // requested device or one of the devices selected by the engine for this stream
2940 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2941 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002942 for (size_t i = 0; i < mOutputs.size(); i++) {
2943 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002944 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002945
jiabin9a3361e2019-10-01 09:38:30 -07002946 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2947 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002948 }
François Gaffieed91f582020-01-31 10:35:37 +01002949 if (!(desc->isActive(vs) || isInCall())) {
2950 continue;
2951 }
2952 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2953 curDevices.find(device) == curDevices.end()) {
2954 continue;
2955 }
2956 bool applyVolume = false;
2957 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2958 curSrcDevices.insert(device);
2959 applyVolume = (curSrcDevices.find(
2960 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2961 } else {
2962 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2963 }
2964 if (!applyVolume) {
2965 continue; // next output
2966 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002967 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2968 // If a higher priority strategy is active, and the output is routed to a device with a
2969 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002970 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002971 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02002972 // If the volume source is active with higher priority source, ensure at least Sw Muted
2973 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002974 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2975 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2976 false /*preferredDevice*/);
2977 if (activeClients.empty()) {
2978 continue;
2979 }
2980 bool isPreempted = false;
2981 bool isHigherPriority = productStrategy < strategy;
2982 for (const auto &client : activeClients) {
2983 if (isHigherPriority && (client->volumeSource() != vs)) {
2984 ALOGV("%s: Strategy=%d (\nrequester:\n"
2985 " group %d, volumeGroup=%d attributes=%s)\n"
2986 " higher priority source active:\n"
2987 " volumeGroup=%d attributes=%s) \n"
2988 " on output %zu, bailing out", __func__, productStrategy,
2989 group, group, toString(attributes).c_str(),
2990 client->volumeSource(), toString(client->attributes()).c_str(), i);
2991 applyVolume = false;
2992 isPreempted = true;
2993 break;
2994 }
2995 // However, continue for loop to ensure no higher prio clients running on output
2996 if (client->volumeSource() == vs) {
2997 applyVolume = true;
2998 }
2999 }
3000 if (isPreempted || applyVolume) {
3001 break;
3002 }
3003 }
3004 if (!applyVolume) {
3005 continue; // next output
3006 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003007 }
François Gaffieed91f582020-01-31 10:35:37 +01003008 //FIXME: workaround for truncated touch sounds
3009 // delayed volume change for system stream to be removed when the problem is
3010 // handled by system UI
3011 status_t volStatus = checkAndSetVolume(
3012 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003013 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003014 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3015 if (volStatus != NO_ERROR) {
3016 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003017 }
3018 }
François Gaffiecfe17322018-11-07 13:41:29 +01003019 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3020 return status;
3021}
3022
François Gaffieaaac0fd2018-11-22 17:56:39 +01003023status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003024 audio_devices_t device,
3025 IVolumeCurves &volumeCurves)
3026{
3027 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3028 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003029 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3030 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003031 (index > volumeCurves.getVolumeIndexMax())) {
3032 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3033 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3034 return BAD_VALUE;
3035 }
3036 if (!audio_is_output_device(device)) {
3037 return BAD_VALUE;
3038 }
3039
3040 // Force max volume if stream cannot be muted
3041 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3042
François Gaffieaaac0fd2018-11-22 17:56:39 +01003043 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003044 volumeCurves.addCurrentVolumeIndex(device, index);
3045 return NO_ERROR;
3046}
3047
3048status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3049 int &index,
3050 audio_devices_t device)
3051{
3052 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3053 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003054 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003055 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003056 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3057 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003058 }
jiabin9a3361e2019-10-01 09:38:30 -07003059 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003060}
3061
3062status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3063 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003064 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003065{
jiabin9a3361e2019-10-01 09:38:30 -07003066 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003067 return BAD_VALUE;
3068 }
jiabin9a3361e2019-10-01 09:38:30 -07003069 index = curves.getVolumeIndex(deviceTypes);
3070 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003071 return NO_ERROR;
3072}
3073
3074status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3075 int &index)
3076{
3077 index = getVolumeCurves(attr).getVolumeIndexMin();
3078 return NO_ERROR;
3079}
3080
3081status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3082 int &index)
3083{
3084 index = getVolumeCurves(attr).getVolumeIndexMax();
3085 return NO_ERROR;
3086}
3087
Eric Laurent36829f92017-04-07 19:04:42 -07003088audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003089{
3090 // select one output among several suitable for global effects.
3091 // The priority is as follows:
3092 // 1: An offloaded output. If the effect ends up not being offloadable,
3093 // AudioFlinger will invalidate the track and the offloaded output
3094 // will be closed causing the effect to be moved to a PCM output.
3095 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003096 // 3: The primary output
3097 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003098
François Gaffiec005e562018-11-06 15:04:49 +01003099 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3100 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003101 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003102
Eric Laurent36829f92017-04-07 19:04:42 -07003103 if (outputs.size() == 0) {
3104 return AUDIO_IO_HANDLE_NONE;
3105 }
Eric Laurente552edb2014-03-10 17:42:56 -07003106
Eric Laurent36829f92017-04-07 19:04:42 -07003107 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3108 bool activeOnly = true;
3109
3110 while (output == AUDIO_IO_HANDLE_NONE) {
3111 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3112 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3113 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3114
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003115 for (audio_io_handle_t output : outputs) {
3116 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003117 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003118 continue;
3119 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003120 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3121 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003122 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003123 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003124 }
3125 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003126 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003127 }
3128 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003129 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003130 }
3131 }
3132 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3133 output = outputOffloaded;
3134 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3135 output = outputDeepBuffer;
3136 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3137 output = outputPrimary;
3138 } else {
3139 output = outputs[0];
3140 }
3141 activeOnly = false;
3142 }
3143
3144 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003145 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003146 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3147 mMusicEffectOutput = output;
3148 }
3149
3150 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003151 return output;
3152}
3153
Eric Laurent36829f92017-04-07 19:04:42 -07003154audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3155{
3156 return selectOutputForMusicEffects();
3157}
3158
Eric Laurente0720872014-03-11 09:30:41 -07003159status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003160 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003161 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003162 int session,
3163 int id)
3164{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003165 if (session != AUDIO_SESSION_DEVICE) {
3166 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003167 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003168 index = mInputs.indexOfKey(io);
3169 if (index < 0) {
3170 ALOGW("registerEffect() unknown io %d", io);
3171 return INVALID_OPERATION;
3172 }
Eric Laurente552edb2014-03-10 17:42:56 -07003173 }
3174 }
François Gaffiec005e562018-11-06 15:04:49 +01003175 return mEffects.registerEffect(desc, io, session, id,
3176 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3177 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003178}
3179
Eric Laurentc241b0d2018-11-28 09:08:49 -08003180status_t AudioPolicyManager::unregisterEffect(int id)
3181{
3182 if (mEffects.getEffect(id) == nullptr) {
3183 return INVALID_OPERATION;
3184 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003185 if (mEffects.isEffectEnabled(id)) {
3186 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3187 setEffectEnabled(id, false);
3188 }
3189 return mEffects.unregisterEffect(id);
3190}
3191
3192status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3193{
3194 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3195 if (effect == nullptr) {
3196 return INVALID_OPERATION;
3197 }
3198
3199 status_t status = mEffects.setEffectEnabled(id, enabled);
3200 if (status == NO_ERROR) {
3201 mInputs.trackEffectEnabled(effect, enabled);
3202 }
3203 return status;
3204}
3205
Eric Laurent6c796322019-04-09 14:13:17 -07003206
3207status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3208{
3209 mEffects.moveEffects(ids, io);
3210 return NO_ERROR;
3211}
3212
Eric Laurentc75307b2015-03-17 15:29:32 -07003213bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3214{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003215 auto vs = toVolumeSource(stream, false);
3216 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003217}
3218
3219bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3220{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003221 auto vs = toVolumeSource(stream, false);
3222 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003223}
3224
Eric Laurente0720872014-03-11 09:30:41 -07003225bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003226{
3227 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003228 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003229 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003230 return true;
3231 }
3232 }
3233 return false;
3234}
3235
Eric Laurent275e8e92014-11-30 15:14:47 -08003236// Register a list of custom mixes with their attributes and format.
3237// When a mix is registered, corresponding input and output profiles are
3238// added to the remote submix hw module. The profile contains only the
3239// parameters (sampling rate, format...) specified by the mix.
3240// The corresponding input remote submix device is also connected.
3241//
3242// When a remote submix device is connected, the address is checked to select the
3243// appropriate profile and the corresponding input or output stream is opened.
3244//
3245// When capture starts, getInputForAttr() will:
3246// - 1 look for a mix matching the address passed in attribtutes tags if any
3247// - 2 if none found, getDeviceForInputSource() will:
3248// - 2.1 look for a mix matching the attributes source
3249// - 2.2 if none found, default to device selection by policy rules
3250// At this time, the corresponding output remote submix device is also connected
3251// and active playback use cases can be transferred to this mix if needed when reconnecting
3252// after AudioTracks are invalidated
3253//
3254// When playback starts, getOutputForAttr() will:
3255// - 1 look for a mix matching the address passed in attribtutes tags if any
3256// - 2 if none found, look for a mix matching the attributes usage
3257// - 3 if none found, default to device and output selection by policy rules.
3258
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003259status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003260{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003261 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3262 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003263 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003264 sp<HwModule> rSubmixModule;
3265 // examine each mix's route type
3266 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003267 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003268 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3269 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3270 ALOGE("Unsupported Policy Mix %zu of %zu: "
3271 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3272 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003273 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003274 break;
3275 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003276 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3277 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003278 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003279 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3280 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003281 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003282 rSubmixModule = mHwModules.getModuleFromName(
3283 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3284 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003285 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003286 i);
3287 res = INVALID_OPERATION;
3288 break;
3289 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003290 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003291
Eric Laurent97ac8712018-07-27 18:59:02 -07003292 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003293 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003294 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003295 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003296 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3297 } else {
3298 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3299 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003300 }
François Gaffie036e1e92015-03-19 10:16:24 +01003301
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003302 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003303 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003304 res = INVALID_OPERATION;
3305 break;
3306 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003307 audio_config_t outputConfig = mix.mFormat;
3308 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003309 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3310 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003311 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3312 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003313 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003314 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003315 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003316 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003317
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003318 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003319 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3320 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3321 ALOGE("Failed to set remote submix device available, type %u, address %s",
3322 mix.mDeviceType, address.string());
3323 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003324 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003325 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3326 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003327 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003328 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003329 i, mixes.size(), type, address.string());
3330
3331 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3332 mix.mDeviceType, mix.mDeviceAddress,
3333 String8(), AUDIO_FORMAT_DEFAULT);
3334 if (device == nullptr) {
3335 res = INVALID_OPERATION;
3336 break;
3337 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003338
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003339 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003340 // First try to find an already opened output supporting the device
3341 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003342 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003343
Eric Laurentc529cf62020-04-17 18:19:10 -07003344 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003345 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003346 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3347 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003348 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003349 } else {
3350 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003351 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003352 }
3353 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003354 // If no output found, try to find a direct output profile supporting the device
3355 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3356 sp<HwModule> module = mHwModules[i];
3357 for (size_t j = 0;
3358 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3359 j++) {
3360 sp<IOProfile> profile = module->getOutputProfiles()[j];
3361 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3362 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3363 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3364 address.string());
3365 res = INVALID_OPERATION;
3366 } else {
3367 foundOutput = true;
3368 }
3369 }
3370 }
3371 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003372 if (res != NO_ERROR) {
3373 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003374 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003375 res = INVALID_OPERATION;
3376 break;
3377 } else if (!foundOutput) {
3378 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003379 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003380 res = INVALID_OPERATION;
3381 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003382 } else {
3383 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003384 }
Eric Laurentc722f302014-12-10 11:21:49 -08003385 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003386 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003387 if (res != NO_ERROR) {
3388 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003389 } else if (checkOutputs) {
3390 checkForDeviceAndOutputChanges();
3391 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003392 }
3393 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003394}
3395
3396status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3397{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003398 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003399 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003400 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003401 sp<HwModule> rSubmixModule;
3402 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003403 for (const auto& mix : mixes) {
3404 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003405
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003406 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003407 rSubmixModule = mHwModules.getModuleFromName(
3408 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3409 if (rSubmixModule == 0) {
3410 res = INVALID_OPERATION;
3411 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003412 }
3413 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003414
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003415 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003416
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003417 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003418 res = INVALID_OPERATION;
3419 continue;
3420 }
3421
Kevin Rocard04ed0462019-05-02 17:53:24 -07003422 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3423 if (getDeviceConnectionState(device, address.string()) ==
3424 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3425 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3426 address.string(), "remote-submix",
3427 AUDIO_FORMAT_DEFAULT);
3428 if (res != OK) {
3429 ALOGE("Error making RemoteSubmix device unavailable for mix "
3430 "with type %d, address %s", device, address.string());
3431 }
3432 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003433 }
jiabin5740f082019-08-19 15:08:30 -07003434 rSubmixModule->removeOutputProfile(address.c_str());
3435 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003436
Kevin Rocard153f92d2018-12-18 18:33:28 -08003437 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003438 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003439 res = INVALID_OPERATION;
3440 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003441 } else {
3442 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003443 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003444 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003445 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003446 if (res == NO_ERROR && checkOutputs) {
3447 checkForDeviceAndOutputChanges();
3448 updateCallAndOutputRouting();
3449 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003450 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003451}
3452
Mikhail Naganov100f0122018-11-29 11:22:16 -08003453void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3454{
3455 size_t i = 0;
3456 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3457 for (const auto& fmt : mManualSurroundFormats) {
3458 if (i++ != 0) dst->append(", ");
3459 std::string sfmt;
3460 FormatConverter::toString(fmt, sfmt);
3461 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3462 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3463 }
3464}
3465
Eric Laurentc529cf62020-04-17 18:19:10 -07003466// Returns true if all devices types match the predicate and are supported by one HW module
3467bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003468 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003469 std::function<bool(audio_devices_t)> predicate,
3470 const char *context) {
3471 for (size_t i = 0; i < devices.size(); i++) {
3472 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003473 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003474 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003475 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003476 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003477 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003478 return false;
3479 }
3480 }
3481 return true;
3482}
3483
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003484status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003485 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003486 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003487 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3488 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003489 }
3490 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003491 if (res != NO_ERROR) {
3492 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3493 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003494 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003495
3496 checkForDeviceAndOutputChanges();
3497 updateCallAndOutputRouting();
3498
3499 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003500}
3501
3502status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3503 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003504 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3505 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003506 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003507 __FUNCTION__, uid);
3508 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003509 }
3510
Eric Laurentc529cf62020-04-17 18:19:10 -07003511 checkForDeviceAndOutputChanges();
3512 updateCallAndOutputRouting();
3513
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003514 return res;
3515}
3516
Eric Laurent2517af32020-11-25 15:31:27 +01003517
jiabin0a488932020-08-07 17:32:40 -07003518status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3519 device_role_t role,
3520 const AudioDeviceTypeAddrVector &devices) {
3521 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3522 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003523
Eric Laurentc529cf62020-04-17 18:19:10 -07003524 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003525 return BAD_VALUE;
3526 }
jiabin0a488932020-08-07 17:32:40 -07003527 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003528 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003529 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3530 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003531 return status;
3532 }
3533
3534 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003535
3536 bool forceVolumeReeval = false;
3537 // FIXME: workaround for truncated touch sounds
3538 // to be removed when the problem is handled by system UI
3539 uint32_t delayMs = 0;
3540 if (strategy == mCommunnicationStrategy) {
3541 forceVolumeReeval = true;
3542 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3543 updateInputRouting();
3544 }
3545 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003546
3547 return NO_ERROR;
3548}
3549
3550void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3551{
3552 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003553 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003554 // Only apply special touch sound delay once
3555 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003556 }
3557 for (size_t i = 0; i < mOutputs.size(); i++) {
3558 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3559 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3560 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3561 // As done in setDeviceConnectionState, we could also fix default device issue by
3562 // preventing the force re-routing in case of default dev that distinguishes on address.
3563 // Let's give back to engine full device choice decision however.
3564 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003565 // Only apply special touch sound delay once
3566 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003567 }
3568 if (forceVolumeReeval && !newDevices.isEmpty()) {
3569 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3570 }
3571 }
3572}
3573
Eric Laurent2517af32020-11-25 15:31:27 +01003574void AudioPolicyManager::updateInputRouting() {
3575 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303576 // Skip for hotword recording as the input device switch
3577 // is handled within sound trigger HAL
3578 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3579 continue;
3580 }
Eric Laurent2517af32020-11-25 15:31:27 +01003581 auto newDevice = getNewInputDevice(activeDesc);
3582 // Force new input selection if the new device can not be reached via current input
3583 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3584 setInputDevice(activeDesc->mIoHandle, newDevice);
3585 } else {
3586 closeInput(activeDesc->mIoHandle);
3587 }
3588 }
3589}
3590
jiabin0a488932020-08-07 17:32:40 -07003591status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3592 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003593{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003594 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003595
jiabin0a488932020-08-07 17:32:40 -07003596 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003597 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003598 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3599 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003600 return status;
3601 }
3602
3603 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003604
3605 bool forceVolumeReeval = false;
3606 // FIXME: workaround for truncated touch sounds
3607 // to be removed when the problem is handled by system UI
3608 uint32_t delayMs = 0;
3609 if (strategy == mCommunnicationStrategy) {
3610 forceVolumeReeval = true;
3611 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3612 updateInputRouting();
3613 }
3614 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003615
3616 return NO_ERROR;
3617}
3618
jiabin0a488932020-08-07 17:32:40 -07003619status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3620 device_role_t role,
3621 AudioDeviceTypeAddrVector &devices) {
3622 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003623}
3624
Jiabin Huang3b98d322020-09-03 17:54:16 +00003625status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3626 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3627 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3628 dumpAudioDeviceTypeAddrVector(devices).c_str());
3629
Mikhail Naganov55773032020-10-01 15:08:13 -07003630 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003631 return BAD_VALUE;
3632 }
3633 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3634 ALOGW_IF(status != NO_ERROR,
3635 "Engine could not set preferred devices %s for audio source %d role %d",
3636 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3637
3638 return status;
3639}
3640
3641status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3642 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3643 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3644 dumpAudioDeviceTypeAddrVector(devices).c_str());
3645
Mikhail Naganov55773032020-10-01 15:08:13 -07003646 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003647 return BAD_VALUE;
3648 }
3649 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3650 ALOGW_IF(status != NO_ERROR,
3651 "Engine could not add preferred devices %s for audio source %d role %d",
3652 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3653
Eric Laurent2517af32020-11-25 15:31:27 +01003654 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003655 return status;
3656}
3657
3658status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3659 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3660{
3661 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3662 dumpAudioDeviceTypeAddrVector(devices).c_str());
3663
Mikhail Naganov55773032020-10-01 15:08:13 -07003664 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003665 return BAD_VALUE;
3666 }
3667
3668 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3669 audioSource, role, devices);
3670 ALOGW_IF(status != NO_ERROR,
3671 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3672
Eric Laurent2517af32020-11-25 15:31:27 +01003673 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003674 return status;
3675}
3676
3677status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3678 device_role_t role) {
3679 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3680
3681 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3682 ALOGW_IF(status != NO_ERROR,
3683 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3684
Eric Laurent2517af32020-11-25 15:31:27 +01003685 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003686 return status;
3687}
3688
3689status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3690 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3691 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3692}
3693
Oscar Azucena90e77632019-11-27 17:12:28 -08003694status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003695 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003696 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003697 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3698 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003699 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003700 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3701 if (status != NO_ERROR) {
3702 ALOGE("%s() could not set device affinity for userId %d",
3703 __FUNCTION__, userId);
3704 return status;
3705 }
3706
3707 // reevaluate outputs for all devices
3708 checkForDeviceAndOutputChanges();
3709 updateCallAndOutputRouting();
3710
3711 return NO_ERROR;
3712}
3713
3714status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003715 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003716 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3717 if (status != NO_ERROR) {
3718 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3719 __FUNCTION__, userId);
3720 return status;
3721 }
3722
3723 // reevaluate outputs for all devices
3724 checkForDeviceAndOutputChanges();
3725 updateCallAndOutputRouting();
3726
3727 return NO_ERROR;
3728}
3729
Andy Hungc29d82b2018-10-05 12:23:17 -07003730void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003731{
Andy Hungc29d82b2018-10-05 12:23:17 -07003732 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003733 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003734 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003735 std::string stateLiteral;
3736 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003737 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003738 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3739 "communications", "media", "record", "dock", "system",
3740 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3741 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3742 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003743 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3744 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3745 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3746 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3747 dst->append(" (MANUAL: ");
3748 dumpManualSurroundFormats(dst);
3749 dst->append(")");
3750 }
3751 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003752 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003753 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3754 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003755 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003756 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003757
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003758 dst->append("\n");
3759 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3760 dst->append("\n");
3761 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003762 mHwModulesAll.dump(dst);
3763 mOutputs.dump(dst);
3764 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003765 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003766 mAudioPatches.dump(dst);
3767 mPolicyMixes.dump(dst);
3768 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003769
Kevin Rocardb99cc752019-03-21 20:52:24 -07003770 dst->appendFormat(" AllowedCapturePolicies:\n");
3771 for (auto& policy : mAllowedCapturePolicies) {
3772 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3773 }
3774
François Gaffiec005e562018-11-06 15:04:49 +01003775 dst->appendFormat("\nPolicy Engine dump:\n");
3776 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003777}
3778
3779status_t AudioPolicyManager::dump(int fd)
3780{
3781 String8 result;
3782 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003783 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003784 return NO_ERROR;
3785}
3786
Kevin Rocardb99cc752019-03-21 20:52:24 -07003787status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3788{
3789 mAllowedCapturePolicies[uid] = capturePolicy;
3790 return NO_ERROR;
3791}
3792
Eric Laurente552edb2014-03-10 17:42:56 -07003793// This function checks for the parameters which can be offloaded.
3794// This can be enhanced depending on the capability of the DSP and policy
3795// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003796audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003797{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003798 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003799 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003800 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003801 offloadInfo.format,
3802 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3803 offloadInfo.has_video);
3804
jiabin2b9d5a12021-12-10 01:06:29 +00003805 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003806 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003807 }
3808
3809 // See if there is a profile to support this.
3810 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003811 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003812 offloadInfo.sample_rate,
3813 offloadInfo.format,
3814 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003815 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3816 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003817 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3818 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3819 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003820 if (profile == nullptr) {
3821 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3822 }
3823 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3824 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3825 }
3826 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003827}
3828
Michael Chana94fbb22018-04-24 14:31:19 +10003829bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3830 const audio_attributes_t& attributes) {
3831 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003832 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003833 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3834 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003835 config.sample_rate,
3836 config.format,
3837 config.channel_mask,
3838 output_flags,
3839 true /* directOnly */);
3840 ALOGV("%s() profile %sfound with name: %s, "
3841 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3842 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003843 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003844 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003845
3846 // also try the MSD module if compatible profile not found
3847 if (profile == nullptr) {
3848 profile = getMsdProfileForOutput(outputDevices,
3849 config.sample_rate,
3850 config.format,
3851 config.channel_mask,
3852 output_flags,
3853 true /* directOnly */);
3854 ALOGV("%s() MSD profile %sfound with name: %s, "
3855 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3856 __FUNCTION__, profile != 0 ? "" : "NOT ",
3857 (profile != 0 ? profile->getTagName().c_str() : "null"),
3858 config.sample_rate, config.format, config.channel_mask, output_flags);
3859 }
3860 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003861}
3862
jiabin2b9d5a12021-12-10 01:06:29 +00003863bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3864 bool durationIgnored) {
3865 if (mMasterMono) {
3866 return false; // no offloading if mono is set.
3867 }
3868
3869 // Check if offload has been disabled
3870 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3871 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3872 return false;
3873 }
3874
3875 // Check if stream type is music, then only allow offload as of now.
3876 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3877 {
3878 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3879 return false;
3880 }
3881
3882 //TODO: enable audio offloading with video when ready
3883 const bool allowOffloadWithVideo =
3884 property_get_bool("audio.offload.video", false /* default_value */);
3885 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3886 ALOGV("%s: has_video == true, returning false", __func__);
3887 return false;
3888 }
3889
3890 //If duration is less than minimum value defined in property, return false
3891 const int min_duration_secs = property_get_int32(
3892 "audio.offload.min.duration.secs", -1 /* default_value */);
3893 if (!durationIgnored) {
3894 if (min_duration_secs >= 0) {
3895 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3896 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3897 __func__, min_duration_secs);
3898 return false;
3899 }
3900 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3901 ALOGV("%s: Offload denied by duration < default min(=%u)",
3902 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3903 return false;
3904 }
3905 }
3906
3907 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3908 // creating an offloaded track and tearing it down immediately after start when audioflinger
3909 // detects there is an active non offloadable effect.
3910 // FIXME: We should check the audio session here but we do not have it in this context.
3911 // This may prevent offloading in rare situations where effects are left active by apps
3912 // in the background.
3913 if (mEffects.isNonOffloadableEffectEnabled()) {
3914 return false;
3915 }
3916
3917 return true;
3918}
3919
3920audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
3921 const audio_config_t *config) {
3922 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
3923 offloadInfo.format = config->format;
3924 offloadInfo.sample_rate = config->sample_rate;
3925 offloadInfo.channel_mask = config->channel_mask;
3926 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
3927 offloadInfo.has_video = false;
3928 offloadInfo.is_streaming = false;
3929 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
3930
3931 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
3932 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3933 audio_flags_to_audio_output_flags(attr->flags, &flags);
3934 // only retain flags that will drive compressed offload or passthrough
3935 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
3936 if (offloadPossible) {
3937 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
3938 }
3939 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
3940
jiabinc8f7dfc2022-01-06 18:42:08 +00003941 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00003942 for (const auto& hwModule : mHwModules) {
3943 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00003944 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00003945 config->sample_rate, nullptr /*updatedSamplingRate*/,
3946 config->format, nullptr /*updatedFormat*/,
3947 config->channel_mask, nullptr /*updatedChannelMask*/,
3948 flags)) {
3949 continue;
3950 }
3951 // reject profiles not corresponding to a device currently available
3952 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
3953 continue;
3954 }
3955 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
3956 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00003957 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00003958 != AUDIO_DIRECT_NOT_SUPPORTED) {
3959 // Already reports offload gapless supported. No need to report offload support.
3960 continue;
3961 }
3962 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
3963 != AUDIO_OUTPUT_FLAG_NONE) {
3964 // If offload gapless is reported, no need to report offload support.
3965 directMode = (audio_direct_mode_t) ((directMode &
3966 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
3967 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
3968 } else {
3969 directMode = (audio_direct_mode_t)(directMode |AUDIO_DIRECT_OFFLOAD_SUPPORTED);
3970 }
3971 } else {
3972 directMode = (audio_direct_mode_t) (directMode |
3973 AUDIO_DIRECT_BITSTREAM_SUPPORTED);
3974 }
3975 }
3976 }
3977 return directMode;
3978}
3979
Dorin Drimusf2196d82022-01-03 12:11:18 +01003980status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
3981 AudioProfileVector& audioProfilesVector) {
3982 AudioDeviceTypeAddrVector devices;
3983 status_t status = getDevicesForAttributes(*attr, &devices);
3984 if (status != OK) {
3985 return status;
3986 }
3987 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
3988 if (devices.empty()) {
3989 return OK; // no output devices for the attributes
3990 }
3991
3992 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01003993 // the MSD module checks for different conditions
3994 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
3995 continue;
3996 }
3997 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
3998 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01003999 continue;
4000 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004001 // allow only profiles that support all the available and routed devices
4002 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004003 != devices.size()) {
4004 continue;
4005 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004006 audioProfilesVector.addAllValidProfiles(
4007 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004008 }
4009 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004010
4011 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4012 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4013 if (msdModule != nullptr) {
4014 if (msdHasPatchesToAllDevices(devices)) {
4015 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4016 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4017 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4018 continue;
4019 }
4020 audioProfilesVector.addAllValidProfiles(
4021 outputProfile->asAudioPort()->getAudioProfiles());
4022 }
4023 } else {
4024 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4025 }
4026 }
4027
Dorin Drimusf2196d82022-01-03 12:11:18 +01004028 return NO_ERROR;
4029}
4030
Eric Laurent6a94d692014-05-20 11:18:06 -07004031status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4032 audio_port_type_t type,
4033 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004034 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004035 unsigned int *generation)
4036{
jiabin19cdba52020-11-24 11:28:58 -08004037 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4038 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004039 return BAD_VALUE;
4040 }
4041 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004042 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004043 *num_ports = 0;
4044 }
4045
4046 size_t portsWritten = 0;
4047 size_t portsMax = *num_ports;
4048 *num_ports = 0;
4049 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004050 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4051 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004052 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004053 for (const auto& dev : mAvailableOutputDevices) {
4054 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004055 continue;
4056 }
4057 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004058 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004059 }
4060 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004061 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004062 }
4063 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004064 for (const auto& dev : mAvailableInputDevices) {
4065 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004066 continue;
4067 }
4068 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004069 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004070 }
4071 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004072 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004073 }
4074 }
4075 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4076 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4077 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4078 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4079 }
4080 *num_ports += mInputs.size();
4081 }
4082 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004083 size_t numOutputs = 0;
4084 for (size_t i = 0; i < mOutputs.size(); i++) {
4085 if (!mOutputs[i]->isDuplicated()) {
4086 numOutputs++;
4087 if (portsWritten < portsMax) {
4088 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4089 }
4090 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004091 }
Eric Laurent84c70242014-06-23 08:46:27 -07004092 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004093 }
4094 }
4095 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004096 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004097 return NO_ERROR;
4098}
4099
jiabin19cdba52020-11-24 11:28:58 -08004100status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004101{
Eric Laurent99fcae42018-05-17 16:59:18 -07004102 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4103 return BAD_VALUE;
4104 }
4105 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4106 if (dev != 0) {
4107 dev->toAudioPort(port);
4108 return NO_ERROR;
4109 }
4110 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4111 if (dev != 0) {
4112 dev->toAudioPort(port);
4113 return NO_ERROR;
4114 }
4115 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4116 if (out != 0) {
4117 out->toAudioPort(port);
4118 return NO_ERROR;
4119 }
4120 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4121 if (in != 0) {
4122 in->toAudioPort(port);
4123 return NO_ERROR;
4124 }
4125 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004126}
4127
François Gaffieafd4cea2019-11-18 15:50:22 +01004128status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4129 audio_patch_handle_t *handle,
4130 uid_t uid, uint32_t delayMs,
4131 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07004132{
François Gaffieafd4cea2019-11-18 15:50:22 +01004133 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004134 if (handle == NULL || patch == NULL) {
4135 return BAD_VALUE;
4136 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004137 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004138
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004139 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004140 return BAD_VALUE;
4141 }
4142 // only one source per audio patch supported for now
4143 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004144 return INVALID_OPERATION;
4145 }
Eric Laurent874c42872014-08-08 15:13:39 -07004146
4147 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004148 return INVALID_OPERATION;
4149 }
Eric Laurent874c42872014-08-08 15:13:39 -07004150 for (size_t i = 0; i < patch->num_sinks; i++) {
4151 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4152 return INVALID_OPERATION;
4153 }
4154 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004155
4156 sp<AudioPatch> patchDesc;
4157 ssize_t index = mAudioPatches.indexOfKey(*handle);
4158
François Gaffieafd4cea2019-11-18 15:50:22 +01004159 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4160 patch->sources[0].role,
4161 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004162#if LOG_NDEBUG == 0
4163 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004164 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4165 patch->sinks[i].role,
4166 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004167 }
4168#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004169
4170 if (index >= 0) {
4171 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004172 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4173 __func__, mUidCached, patchDesc->getUid(), uid);
4174 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004175 return INVALID_OPERATION;
4176 }
4177 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004178 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004179 }
4180
4181 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004182 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004183 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004184 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004185 return BAD_VALUE;
4186 }
Eric Laurent84c70242014-06-23 08:46:27 -07004187 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4188 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004189 if (patchDesc != 0) {
4190 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004191 ALOGV("%s source id differs for patch current id %d new id %d",
4192 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004193 return BAD_VALUE;
4194 }
4195 }
Eric Laurent874c42872014-08-08 15:13:39 -07004196 DeviceVector devices;
4197 for (size_t i = 0; i < patch->num_sinks; i++) {
4198 // Only support mix to devices connection
4199 // TODO add support for mix to mix connection
4200 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004201 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004202 return INVALID_OPERATION;
4203 }
4204 sp<DeviceDescriptor> devDesc =
4205 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4206 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004207 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004208 return BAD_VALUE;
4209 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004210
François Gaffie11d30102018-11-02 16:09:09 +01004211 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004212 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004213 NULL, // updatedSamplingRate
4214 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004215 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004216 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004217 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004218 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004219 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004220 return INVALID_OPERATION;
4221 }
4222 devices.add(devDesc);
4223 }
4224 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004225 return INVALID_OPERATION;
4226 }
Eric Laurent874c42872014-08-08 15:13:39 -07004227
Eric Laurent6a94d692014-05-20 11:18:06 -07004228 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004229 ALOGV("%s setting device %s on output %d",
4230 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004231 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004232 index = mAudioPatches.indexOfKey(*handle);
4233 if (index >= 0) {
4234 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004235 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004236 }
4237 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004238 patchDesc->setUid(uid);
4239 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004240 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004241 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004242 return INVALID_OPERATION;
4243 }
4244 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4245 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4246 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004247 // only one sink supported when connecting an input device to a mix
4248 if (patch->num_sinks > 1) {
4249 return INVALID_OPERATION;
4250 }
François Gaffie53615e22015-03-19 09:24:12 +01004251 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004252 if (inputDesc == NULL) {
4253 return BAD_VALUE;
4254 }
4255 if (patchDesc != 0) {
4256 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4257 return BAD_VALUE;
4258 }
4259 }
François Gaffie11d30102018-11-02 16:09:09 +01004260 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004261 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004262 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004263 return BAD_VALUE;
4264 }
4265
François Gaffie11d30102018-11-02 16:09:09 +01004266 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004267 patch->sinks[0].sample_rate,
4268 NULL, /*updatedSampleRate*/
4269 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004270 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004271 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004272 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004273 // FIXME for the parameter type,
4274 // and the NONE
4275 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004276 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004277 return INVALID_OPERATION;
4278 }
4279 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004280 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004281 device->toString().c_str(), inputDesc->mIoHandle);
4282 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004283 index = mAudioPatches.indexOfKey(*handle);
4284 if (index >= 0) {
4285 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004286 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004287 }
4288 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004289 patchDesc->setUid(uid);
4290 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004291 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004292 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004293 return INVALID_OPERATION;
4294 }
4295 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4296 // device to device connection
4297 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004298 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004299 return BAD_VALUE;
4300 }
4301 }
François Gaffie11d30102018-11-02 16:09:09 +01004302 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004303 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004304 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004305 return BAD_VALUE;
4306 }
Eric Laurent874c42872014-08-08 15:13:39 -07004307
Eric Laurent6a94d692014-05-20 11:18:06 -07004308 //update source and sink with our own data as the data passed in the patch may
4309 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004310 PatchBuilder patchBuilder;
4311 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004312
4313 // if first sink is to MSD, establish single MSD patch
4314 if (getMsdAudioOutDevices().contains(
4315 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4316 ALOGV("%s patching to MSD", __FUNCTION__);
4317 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4318 goto installPatch;
4319 }
4320
François Gaffieafd4cea2019-11-18 15:50:22 +01004321 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4322 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004323
Eric Laurent874c42872014-08-08 15:13:39 -07004324 for (size_t i = 0; i < patch->num_sinks; i++) {
4325 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004326 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004327 return INVALID_OPERATION;
4328 }
François Gaffie11d30102018-11-02 16:09:09 +01004329 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004330 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004331 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004332 return BAD_VALUE;
4333 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004334 audio_port_config sinkPortConfig = {};
4335 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4336 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004337
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004338 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4339 // volume management purpose (tracking activity)
4340 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4341 // in config XML to reach the sink so that is can be declared as available.
4342 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4343 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4344 if (sourceDesc != nullptr) {
4345 // take care of dynamic routing for SwOutput selection,
4346 audio_attributes_t attributes = sourceDesc->attributes();
4347 audio_stream_type_t stream = sourceDesc->stream();
4348 audio_attributes_t resultAttr;
4349 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4350 config.sample_rate = sourceDesc->config().sample_rate;
4351 config.channel_mask = sourceDesc->config().channel_mask;
4352 config.format = sourceDesc->config().format;
4353 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4354 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4355 bool isRequestedDeviceForExclusiveUse = false;
4356 output_type_t outputType;
4357 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4358 &stream, sourceDesc->uid(), &config, &flags,
4359 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4360 nullptr, &outputType);
4361 if (output == AUDIO_IO_HANDLE_NONE) {
4362 ALOGV("%s no output for device %s",
4363 __FUNCTION__, sinkDevice->toString().c_str());
4364 return INVALID_OPERATION;
4365 }
4366 outputDesc = mOutputs.valueFor(output);
4367 if (outputDesc->isDuplicated()) {
4368 ALOGE("%s output is duplicated", __func__);
4369 return INVALID_OPERATION;
4370 }
4371 sourceDesc->setSwOutput(outputDesc);
4372 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004373 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004374 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004375 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004376 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004377 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4378 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004379 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4380 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004381 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4382 (sourceDesc != nullptr &&
4383 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004384 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004385 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004386 return INVALID_OPERATION;
4387 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004388 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004389 SortedVector<audio_io_handle_t> outputs =
4390 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4391 // if the sink device is reachable via an opened output stream, request to
4392 // go via this output stream by adding a second source to the patch
4393 // description
4394 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004395 if (output != AUDIO_IO_HANDLE_NONE) {
4396 outputDesc = mOutputs.valueFor(output);
4397 if (outputDesc->isDuplicated()) {
4398 ALOGV("%s output for device %s is duplicated",
4399 __FUNCTION__, sinkDevice->toString().c_str());
4400 return INVALID_OPERATION;
4401 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004402 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004403 }
4404 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004405 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004406 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004407 // for volume control, we may need a valid stream
4408 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4409 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4410 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004411 }
Eric Laurent83b88082014-06-20 18:31:16 -07004412 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004413 }
4414 // TODO: check from routing capabilities in config file and other conflicting patches
4415
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004416installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004417 status_t status = installPatch(
4418 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004419 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004420 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004421 return INVALID_OPERATION;
4422 }
4423 } else {
4424 return BAD_VALUE;
4425 }
4426 } else {
4427 return BAD_VALUE;
4428 }
4429 return NO_ERROR;
4430}
4431
4432status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4433 uid_t uid)
4434{
4435 ALOGV("releaseAudioPatch() patch %d", handle);
4436
4437 ssize_t index = mAudioPatches.indexOfKey(handle);
4438
4439 if (index < 0) {
4440 return BAD_VALUE;
4441 }
4442 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004443 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4444 __func__, mUidCached, patchDesc->getUid(), uid);
4445 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004446 return INVALID_OPERATION;
4447 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004448 return releaseAudioPatchInternal(handle);
4449}
Eric Laurent6a94d692014-05-20 11:18:06 -07004450
François Gaffieafd4cea2019-11-18 15:50:22 +01004451status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4452 uint32_t delayMs)
4453{
4454 ALOGV("%s patch %d", __func__, handle);
4455 if (mAudioPatches.indexOfKey(handle) < 0) {
4456 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4457 return BAD_VALUE;
4458 }
4459 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004460 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004461 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004462 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004463 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004464 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004465 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004466 return BAD_VALUE;
4467 }
4468
François Gaffie11d30102018-11-02 16:09:09 +01004469 setOutputDevices(outputDesc,
4470 getNewOutputDevices(outputDesc, true /*fromCache*/),
4471 true,
4472 0,
4473 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004474 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4475 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004476 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004477 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004478 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004479 return BAD_VALUE;
4480 }
4481 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004482 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004483 true,
4484 NULL);
4485 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004486 status_t status =
4487 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4488 ALOGV("%s patch panel returned %d patchHandle %d",
4489 __func__, status, patchDesc->getAfHandle());
4490 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004491 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004492 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004493 // SW Bridge
4494 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4495 sp<SwAudioOutputDescriptor> outputDesc =
4496 mOutputs.getOutputFromId(patch->sources[1].id);
4497 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004498 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4499 // releaseOutput has already called closeOuput in case of direct output
4500 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004501 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004502 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4503 // force SwOutput patch removal as AF counter part patch has already gone.
4504 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4505 removeAudioPatch(outputDesc->getPatchHandle());
4506 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004507 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4508 setOutputDevices(outputDesc,
4509 getNewOutputDevices(outputDesc, true /*fromCache*/),
4510 true, /*force*/
4511 0,
4512 NULL);
4513 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004514 } else {
4515 return BAD_VALUE;
4516 }
4517 } else {
4518 return BAD_VALUE;
4519 }
4520 return NO_ERROR;
4521}
4522
4523status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4524 struct audio_patch *patches,
4525 unsigned int *generation)
4526{
François Gaffie53615e22015-03-19 09:24:12 +01004527 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004528 return BAD_VALUE;
4529 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004530 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004531 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004532}
4533
Eric Laurente1715a42014-05-20 11:30:42 -07004534status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004535{
Eric Laurente1715a42014-05-20 11:30:42 -07004536 ALOGV("setAudioPortConfig()");
4537
4538 if (config == NULL) {
4539 return BAD_VALUE;
4540 }
4541 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4542 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004543 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4544 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004545 }
4546
Eric Laurenta121f902014-06-03 13:32:54 -07004547 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004548 if (config->type == AUDIO_PORT_TYPE_MIX) {
4549 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004550 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004551 if (outputDesc == NULL) {
4552 return BAD_VALUE;
4553 }
Eric Laurent84c70242014-06-23 08:46:27 -07004554 ALOG_ASSERT(!outputDesc->isDuplicated(),
4555 "setAudioPortConfig() called on duplicated output %d",
4556 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004557 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004558 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004559 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004560 if (inputDesc == NULL) {
4561 return BAD_VALUE;
4562 }
Eric Laurenta121f902014-06-03 13:32:54 -07004563 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004564 } else {
4565 return BAD_VALUE;
4566 }
4567 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4568 sp<DeviceDescriptor> deviceDesc;
4569 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4570 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4571 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4572 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4573 } else {
4574 return BAD_VALUE;
4575 }
4576 if (deviceDesc == NULL) {
4577 return BAD_VALUE;
4578 }
Eric Laurenta121f902014-06-03 13:32:54 -07004579 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004580 } else {
4581 return BAD_VALUE;
4582 }
4583
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004584 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004585 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4586 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004587 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004588 audioPortConfig->toAudioPortConfig(&newConfig, config);
4589 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004590 }
Eric Laurenta121f902014-06-03 13:32:54 -07004591 if (status != NO_ERROR) {
4592 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004593 }
Eric Laurente1715a42014-05-20 11:30:42 -07004594
4595 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004596}
4597
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004598void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4599{
Eric Laurentd60560a2015-04-10 11:31:20 -07004600 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004601 clearAudioPatches(uid);
4602 clearSessionRoutes(uid);
4603}
4604
Eric Laurent6a94d692014-05-20 11:18:06 -07004605void AudioPolicyManager::clearAudioPatches(uid_t uid)
4606{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004607 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004608 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004609 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004610 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004611 }
4612 }
4613}
4614
François Gaffiec005e562018-11-06 15:04:49 +01004615void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004616{
François Gaffiec005e562018-11-06 15:04:49 +01004617 // Take the first attributes following the product strategy as it is used to retrieve the routed
4618 // device. All attributes wihin a strategy follows the same "routing strategy"
4619 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4620 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004621 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004622 for (size_t j = 0; j < mOutputs.size(); j++) {
4623 if (mOutputs.keyAt(j) == ouptutToSkip) {
4624 continue;
4625 }
4626 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004627 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004628 continue;
4629 }
4630 // If the default device for this strategy is on another output mix,
4631 // invalidate all tracks in this strategy to force re connection.
4632 // Otherwise select new device on the output mix.
4633 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004634 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4635 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004636 }
4637 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004638 setOutputDevices(
4639 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004640 }
4641 }
4642}
4643
4644void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4645{
4646 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004647 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004648 for (size_t i = 0; i < mOutputs.size(); i++) {
4649 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004650 for (const auto& client : outputDesc->getClientIterable()) {
4651 if (client->hasPreferredDevice() && client->uid() == uid) {
4652 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004653 auto clientStrategy = client->strategy();
4654 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4655 end(affectedStrategies)) {
4656 continue;
4657 }
4658 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004659 }
4660 }
4661 }
4662 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004663 for (const auto& strategy : affectedStrategies) {
4664 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004665 }
4666
4667 // remove input routes associated with this uid
4668 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004669 for (size_t i = 0; i < mInputs.size(); i++) {
4670 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004671 for (const auto& client : inputDesc->getClientIterable()) {
4672 if (client->hasPreferredDevice() && client->uid() == uid) {
4673 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4674 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004675 }
4676 }
4677 }
4678 // reroute inputs if necessary
4679 SortedVector<audio_io_handle_t> inputsToClose;
4680 for (size_t i = 0; i < mInputs.size(); i++) {
4681 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004682 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004683 inputsToClose.add(inputDesc->mIoHandle);
4684 }
4685 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004686 for (const auto& input : inputsToClose) {
4687 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004688 }
4689}
4690
Eric Laurentd60560a2015-04-10 11:31:20 -07004691void AudioPolicyManager::clearAudioSources(uid_t uid)
4692{
4693 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004694 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4695 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004696 stopAudioSource(mAudioSources.keyAt(i));
4697 }
4698 }
4699}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004700
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004701status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4702 audio_io_handle_t *ioHandle,
4703 audio_devices_t *device)
4704{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004705 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4706 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004707 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004708 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004709
François Gaffiedf372692015-03-19 10:43:27 +01004710 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004711}
4712
Eric Laurentd60560a2015-04-10 11:31:20 -07004713status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004714 const audio_attributes_t *attributes,
4715 audio_port_handle_t *portId,
4716 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004717{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004718 ALOGV("%s", __FUNCTION__);
4719 *portId = AUDIO_PORT_HANDLE_NONE;
4720
4721 if (source == NULL || attributes == NULL || portId == NULL) {
4722 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4723 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004724 return BAD_VALUE;
4725 }
4726
Eric Laurentd60560a2015-04-10 11:31:20 -07004727 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4728 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004729 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4730 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004731 return INVALID_OPERATION;
4732 }
4733
François Gaffie11d30102018-11-02 16:09:09 +01004734 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004735 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004736 String8(source->ext.device.address),
4737 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004738 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004739 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004740 return BAD_VALUE;
4741 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004742
jiabin4ef93452019-09-10 14:29:54 -07004743 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004744
François Gaffieaaac0fd2018-11-22 17:56:39 +01004745 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004746 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004747 mEngine->getStreamTypeForAttributes(*attributes),
4748 mEngine->getProductStrategyForAttributes(*attributes),
4749 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004750
4751 status_t status = connectAudioSource(sourceDesc);
4752 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004753 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004754 }
4755 return status;
4756}
4757
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004758status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004759{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004760 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004761
4762 // make sure we only have one patch per source.
4763 disconnectAudioSource(sourceDesc);
4764
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004765 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004766 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4767 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4768 sourceDesc->srcDevice()->type(),
4769 String8(sourceDesc->srcDevice()->address().c_str()),
4770 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004771 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004772 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004773 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004774 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004775 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4776 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4777 return INVALID_OPERATION;
4778 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004779 PatchBuilder patchBuilder;
4780 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4781 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4782 status_t status =
4783 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4784 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4785 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4786 return INVALID_OPERATION;
4787 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004788 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004789 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4790 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4791 if (swOutput != 0) {
4792 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004793 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004794 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004795 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004796 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004797 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004798 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004799 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004800 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004801 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004802 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004803 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004804 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4805 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004806 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004807 if (delayMs != 0) {
4808 usleep(delayMs * 1000);
4809 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004810 } else {
4811 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4812 if (hwOutputDesc != 0) {
4813 // create Hwoutput and add to mHwOutputs
4814 } else {
4815 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4816 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004817 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004818 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004819
4820FailureSourceActive:
4821 swOutput->stop();
4822 releaseOutput(sourceDesc->portId());
4823FailureSourceAdded:
4824 sourceDesc->setSwOutput(nullptr);
4825FailureReleasePatch:
4826 releaseAudioPatchInternal(handle);
4827 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004828}
4829
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004830status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004831{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004832 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4833 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004834 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004835 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004836 return BAD_VALUE;
4837 }
4838 status_t status = disconnectAudioSource(sourceDesc);
4839
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004840 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004841 return status;
4842}
4843
Andy Hung2ddee192015-12-18 17:34:44 -08004844status_t AudioPolicyManager::setMasterMono(bool mono)
4845{
4846 if (mMasterMono == mono) {
4847 return NO_ERROR;
4848 }
4849 mMasterMono = mono;
4850 // if enabling mono we close all offloaded devices, which will invalidate the
4851 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4852 // for recreating the new AudioTrack as non-offloaded PCM.
4853 //
4854 // If disabling mono, we leave all tracks as is: we don't know which clients
4855 // and tracks are able to be recreated as offloaded. The next "song" should
4856 // play back offloaded.
4857 if (mMasterMono) {
4858 Vector<audio_io_handle_t> offloaded;
4859 for (size_t i = 0; i < mOutputs.size(); ++i) {
4860 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4861 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4862 offloaded.push(desc->mIoHandle);
4863 }
4864 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004865 for (const auto& handle : offloaded) {
4866 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004867 }
4868 }
4869 // update master mono for all remaining outputs
4870 for (size_t i = 0; i < mOutputs.size(); ++i) {
4871 updateMono(mOutputs.keyAt(i));
4872 }
4873 return NO_ERROR;
4874}
4875
4876status_t AudioPolicyManager::getMasterMono(bool *mono)
4877{
4878 *mono = mMasterMono;
4879 return NO_ERROR;
4880}
4881
Eric Laurentac9cef52017-06-09 15:46:26 -07004882float AudioPolicyManager::getStreamVolumeDB(
4883 audio_stream_type_t stream, int index, audio_devices_t device)
4884{
jiabin9a3361e2019-10-01 09:38:30 -07004885 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004886}
4887
jiabin81772902018-04-02 17:52:27 -07004888status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4889 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004890 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004891{
Kriti Dang6537def2021-03-02 13:46:59 +01004892 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4893 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004894 return BAD_VALUE;
4895 }
Kriti Dang6537def2021-03-02 13:46:59 +01004896 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4897 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004898
4899 size_t formatsWritten = 0;
4900 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004901
Kriti Dang6537def2021-03-02 13:46:59 +01004902 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004903 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4904 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004905 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004906 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004907 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004908 bool formatEnabled = true;
4909 switch (forceUse) {
4910 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004911 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004912 break;
4913 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4914 formatEnabled = false;
4915 break;
4916 default: // AUTO or ALWAYS => true
4917 break;
jiabin81772902018-04-02 17:52:27 -07004918 }
4919 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4920 }
jiabin81772902018-04-02 17:52:27 -07004921 }
4922 return NO_ERROR;
4923}
4924
Kriti Dang6537def2021-03-02 13:46:59 +01004925status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4926 audio_format_t *surroundFormats) {
4927 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4928 return BAD_VALUE;
4929 }
4930 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4931 __func__, *numSurroundFormats, surroundFormats);
4932
4933 size_t formatsWritten = 0;
4934 size_t formatsMax = *numSurroundFormats;
4935 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4936
4937 // Return formats from all device profiles that have already been resolved by
4938 // checkOutputsForDevice().
4939 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4940 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4941 audio_devices_t deviceType = device->type();
4942 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4943 // returns formats reported by HDMI devices.
4944 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4945 continue;
4946 }
4947 // Formats reported by sink devices
4948 std::unordered_set<audio_format_t> formatset;
4949 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4950 formatset.insert(it->second.begin(), it->second.end());
4951 }
4952
4953 // Formats hard-coded in the in policy configuration file (if any).
4954 FormatVector encodedFormats = device->encodedFormats();
4955 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4956 // Filter the formats which are supported by the vendor hardware.
4957 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4958 if (mConfig.getSurroundFormats().count(*it) != 0) {
4959 formats.insert(*it);
4960 } else {
4961 for (const auto& pair : mConfig.getSurroundFormats()) {
4962 if (pair.second.count(*it) != 0) {
4963 formats.insert(pair.first);
4964 break;
4965 }
4966 }
4967 }
4968 }
4969 }
4970 *numSurroundFormats = formats.size();
4971 for (const auto& format: formats) {
4972 if (formatsWritten < formatsMax) {
4973 surroundFormats[formatsWritten++] = format;
4974 }
4975 }
4976 return NO_ERROR;
4977}
4978
jiabin81772902018-04-02 17:52:27 -07004979status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4980{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004981 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004982 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4983 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004984 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004985 return BAD_VALUE;
4986 }
4987
Mikhail Naganov100f0122018-11-29 11:22:16 -08004988 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4989 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004990 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004991 return INVALID_OPERATION;
4992 }
4993
Mikhail Naganov100f0122018-11-29 11:22:16 -08004994 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004995 return NO_ERROR;
4996 }
4997
Mikhail Naganov100f0122018-11-29 11:22:16 -08004998 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004999 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005000 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005001 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005002 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005003 }
5004 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005005 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005006 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005007 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005008 }
5009 }
5010
5011 sp<SwAudioOutputDescriptor> outputDesc;
5012 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005013 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5014 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005015 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5016 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005017 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005018 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005019 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5020 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5021 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005022 name.c_str(),
5023 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005024 if (status != NO_ERROR) {
5025 continue;
5026 }
5027 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5028 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5029 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005030 name.c_str(),
5031 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005032 profileUpdated |= (status == NO_ERROR);
5033 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005034 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005035 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005036 AUDIO_DEVICE_IN_HDMI);
5037 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5038 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005039 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005040 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005041 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5042 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5043 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005044 name.c_str(),
5045 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005046 if (status != NO_ERROR) {
5047 continue;
5048 }
5049 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5050 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5051 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005052 name.c_str(),
5053 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005054 profileUpdated |= (status == NO_ERROR);
5055 }
5056
jiabin81772902018-04-02 17:52:27 -07005057 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005058 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005059 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005060 }
5061
5062 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5063}
5064
Eric Laurent5ada82e2019-08-29 17:53:54 -07005065void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005066{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005067 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005068 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005069 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005070 }
5071}
5072
jiabin6012f912018-11-02 17:06:30 -07005073bool AudioPolicyManager::isHapticPlaybackSupported()
5074{
5075 for (const auto& hwModule : mHwModules) {
5076 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5077 for (const auto &outProfile : outputProfiles) {
5078 struct audio_port audioPort;
5079 outProfile->toAudioPort(&audioPort);
5080 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5081 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5082 return true;
5083 }
5084 }
5085 }
5086 }
5087 return false;
5088}
5089
Carter Hsu325a8eb2022-01-19 19:56:51 +08005090bool AudioPolicyManager::isUltrasoundSupported()
5091{
5092 bool hasUltrasoundOutput = false;
5093 bool hasUltrasoundInput = false;
5094 for (const auto& hwModule : mHwModules) {
5095 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5096 if (!hasUltrasoundOutput) {
5097 for (const auto &outProfile : outputProfiles) {
5098 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5099 hasUltrasoundOutput = true;
5100 break;
5101 }
5102 }
5103 }
5104
5105 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5106 if (!hasUltrasoundInput) {
5107 for (const auto &inputProfile : inputProfiles) {
5108 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5109 hasUltrasoundInput = true;
5110 break;
5111 }
5112 }
5113 }
5114
5115 if (hasUltrasoundOutput && hasUltrasoundInput)
5116 return true;
5117 }
5118 return false;
5119}
5120
Eric Laurent8340e672019-11-06 11:01:08 -08005121bool AudioPolicyManager::isCallScreenModeSupported()
5122{
5123 return getConfig().isCallScreenModeSupported();
5124}
5125
5126
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005127status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005128{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005129 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005130 if (!sourceDesc->isConnected()) {
5131 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5132 return NO_ERROR;
5133 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005134 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5135 if (swOutput != 0) {
5136 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005137 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005138 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005139 }
jiabinbce0c1d2020-10-05 11:20:18 -07005140 if (releaseOutput(sourceDesc->portId())) {
5141 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5142 // no need to release audio patch here but just return NO_ERROR.
5143 return NO_ERROR;
5144 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005145 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005146 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005147 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005148 // close Hwoutput and remove from mHwOutputs
5149 } else {
5150 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5151 }
5152 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005153 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
5154 sourceDesc->disconnect();
5155 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005156}
5157
François Gaffiec005e562018-11-06 15:04:49 +01005158sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5159 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005160{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005161 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005162 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005163 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005164 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005165 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5166 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005167 source = sourceDesc;
5168 break;
5169 }
5170 }
5171 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005172}
5173
Eric Laurent39095982021-08-24 18:29:27 +02005174/* static */
5175bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
5176 switch (channels) {
5177 case AUDIO_CHANNEL_OUT_5POINT1:
5178 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
5179 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
5180 case AUDIO_CHANNEL_OUT_7POINT1:
5181 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
5182 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
5183 return true;
5184 default:
5185 return false;
5186 }
5187}
5188
Eric Laurentb4f42a92022-01-17 17:37:31 +01005189bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005190 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005191 const AudioDeviceTypeAddrVector &devices,
5192 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005193{
5194 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5195 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005196 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005197 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005198 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5199 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5200 return false;
5201 }
5202 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5203 return false;
5204 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005205 }
5206
5207 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005208 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5209 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005210 // to the specified devices must exist.
5211 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005212 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005213 if (profile == nullptr) {
5214 return false;
5215 }
5216
5217 // The caller can have the audio config criteria ignored by either passing a null ptr or
5218 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005219 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005220 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005221 // If the spatializer output is already opened, only channel masks included in the
5222 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005223
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005224 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005225 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005226 return false;
5227 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005228 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5229 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005230 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005231 != config->channel_mask) {
5232 return false;
5233 }
5234 }
5235 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005236 return true;
5237}
5238
5239void AudioPolicyManager::checkVirtualizerClientRoutes() {
5240 std::set<audio_stream_type_t> streamsToInvalidate;
5241 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005242 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5243 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005244 audio_attributes_t attr = client->attributes();
5245 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5246 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5247 audio_config_base_t clientConfig = client->config();
5248 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005249 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005250 && canBeSpatializedInt(&attr, &config,
5251 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005252 streamsToInvalidate.insert(client->stream());
5253 }
5254 }
5255 }
5256
5257 for (audio_stream_type_t stream : streamsToInvalidate) {
5258 mpClientInterface->invalidateStream(stream);
5259 }
5260}
5261
Eric Laurentfa0f6742021-08-17 18:39:44 +02005262status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005263 const audio_attributes_t *attr,
5264 audio_io_handle_t *output) {
5265 *output = AUDIO_IO_HANDLE_NONE;
5266
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005267 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5268 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5269 audio_config_t *configPtr = nullptr;
5270 audio_config_t config;
5271 if (mixerConfig != nullptr) {
5272 config = audio_config_initializer(mixerConfig);
5273 configPtr = &config;
5274 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005275 if (!canBeSpatializedInt(
5276 attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02005277 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005278 return BAD_VALUE;
5279 }
5280
5281 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005282 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005283 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005284 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005285 return BAD_VALUE;
5286 }
5287
Eric Laurent39095982021-08-24 18:29:27 +02005288 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
5289 && configPtr != nullptr
5290 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
5291 *output = mSpatializerOutput->mIoHandle;
5292 ALOGV("%s returns current spatializer output %d", __func__, *output);
5293 return NO_ERROR;
5294 }
5295 mSpatializerOutput.clear();
5296 for (size_t i = 0; i < mOutputs.size(); i++) {
5297 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5298 if (!desc->isDuplicated() && desc->mProfile == profile) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005299 ALOGV("%s found output %d for spatializer profile", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005300 mSpatializerOutput = desc;
5301 break;
5302 }
5303 }
5304 if (mSpatializerOutput == nullptr) {
5305 ALOGW("%s no opened spatializer output for profile %s",
5306 __func__, profile->getName().c_str());
5307 return BAD_VALUE;
5308 }
5309
5310 if (configPtr != nullptr
5311 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5312 audio_config_base_t savedMixerConfig = {
5313 .sample_rate = mSpatializerOutput->getSamplingRate(),
5314 .format = mSpatializerOutput->getFormat(),
5315 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5316 };
5317 DeviceVector savedDevices = mSpatializerOutput->devices();
5318
Eric Laurentb4f42a92022-01-17 17:37:31 +01005319 ALOGV("%s reopening spatializer output to match channel mask %#x (current mask %#x)",
5320 __func__, configPtr->channel_mask, mSpatializerOutput->mMixerChannelMask);
Eric Laurent39095982021-08-24 18:29:27 +02005321
Eric Laurentb4f42a92022-01-17 17:37:31 +01005322 closeOutput(mSpatializerOutput->mIoHandle);
5323 //from now on mSpatializerOutput is null
5324
5325 sp<SwAudioOutputDescriptor> desc =
5326 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
5327 if (desc == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005328 // re open the spatializer output with previous channel mask
Eric Laurentb4f42a92022-01-17 17:37:31 +01005329 desc = openOutputWithProfileAndDevice(profile, savedDevices, &savedMixerConfig);
5330 if (desc == nullptr) {
5331 ALOGE("%s failed to restore mSpatializerOutput with previous config", __func__);
Eric Laurent39095982021-08-24 18:29:27 +02005332 } else {
5333 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005334 }
5335 mPreviousOutputs = mOutputs;
5336 mpClientInterface->onAudioPortListUpdate();
5337 *output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005338 ALOGW("%s could not open spatializer output with requested config", __func__);
5339 return BAD_VALUE;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005340 }
Eric Laurent39095982021-08-24 18:29:27 +02005341 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005342 mPreviousOutputs = mOutputs;
5343 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005344 }
5345
5346 checkVirtualizerClientRoutes();
5347
Eric Laurent39095982021-08-24 18:29:27 +02005348 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005349 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005350 return NO_ERROR;
5351}
5352
Eric Laurentfa0f6742021-08-17 18:39:44 +02005353status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5354 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005355 return INVALID_OPERATION;
5356 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005357 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005358 return BAD_VALUE;
5359 }
Eric Laurent39095982021-08-24 18:29:27 +02005360
Eric Laurentfa0f6742021-08-17 18:39:44 +02005361 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005362
5363 checkVirtualizerClientRoutes();
5364
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005365 return NO_ERROR;
5366}
5367
Eric Laurente552edb2014-03-10 17:42:56 -07005368// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005369// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005370// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005371uint32_t AudioPolicyManager::nextAudioPortGeneration()
5372{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005373 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005374}
5375
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005376static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005377 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5378 !audioPolicyXmlConfigFile.empty()) {
5379 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5380 if (ret == NO_ERROR) {
5381 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005382 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005383 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005384 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005385 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005386}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005387
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005388AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5389 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005390 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005391 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005392 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005393 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005394 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005395 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005396 mAudioPortGeneration(1),
5397 mBeaconMuteRefCount(0),
5398 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005399 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005400 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005401 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005402 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005403{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005404}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005405
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005406AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5407 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5408{
5409 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005410}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005411
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005412void AudioPolicyManager::loadConfig() {
5413 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005414 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005415 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005416 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005417}
5418
5419status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005420 {
5421 auto engLib = EngineLibrary::load(
5422 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5423 if (!engLib) {
5424 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5425 return NO_INIT;
5426 }
5427 mEngine = engLib->createEngine();
5428 if (mEngine == nullptr) {
5429 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5430 return NO_INIT;
5431 }
François Gaffie2110e042015-03-24 08:41:51 +01005432 }
5433 mEngine->setObserver(this);
5434 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005435 if (status != NO_ERROR) {
5436 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5437 return status;
5438 }
François Gaffie2110e042015-03-24 08:41:51 +01005439
Eric Laurent1d69c872021-01-11 18:53:01 +01005440 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5441 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5442
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005443 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005444 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005445 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005446
Eric Laurent3a4311c2014-03-17 12:00:47 -07005447 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005448 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5449 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5450 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005451 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005452 }
jiabin9ff780e2018-03-19 18:19:52 -07005453 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005454 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005455 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005456 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005457 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005458 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005459 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005460 }
5461 }
5462 }
Eric Laurente552edb2014-03-10 17:42:56 -07005463
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005464 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005465
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005466 // Silence ALOGV statements
5467 property_set("log.tag." LOG_TAG, "D");
5468
Eric Laurente552edb2014-03-10 17:42:56 -07005469 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005470 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005471}
5472
Eric Laurente0720872014-03-11 09:30:41 -07005473AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005474{
Eric Laurente552edb2014-03-10 17:42:56 -07005475 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005476 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005477 }
5478 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005479 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005480 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005481 mAvailableOutputDevices.clear();
5482 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005483 mOutputs.clear();
5484 mInputs.clear();
5485 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005486 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005487 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005488}
5489
Eric Laurente0720872014-03-11 09:30:41 -07005490status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005491{
Eric Laurent87ffa392015-05-22 10:32:38 -07005492 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005493}
5494
Eric Laurente552edb2014-03-10 17:42:56 -07005495// ---
5496
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005497void AudioPolicyManager::onNewAudioModulesAvailable()
5498{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005499 DeviceVector newDevices;
5500 onNewAudioModulesAvailableInt(&newDevices);
5501 if (!newDevices.empty()) {
5502 nextAudioPortGeneration();
5503 mpClientInterface->onAudioPortListUpdate();
5504 }
5505}
5506
5507void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5508{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005509 for (const auto& hwModule : mHwModulesAll) {
5510 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5511 continue;
5512 }
5513 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5514 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5515 ALOGW("could not open HW module %s", hwModule->getName());
5516 continue;
5517 }
5518 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005519 // open all output streams needed to access attached devices.
5520 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005521 // This also validates mAvailableOutputDevices list
5522 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5523 if (!outProfile->canOpenNewIo()) {
5524 ALOGE("Invalid Output profile max open count %u for profile %s",
5525 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5526 continue;
5527 }
5528 if (!outProfile->hasSupportedDevices()) {
5529 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5530 continue;
5531 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005532 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5533 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005534 mTtsOutputAvailable = true;
5535 }
5536
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005537 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5538 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5539 sp<DeviceDescriptor> supportedDevice = 0;
5540 if (supportedDevices.contains(mDefaultOutputDevice)) {
5541 supportedDevice = mDefaultOutputDevice;
5542 } else {
5543 // choose first device present in profile's SupportedDevices also part of
5544 // mAvailableOutputDevices.
5545 if (availProfileDevices.isEmpty()) {
5546 continue;
5547 }
5548 supportedDevice = availProfileDevices.itemAt(0);
5549 }
5550 if (!mOutputDevicesAll.contains(supportedDevice)) {
5551 continue;
5552 }
5553 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5554 mpClientInterface);
5555 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005556 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5557 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005558 AUDIO_STREAM_DEFAULT,
5559 AUDIO_OUTPUT_FLAG_NONE, &output);
5560 if (status != NO_ERROR) {
5561 ALOGW("Cannot open output stream for devices %s on hw module %s",
5562 supportedDevice->toString().c_str(), 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 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005570 device->setEncapsulationInfoFromHal(mpClientInterface);
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 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005575 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005576 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5577 mPrimaryOutput = outputDesc;
5578 }
Eric Laurent39095982021-08-24 18:29:27 +02005579 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005580 outputDesc->close();
5581 } else {
5582 addOutput(output, outputDesc);
5583 setOutputDevices(outputDesc,
5584 DeviceVector(supportedDevice),
5585 true,
5586 0,
5587 NULL);
5588 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005589 }
5590 // open input streams needed to access attached devices to validate
5591 // mAvailableInputDevices list
5592 for (const auto& inProfile : hwModule->getInputProfiles()) {
5593 if (!inProfile->canOpenNewIo()) {
5594 ALOGE("Invalid Input profile max open count %u for profile %s",
5595 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5596 continue;
5597 }
5598 if (!inProfile->hasSupportedDevices()) {
5599 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5600 continue;
5601 }
5602 // chose first device present in profile's SupportedDevices also part of
5603 // available input devices
5604 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5605 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5606 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005607 ALOGV("%s: Input device list is empty! for profile %s",
5608 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005609 continue;
5610 }
5611 sp<AudioInputDescriptor> inputDesc =
5612 new AudioInputDescriptor(inProfile, mpClientInterface);
5613
5614 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5615 status_t status = inputDesc->open(nullptr,
5616 availProfileDevices.itemAt(0),
5617 AUDIO_SOURCE_MIC,
5618 AUDIO_INPUT_FLAG_NONE,
5619 &input);
5620 if (status != NO_ERROR) {
5621 ALOGW("Cannot open input stream for device %s on hw module %s",
5622 availProfileDevices.toString().c_str(),
5623 hwModule->getName());
5624 continue;
5625 }
5626 for (const auto &device : availProfileDevices) {
5627 // give a valid ID to an attached device once confirmed it is reachable
5628 if (!device->isAttached()) {
5629 device->attach(hwModule);
5630 device->importAudioPortAndPickAudioProfile(inProfile, true);
5631 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005632 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005633 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5634 }
5635 }
5636 inputDesc->close();
5637 }
5638 }
5639}
5640
Eric Laurent98e38192018-02-15 18:31:53 -08005641void AudioPolicyManager::addOutput(audio_io_handle_t output,
5642 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005643{
Eric Laurent1c333e22014-05-20 10:48:17 -07005644 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005645 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005646 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005647 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005648 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005649}
5650
François Gaffie53615e22015-03-19 09:24:12 +01005651void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5652{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005653 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5654 ALOGV("%s: removing primary output", __func__);
5655 mPrimaryOutput = nullptr;
5656 }
François Gaffie53615e22015-03-19 09:24:12 +01005657 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005658 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005659}
5660
Eric Laurent98e38192018-02-15 18:31:53 -08005661void AudioPolicyManager::addInput(audio_io_handle_t input,
5662 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005663{
Eric Laurent1c333e22014-05-20 10:48:17 -07005664 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005665 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005666}
Eric Laurente552edb2014-03-10 17:42:56 -07005667
François Gaffie11d30102018-11-02 16:09:09 +01005668status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005669 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005670 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005671{
François Gaffie11d30102018-11-02 16:09:09 +01005672 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005673 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005674 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005675
François Gaffie11d30102018-11-02 16:09:09 +01005676 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005677 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005678 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005679 }
Eric Laurente552edb2014-03-10 17:42:56 -07005680
Eric Laurent3b73df72014-03-11 09:06:29 -07005681 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005682 // first call getAudioPort to get the supported attributes from the HAL
5683 struct audio_port_v7 port = {};
5684 device->toAudioPort(&port);
5685 status_t status = mpClientInterface->getAudioPort(&port);
5686 if (status == NO_ERROR) {
5687 device->importAudioPort(port);
5688 }
5689
5690 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005691 for (size_t i = 0; i < mOutputs.size(); i++) {
5692 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005693 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005694 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005695 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5696 mOutputs.keyAt(i), device->toString().c_str());
5697 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005698 }
5699 }
5700 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005701 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005702 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005703 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5704 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005705 if (profile->supportsDevice(device)) {
5706 profiles.add(profile);
5707 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5708 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005709 }
5710 }
5711 }
5712
Eric Laurent7b279bb2015-12-14 10:18:23 -08005713 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005714
Eric Laurente552edb2014-03-10 17:42:56 -07005715 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005716 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005717 return BAD_VALUE;
5718 }
5719
5720 // open outputs for matching profiles if needed. Direct outputs are also opened to
5721 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5722 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005723 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005724
5725 // nothing to do if one output is already opened for this profile
5726 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005727 for (j = 0; j < outputs.size(); j++) {
5728 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005729 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005730 // matching profile: save the sample rates, format and channel masks supported
5731 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005732 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005733 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005734 }
Eric Laurente552edb2014-03-10 17:42:56 -07005735 break;
5736 }
5737 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005738 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005739 continue;
5740 }
5741
Eric Laurent3974e3b2017-12-07 17:58:43 -08005742 if (!profile->canOpenNewIo()) {
5743 ALOGW("Max Output number %u already opened for this profile %s",
5744 profile->maxOpenCount, profile->getTagName().c_str());
5745 continue;
5746 }
5747
Eric Laurent83efe1c2017-07-09 16:51:08 -07005748 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005749 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005750 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5751 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005752 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005753 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005754 profiles.removeAt(profile_index);
5755 profile_index--;
5756 } else {
5757 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005758 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005759 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005760 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5761 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005762 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005763 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005764
François Gaffie11d30102018-11-02 16:09:09 +01005765 if (device_distinguishes_on_address(deviceType)) {
5766 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5767 device->toString().c_str());
5768 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5769 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005770 }
Eric Laurente552edb2014-03-10 17:42:56 -07005771 ALOGV("checkOutputsForDevice(): adding output %d", output);
5772 }
5773 }
5774
5775 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005776 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005777 return BAD_VALUE;
5778 }
Eric Laurentd4692962014-05-05 18:13:44 -07005779 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005780 // check if one opened output is not needed any more after disconnecting one device
5781 for (size_t i = 0; i < mOutputs.size(); i++) {
5782 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005783 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005784 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005785 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005786 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005787 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005788 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005789 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5790 mOutputs.keyAt(i));
5791 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005792 }
Eric Laurente552edb2014-03-10 17:42:56 -07005793 }
5794 }
Eric Laurentd4692962014-05-05 18:13:44 -07005795 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005796 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005797 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5798 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005799 if (!profile->supportsDevice(device)) {
5800 continue;
5801 }
5802 ALOGV("checkOutputsForDevice(): "
5803 "clearing direct output profile %zu on module %s",
5804 j, hwModule->getName());
5805 profile->clearAudioProfiles();
5806 if (!profile->hasDynamicAudioProfile()) {
5807 continue;
5808 }
5809 // When a device is disconnected, if there is an IOProfile that contains dynamic
5810 // profiles and supports the disconnected device, call getAudioPort to repopulate
5811 // the capabilities of the devices that is supported by the IOProfile.
5812 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5813 if (supportedDevice == device ||
5814 !mAvailableOutputDevices.contains(supportedDevice)) {
5815 continue;
5816 }
5817 struct audio_port_v7 port;
5818 supportedDevice->toAudioPort(&port);
5819 status_t status = mpClientInterface->getAudioPort(&port);
5820 if (status == NO_ERROR) {
5821 supportedDevice->importAudioPort(port);
5822 }
Eric Laurente552edb2014-03-10 17:42:56 -07005823 }
5824 }
5825 }
5826 }
5827 return NO_ERROR;
5828}
5829
François Gaffie11d30102018-11-02 16:09:09 +01005830status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005831 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005832{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005833 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005834
François Gaffie11d30102018-11-02 16:09:09 +01005835 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005836 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005837 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005838 }
5839
Eric Laurentd4692962014-05-05 18:13:44 -07005840 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005841 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005842 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005843 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005844 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005845 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005846 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005847 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005848
François Gaffie11d30102018-11-02 16:09:09 +01005849 if (profile->supportsDevice(device)) {
5850 profiles.add(profile);
5851 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5852 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005853 }
5854 }
5855 }
5856
Eric Laurent0dd51852019-04-19 18:18:58 -07005857 if (profiles.isEmpty()) {
5858 ALOGW("%s: No input profile available for device %s",
5859 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005860 return BAD_VALUE;
5861 }
5862
5863 // open inputs for matching profiles if needed. Direct inputs are also opened to
5864 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5865 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5866
Eric Laurent1c333e22014-05-20 10:48:17 -07005867 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005868
Eric Laurentd4692962014-05-05 18:13:44 -07005869 // nothing to do if one input is already opened for this profile
5870 size_t input_index;
5871 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5872 desc = mInputs.valueAt(input_index);
5873 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005874 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005875 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005876 }
Eric Laurentd4692962014-05-05 18:13:44 -07005877 break;
5878 }
5879 }
5880 if (input_index != mInputs.size()) {
5881 continue;
5882 }
5883
Eric Laurent3974e3b2017-12-07 17:58:43 -08005884 if (!profile->canOpenNewIo()) {
5885 ALOGW("Max Input number %u already opened for this profile %s",
5886 profile->maxOpenCount, profile->getTagName().c_str());
5887 continue;
5888 }
5889
Eric Laurentfe231122017-11-17 17:48:06 -08005890 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005891 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005892 status_t status = desc->open(nullptr,
5893 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005894 AUDIO_SOURCE_MIC,
5895 AUDIO_INPUT_FLAG_NONE,
5896 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005897
Eric Laurentcf2c0212014-07-25 16:20:43 -07005898 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005899 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005900 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005901 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005902 mpClientInterface->setParameters(input, String8(param));
5903 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005904 }
François Gaffie11d30102018-11-02 16:09:09 +01005905 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005906 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005907 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005908 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005909 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005910 }
5911
Eric Laurent0dd51852019-04-19 18:18:58 -07005912 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005913 addInput(input, desc);
5914 }
5915 } // endif input != 0
5916
Eric Laurentcf2c0212014-07-25 16:20:43 -07005917 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08005918 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005919 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005920 profiles.removeAt(profile_index);
5921 profile_index--;
5922 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005923 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005924 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005925 }
Eric Laurentd4692962014-05-05 18:13:44 -07005926 ALOGV("checkInputsForDevice(): adding input %d", input);
5927 }
5928 } // end scan profiles
5929
5930 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005931 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005932 return BAD_VALUE;
5933 }
5934 } else {
5935 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005936 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005937 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005938 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005939 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005940 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005941 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005942 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005943 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5944 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005945 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005946 }
5947 }
5948 }
5949 } // end disconnect
5950
5951 return NO_ERROR;
5952}
5953
5954
Eric Laurente0720872014-03-11 09:30:41 -07005955void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005956{
5957 ALOGV("closeOutput(%d)", output);
5958
François Gaffie1c878552018-11-22 16:53:21 +01005959 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5960 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005961 ALOGW("closeOutput() unknown output %d", output);
5962 return;
5963 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005964 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005965 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005966
Eric Laurente552edb2014-03-10 17:42:56 -07005967 // look for duplicated outputs connected to the output being removed.
5968 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005969 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5970 if (dupOutput->isDuplicated() &&
5971 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5972 sp<SwAudioOutputDescriptor> remainingOutput =
5973 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005974 // As all active tracks on duplicated output will be deleted,
5975 // and as they were also referenced on the other output, the reference
5976 // count for their stream type must be adjusted accordingly on
5977 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005978 const bool wasActive = remainingOutput->isActive();
5979 // Note: no-op on the closing output where all clients has already been set inactive
5980 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005981 // stop() will be a no op if the output is still active but is needed in case all
5982 // active streams refcounts where cleared above
5983 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005984 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005985 }
Eric Laurente552edb2014-03-10 17:42:56 -07005986 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5987 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5988
5989 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005990 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005991 }
5992 }
5993
Eric Laurent05b90f82014-08-27 15:32:29 -07005994 nextAudioPortGeneration();
5995
François Gaffie1c878552018-11-22 16:53:21 +01005996 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005997 if (index >= 0) {
5998 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005999 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6000 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006001 mAudioPatches.removeItemsAt(index);
6002 mpClientInterface->onAudioPatchListUpdate();
6003 }
6004
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006005 if (closingOutputWasActive) {
6006 closingOutput->stop();
6007 }
François Gaffie1c878552018-11-22 16:53:21 +01006008 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006009
François Gaffie53615e22015-03-19 09:24:12 +01006010 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006011 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006012 if (closingOutput == mSpatializerOutput) {
6013 mSpatializerOutput.clear();
6014 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006015
6016 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6017 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006018 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006019 bool directOutputOpen = false;
6020 for (size_t i = 0; i < mOutputs.size(); i++) {
6021 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6022 directOutputOpen = true;
6023 break;
6024 }
6025 }
6026 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006027 ALOGV("no direct outputs open, reset MSD patches");
6028 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6029 // how output devices for patching are resolved. Avoid by caching and reusing the
6030 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6031 // devices to patch to. This may be complicated by the fact that devices may become
6032 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006033 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006034 }
6035 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006036}
6037
6038void AudioPolicyManager::closeInput(audio_io_handle_t input)
6039{
6040 ALOGV("closeInput(%d)", input);
6041
6042 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6043 if (inputDesc == NULL) {
6044 ALOGW("closeInput() unknown input %d", input);
6045 return;
6046 }
6047
Eric Laurent6a94d692014-05-20 11:18:06 -07006048 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006049
François Gaffie11d30102018-11-02 16:09:09 +01006050 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006051 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006052 if (index >= 0) {
6053 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006054 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6055 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006056 mAudioPatches.removeItemsAt(index);
6057 mpClientInterface->onAudioPatchListUpdate();
6058 }
6059
Eric Laurentfe231122017-11-17 17:48:06 -08006060 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006061 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006062
François Gaffie11d30102018-11-02 16:09:09 +01006063 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6064 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006065 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006066 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006067 }
Eric Laurente552edb2014-03-10 17:42:56 -07006068}
6069
François Gaffie11d30102018-11-02 16:09:09 +01006070SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6071 const DeviceVector &devices,
6072 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006073{
6074 SortedVector<audio_io_handle_t> outputs;
6075
François Gaffie11d30102018-11-02 16:09:09 +01006076 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006077 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006078 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006079 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006080 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006081 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006082 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006083 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006084 outputs.add(openOutputs.keyAt(i));
6085 }
6086 }
6087 return outputs;
6088}
6089
Mikhail Naganov37977152018-07-11 15:54:44 -07006090void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6091{
6092 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6093 // output is suspended before any tracks are moved to it
6094 checkA2dpSuspend();
6095 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006096 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006097 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006098 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006099 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006100 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6101 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6102 // configuration changes will ultimately be rerouted correctly. We can still avoid
6103 // unnecessary rerouting by caching and reusing the arguments to
6104 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6105 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006106 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006107 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006108 // an event that changed routing likely occurred, inform upper layers
6109 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006110}
6111
François Gaffiec005e562018-11-06 15:04:49 +01006112bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6113 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006114{
François Gaffiec005e562018-11-06 15:04:49 +01006115 return mEngine->getProductStrategyForAttributes(lAttr) ==
6116 mEngine->getProductStrategyForAttributes(rAttr);
6117}
6118
Francois Gaffieff1eb522020-05-06 18:37:04 +02006119void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6120{
6121 for (size_t i = 0; i < mAudioSources.size(); i++) {
6122 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6123 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006124 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
6125 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006126 connectAudioSource(sourceDesc);
6127 }
6128 }
6129}
6130
6131void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6132{
6133 for (size_t i = 0; i < mAudioSources.size(); i++) {
6134 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6135 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6136 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6137 disconnectAudioSource(sourceDesc);
6138 }
6139 }
6140}
6141
François Gaffiec005e562018-11-06 15:04:49 +01006142void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6143{
6144 auto psId = mEngine->getProductStrategyForAttributes(attr);
6145
6146 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6147 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006148
François Gaffie11d30102018-11-02 16:09:09 +01006149 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6150 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006151
Eric Laurentc209fe42020-06-05 18:11:23 -07006152 uint32_t maxLatency = 0;
6153 bool invalidate = false;
6154 // take into account dynamic audio policies related changes: if a client is now associated
6155 // to a different policy mix than at creation time, invalidate corresponding stream
6156 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6157 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6158 if (desc->isDuplicated()) {
6159 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006160 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006161 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6162 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6163 continue;
6164 }
6165 sp<AudioPolicyMix> primaryMix;
6166 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
6167 client->flags(), primaryMix, nullptr);
6168 if (status != OK) {
6169 continue;
6170 }
yucliuf4de36d2020-09-14 14:57:56 -07006171 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006172 invalidate = true;
6173 if (desc->isStrategyActive(psId)) {
6174 maxLatency = desc->latency();
6175 }
6176 break;
6177 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006178 }
6179 }
6180
Eric Laurentc209fe42020-06-05 18:11:23 -07006181 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006182 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6183 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006184 for (audio_io_handle_t srcOut : srcOutputs) {
6185 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006186 if (desc == nullptr) continue;
6187
6188 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006189 maxLatency = desc->latency();
6190 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006191
6192 if (invalidate) continue;
6193
6194 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006195 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006196 // a client on a non direct outputs has necessarily a linear PCM format
6197 // so we can call selectOutput() safely
6198 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6199 client->flags(),
6200 client->config().format,
6201 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006202 client->config().sample_rate,
6203 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006204 if (newOutput != srcOut) {
6205 invalidate = true;
6206 break;
6207 }
6208 } else {
6209 sp<IOProfile> profile = getProfileForOutput(newDevices,
6210 client->config().sample_rate,
6211 client->config().format,
6212 client->config().channel_mask,
6213 client->flags(),
6214 true /* directOnly */);
6215 if (profile != desc->mProfile) {
6216 invalidate = true;
6217 break;
6218 }
6219 }
6220 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006221 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006222
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006223 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006224 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006225 std::to_string(srcOutputs[0]).c_str(),
6226 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006227 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006228 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006229 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006230 if (desc == nullptr) continue;
6231
6232 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006233 setStrategyMute(psId, true, desc);
6234 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006235 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006236 }
François Gaffiec005e562018-11-06 15:04:49 +01006237 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006238 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006239 connectAudioSource(source);
6240 }
Eric Laurente552edb2014-03-10 17:42:56 -07006241 }
6242
François Gaffiec005e562018-11-06 15:04:49 +01006243 // Move effects associated to this stream from previous output to new output
6244 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006245 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006246 }
François Gaffiec005e562018-11-06 15:04:49 +01006247 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006248 if (invalidate) {
6249 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6250 mpClientInterface->invalidateStream(stream);
6251 }
Eric Laurente552edb2014-03-10 17:42:56 -07006252 }
6253 }
6254}
6255
Eric Laurente0720872014-03-11 09:30:41 -07006256void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006257{
François Gaffiec005e562018-11-06 15:04:49 +01006258 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6259 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6260 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006261 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006262 }
Eric Laurente552edb2014-03-10 17:42:56 -07006263}
6264
Kevin Rocard153f92d2018-12-18 18:33:28 -08006265void AudioPolicyManager::checkSecondaryOutputs() {
6266 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006267 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006268 for (size_t i = 0; i < mOutputs.size(); i++) {
6269 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6270 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006271 sp<AudioPolicyMix> primaryMix;
6272 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006273 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006274 client->flags(), primaryMix, &secondaryMixes);
6275 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6276 for (auto &secondaryMix : secondaryMixes) {
6277 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6278 if (outputDesc != nullptr &&
6279 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6280 secondaryDescs.push_back(outputDesc);
6281 }
6282 }
6283
jiabin10a03f12021-05-07 23:46:28 +00006284 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006285 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006286 } else if (!std::equal(
6287 client->getSecondaryOutputs().begin(),
6288 client->getSecondaryOutputs().end(),
6289 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006290 if (!audio_is_linear_pcm(client->config().format)) {
6291 // If the format is not PCM, the tracks should be invalidated to get correct
6292 // behavior when the secondary output is changed.
6293 streamsToInvalidate.insert(client->stream());
6294 } else {
6295 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6296 std::vector<audio_io_handle_t> secondaryOutputIds;
6297 for (const auto &secondaryDesc: secondaryDescs) {
6298 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6299 weakSecondaryDescs.push_back(secondaryDesc);
6300 }
6301 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6302 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006303 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006304 }
6305 }
6306 }
jiabin10a03f12021-05-07 23:46:28 +00006307 if (!trackSecondaryOutputs.empty()) {
6308 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6309 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006310 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006311 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006312 mpClientInterface->invalidateStream(stream);
6313 }
6314}
6315
Eric Laurent2517af32020-11-25 15:31:27 +01006316bool AudioPolicyManager::isScoRequestedForComm() const {
6317 AudioDeviceTypeAddrVector devices;
6318 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6319 for (const auto &device : devices) {
6320 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6321 return true;
6322 }
6323 }
6324 return false;
6325}
6326
Eric Laurente0720872014-03-11 09:30:41 -07006327void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006328{
François Gaffie53615e22015-03-19 09:24:12 +01006329 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006330 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006331 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006332 return;
6333 }
6334
Eric Laurent3a4311c2014-03-17 12:00:47 -07006335 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006336 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6337 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006338 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006339
6340 // if suspended, restore A2DP output if:
6341 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006342 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006343 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006344 //
Eric Laurentf732e072016-08-03 19:30:28 -07006345 // if not suspended, suspend A2DP output if:
6346 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006347 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006348 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006349 //
6350 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006351 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006352 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006353 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006354 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006355
6356 mpClientInterface->restoreOutput(a2dpOutput);
6357 mA2dpSuspended = false;
6358 }
6359 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006360 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006361 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006362 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006363 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006364
6365 mpClientInterface->suspendOutput(a2dpOutput);
6366 mA2dpSuspended = true;
6367 }
6368 }
6369}
6370
François Gaffie11d30102018-11-02 16:09:09 +01006371DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6372 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006373{
François Gaffie11d30102018-11-02 16:09:09 +01006374 DeviceVector devices;
6375
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006376 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006377 if (index >= 0) {
6378 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006379 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006380 ALOGV("%s device %s forced by patch %d", __func__,
6381 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6382 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006383 }
6384 }
6385
Dean Wheatley514b4312020-06-17 21:45:00 +10006386 // Do not retrieve engine device for outputs through MSD
6387 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6388 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6389 return outputDesc->devices();
6390 }
6391
Eric Laurent97ac8712018-07-27 18:59:02 -07006392 // Honor explicit routing requests only if no client using default routing is active on this
6393 // input: a specific app can not force routing for other apps by setting a preferred device.
6394 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006395 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006396 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006397 if (device != nullptr) {
6398 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006399 }
6400
François Gaffiea807ef92018-11-05 10:44:33 +01006401 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6402 // of setForceUse / Default Bus device here
6403 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6404 if (device != nullptr) {
6405 return DeviceVector(device);
6406 }
6407
François Gaffiec005e562018-11-06 15:04:49 +01006408 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6409 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6410 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306411 auto hasStreamActive = [&](auto stream) {
6412 return hasStream(streams, stream) && isStreamActive(stream, 0);
6413 };
Eric Laurent484e9272018-06-07 17:29:23 -07006414
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306415 auto doGetOutputDevicesForVoice = [&]() {
6416 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006417 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306418 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006419 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6420 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306421 };
6422
6423 // With low-latency playing on speaker, music on WFD, when the first low-latency
6424 // output is stopped, getNewOutputDevices checks for a product strategy
6425 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006426 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306427 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6428 // stream is associated to the output descriptor.
6429 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6430 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6431 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6432 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006433 // Retrieval of devices for voice DL is done on primary output profile, cannot
6434 // check the route (would force modifying configuration file for this profile)
6435 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6436 break;
6437 }
Eric Laurente552edb2014-03-10 17:42:56 -07006438 }
François Gaffiec005e562018-11-06 15:04:49 +01006439 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006440 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006441}
6442
François Gaffie11d30102018-11-02 16:09:09 +01006443sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6444 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006445{
François Gaffie11d30102018-11-02 16:09:09 +01006446 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006447
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006448 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006449 if (index >= 0) {
6450 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006451 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006452 ALOGV("getNewInputDevice() device %s forced by patch %d",
6453 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6454 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006455 }
6456 }
6457
Eric Laurent97ac8712018-07-27 18:59:02 -07006458 // Honor explicit routing requests only if no client using default routing is active on this
6459 // input: a specific app can not force routing for other apps by setting a preferred device.
6460 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006461 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6462 if (device != nullptr) {
6463 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006464 }
6465
Eric Laurentdc95a252018-04-12 12:46:56 -07006466 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006467 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006468 audio_attributes_t attributes;
6469 uid_t uid;
6470 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6471 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006472 attributes = topClient->attributes();
6473 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006474 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006475 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6476 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006477 }
6478
Francois Gaffie716e1432019-01-14 16:58:59 +01006479 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6480 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006481 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006482 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006483 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006484 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006485
Eric Laurente552edb2014-03-10 17:42:56 -07006486 return device;
6487}
6488
Eric Laurent794fde22016-03-11 09:50:45 -08006489bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6490 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006491 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006492}
6493
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006494DeviceTypeSet AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006495 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006496 // getOutputDevicesForStream's behavior for invalid streams.
6497 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6498 // device for music stream), but we want to return the empty set.
6499 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006500 return DeviceTypeSet{};
Eric Laurent6a94d692014-05-20 11:18:06 -07006501 }
François Gaffie11d30102018-11-02 16:09:09 +01006502 DeviceVector activeDevices;
6503 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006504 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6505 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006506 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006507 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006508 }
François Gaffiec005e562018-11-06 15:04:49 +01006509 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006510 devices.merge(curDevices);
6511 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006512 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006513 if (outputDesc->isActive(toVolumeSource(curStream, false))) {
François Gaffie11d30102018-11-02 16:09:09 +01006514 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006515 }
6516 }
Eric Laurente552edb2014-03-10 17:42:56 -07006517 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006518
Eric Laurentb0688d62018-08-14 15:49:18 -07006519 // Favor devices selected on active streams if any to report correct device in case of
6520 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006521 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006522 devices = activeDevices;
6523 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006524 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6525 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006526 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006527 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006528 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006529 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006530 }
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006531 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07006532}
6533
Dorin Drimusf2196d82022-01-03 12:11:18 +01006534// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006535status_t AudioPolicyManager::getDevicesForAttributes(
6536 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
6537 if (devices == nullptr) {
6538 return BAD_VALUE;
6539 }
6540 // check dynamic policies but only for primary descriptors (secondary not used for audible
6541 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006542 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006543 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07006544 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006545 if (status != OK) {
6546 return status;
6547 }
Eric Laurentc529cf62020-04-17 18:19:10 -07006548 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
6549 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
6550 devices->push_back(device);
6551 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006552 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006553 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6554 for (const auto& device : curDevices) {
6555 devices->push_back(device->getDeviceTypeAddr());
6556 }
6557 return NO_ERROR;
6558}
6559
Eric Laurente0720872014-03-11 09:30:41 -07006560void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006561 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006562 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006563 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006564 updateDevicesAndOutputs();
6565 break;
6566 default:
6567 break;
6568 }
6569}
6570
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006571uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006572
6573 // skip beacon mute management if a dedicated TTS output is available
6574 if (mTtsOutputAvailable) {
6575 return 0;
6576 }
6577
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006578 switch(event) {
6579 case STARTING_OUTPUT:
6580 mBeaconMuteRefCount++;
6581 break;
6582 case STOPPING_OUTPUT:
6583 if (mBeaconMuteRefCount > 0) {
6584 mBeaconMuteRefCount--;
6585 }
6586 break;
6587 case STARTING_BEACON:
6588 mBeaconPlayingRefCount++;
6589 break;
6590 case STOPPING_BEACON:
6591 if (mBeaconPlayingRefCount > 0) {
6592 mBeaconPlayingRefCount--;
6593 }
6594 break;
6595 }
6596
6597 if (mBeaconMuteRefCount > 0) {
6598 // any playback causes beacon to be muted
6599 return setBeaconMute(true);
6600 } else {
6601 // no other playback: unmute when beacon starts playing, mute when it stops
6602 return setBeaconMute(mBeaconPlayingRefCount == 0);
6603 }
6604}
6605
6606uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6607 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6608 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6609 // keep track of muted state to avoid repeating mute/unmute operations
6610 if (mBeaconMuted != mute) {
6611 // mute/unmute AUDIO_STREAM_TTS on all outputs
6612 ALOGV("\t muting %d", mute);
6613 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006614 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6615 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6616 ALOGV("\t no tts volume source available");
6617 return 0;
6618 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006619 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006620 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006621 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006622 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006623 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006624 maxLatency = latency;
6625 }
6626 }
6627 mBeaconMuted = mute;
6628 return maxLatency;
6629 }
6630 return 0;
6631}
6632
Eric Laurente0720872014-03-11 09:30:41 -07006633void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006634{
François Gaffiec005e562018-11-06 15:04:49 +01006635 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006636 mPreviousOutputs = mOutputs;
6637}
6638
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006639uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006640 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006641 uint32_t delayMs)
6642{
6643 // mute/unmute strategies using an incompatible device combination
6644 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6645 // if unmuting, unmute only after the specified delay
6646 if (outputDesc->isDuplicated()) {
6647 return 0;
6648 }
6649
6650 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006651 DeviceVector devices = outputDesc->devices();
6652 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006653
François Gaffiec005e562018-11-06 15:04:49 +01006654 auto productStrategies = mEngine->getOrderedProductStrategies();
6655 for (const auto &productStrategy : productStrategies) {
6656 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6657 DeviceVector curDevices =
6658 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6659 curDevices = curDevices.filter(outputDesc->supportedDevices());
6660 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006661 bool doMute = false;
6662
François Gaffiec005e562018-11-06 15:04:49 +01006663 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006664 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006665 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6666 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006667 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006668 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006669 }
Eric Laurent99401132014-05-07 19:48:15 -07006670 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006671 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006672 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006673 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006674 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006675 continue;
6676 }
François Gaffiec005e562018-11-06 15:04:49 +01006677 ALOGVV("%s() %s (curDevice %s)", __func__,
6678 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6679 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6680 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006681 if (mute) {
6682 // FIXME: should not need to double latency if volume could be applied
6683 // immediately by the audioflinger mixer. We must account for the delay
6684 // between now and the next time the audioflinger thread for this output
6685 // will process a buffer (which corresponds to one buffer size,
6686 // usually 1/2 or 1/4 of the latency).
6687 if (muteWaitMs < desc->latency() * 2) {
6688 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006689 }
6690 }
6691 }
6692 }
6693 }
6694 }
6695
Eric Laurent99401132014-05-07 19:48:15 -07006696 // temporary mute output if device selection changes to avoid volume bursts due to
6697 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006698 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006699 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006700
Eric Laurentdc462862016-07-19 12:29:53 -07006701 if (muteWaitMs < tempMuteWaitMs) {
6702 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006703 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006704
6705 // If recommended duration is defined, replace temporary mute duration to avoid
6706 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6707 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6708 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6709 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6710 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6711
François Gaffieaaac0fd2018-11-22 17:56:39 +01006712 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6713 // make sure that we do not start the temporary mute period too early in case of
6714 // delayed device change
6715 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6716 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006717 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006718 }
6719 }
6720
Eric Laurente552edb2014-03-10 17:42:56 -07006721 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6722 if (muteWaitMs > delayMs) {
6723 muteWaitMs -= delayMs;
6724 usleep(muteWaitMs * 1000);
6725 return muteWaitMs;
6726 }
6727 return 0;
6728}
6729
François Gaffie11d30102018-11-02 16:09:09 +01006730uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6731 const DeviceVector &devices,
6732 bool force,
6733 int delayMs,
6734 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006735 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006736{
François Gaffie11d30102018-11-02 16:09:09 +01006737 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006738 uint32_t muteWaitMs;
6739
6740 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006741 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6742 nullptr /* patchHandle */, requiresMuteCheck);
6743 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6744 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006745 return muteWaitMs;
6746 }
Eric Laurente552edb2014-03-10 17:42:56 -07006747
6748 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006749 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006750 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006751 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006752
François Gaffie11d30102018-11-02 16:09:09 +01006753 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6754
6755 if (!filteredDevices.isEmpty()) {
6756 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006757 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006758
6759 // if the outputs are not materially active, there is no need to mute.
6760 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006761 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006762 } else {
6763 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6764 muteWaitMs = 0;
6765 }
Eric Laurente552edb2014-03-10 17:42:56 -07006766
Eric Laurent79ea9582020-06-11 18:49:24 -07006767 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6768 // output profile or if new device is not supported AND previous device(s) is(are) still
6769 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006770 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006771 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6772 // restore previous device after evaluating strategy mute state
6773 outputDesc->setDevices(prevDevices);
6774 return muteWaitMs;
6775 }
6776
Eric Laurente552edb2014-03-10 17:42:56 -07006777 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006778 // the requested device is AUDIO_DEVICE_NONE
6779 // OR the requested device is the same as current device
6780 // AND force is not specified
6781 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006782 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006783 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
Francois Gaffie3523ab32021-06-22 13:24:34 +02006784 !force && outputDesc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006785 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6786 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006787 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6788 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6789 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6790 }
Eric Laurente552edb2014-03-10 17:42:56 -07006791 return muteWaitMs;
6792 }
6793
François Gaffie11d30102018-11-02 16:09:09 +01006794 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006795
Eric Laurente552edb2014-03-10 17:42:56 -07006796 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006797 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006798 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006799 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006800 PatchBuilder patchBuilder;
6801 patchBuilder.addSource(outputDesc);
6802 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6803 for (const auto &filteredDevice : filteredDevices) {
6804 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006805 }
6806
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006807 // Add half reported latency to delayMs when muteWaitMs is null in order
6808 // to avoid disordered sequence of muting volume and changing devices.
6809 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6810 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006811 }
Eric Laurente552edb2014-03-10 17:42:56 -07006812
6813 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006814 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006815
6816 return muteWaitMs;
6817}
6818
Eric Laurentc75307b2015-03-17 15:29:32 -07006819status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006820 int delayMs,
6821 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006822{
Eric Laurent6a94d692014-05-20 11:18:06 -07006823 ssize_t index;
6824 if (patchHandle) {
6825 index = mAudioPatches.indexOfKey(*patchHandle);
6826 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006827 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006828 }
6829 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006830 return INVALID_OPERATION;
6831 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006832 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006833 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006834 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006835 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006836 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006837 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006838 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006839 return status;
6840}
6841
6842status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006843 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006844 bool force,
6845 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006846{
6847 status_t status = NO_ERROR;
6848
Eric Laurent1f2f2232014-06-02 12:01:23 -07006849 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006850 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6851 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006852
François Gaffie11d30102018-11-02 16:09:09 +01006853 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006854 PatchBuilder patchBuilder;
6855 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006856 // AUDIO_SOURCE_HOTWORD is for internal use only:
6857 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006858 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6859 auto result = usecase;
6860 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6861 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6862 }
6863 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006864 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006865 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006866 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006867 }
6868 }
6869 return status;
6870}
6871
Eric Laurent6a94d692014-05-20 11:18:06 -07006872status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6873 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006874{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006875 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006876 ssize_t index;
6877 if (patchHandle) {
6878 index = mAudioPatches.indexOfKey(*patchHandle);
6879 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006880 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006881 }
6882 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006883 return INVALID_OPERATION;
6884 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006885 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006886 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006887 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006888 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006889 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006890 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006891 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006892 return status;
6893}
6894
François Gaffie11d30102018-11-02 16:09:09 +01006895sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006896 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006897 audio_format_t& format,
6898 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006899 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006900{
6901 // Choose an input profile based on the requested capture parameters: select the first available
6902 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006903 //
6904 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6905 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006906
Glenn Kasten730b9262018-03-29 15:01:26 -07006907 sp<IOProfile> firstInexact;
6908 uint32_t updatedSamplingRate = 0;
6909 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6910 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006911 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006912 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006913 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006914 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006915 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006916 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006917 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006918 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006919 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006920 &channelMask /*updatedChannelMask*/,
6921 // FIXME ugly cast
6922 (audio_output_flags_t) flags,
6923 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006924 return profile;
6925 }
François Gaffie11d30102018-11-02 16:09:09 +01006926 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006927 samplingRate,
6928 &updatedSamplingRate,
6929 format,
6930 &updatedFormat,
6931 channelMask,
6932 &updatedChannelMask,
6933 // FIXME ugly cast
6934 (audio_output_flags_t) flags,
6935 false /*exactMatchRequiredForInputFlags*/)) {
6936 firstInexact = profile;
6937 }
6938
Eric Laurente552edb2014-03-10 17:42:56 -07006939 }
6940 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006941 if (firstInexact != nullptr) {
6942 samplingRate = updatedSamplingRate;
6943 format = updatedFormat;
6944 channelMask = updatedChannelMask;
6945 return firstInexact;
6946 }
Eric Laurente552edb2014-03-10 17:42:56 -07006947 return NULL;
6948}
6949
François Gaffieaaac0fd2018-11-22 17:56:39 +01006950float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6951 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006952 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006953 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006954{
jiabin9a3361e2019-10-01 09:38:30 -07006955 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006956
6957 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6958 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6959 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6960 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006961 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
6962 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
6963 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
6964 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
6965 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006966
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006967 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006968 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6969 mOutputs.isActive(ringVolumeSrc, 0)) {
6970 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006971 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006972 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006973 }
6974
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006975 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006976 if ((volumeSource != callVolumeSrc && (isInCall() ||
6977 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006978 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006979 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6980 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006981 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
6982 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
6983 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006984 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006985 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006986 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006987 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006988 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006989 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006990 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6991 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6992 // programmatically muted.
6993 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6994 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6995 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006996 bool exemptFromCapping =
6997 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6998 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006999 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7000 volumeSource, volumeDb);
7001 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007002 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7003 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7004 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007005 }
7006 }
Eric Laurente552edb2014-03-10 17:42:56 -07007007 // if a headset is connected, apply the following rules to ring tones and notifications
7008 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007009 // - always attenuate notifications volume by 6dB
7010 // - attenuate ring tones volume by 6dB unless music is not playing and
7011 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007012 // - if music is playing, always limit the volume to current music volume,
7013 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007014 if (!Intersection(deviceTypes,
7015 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7016 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007017 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7018 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007019 ((volumeSource == alarmVolumeSrc ||
7020 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007021 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7022 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7023 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007024 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7025 curves.canBeMuted()) {
7026
Eric Laurente552edb2014-03-10 17:42:56 -07007027 // when the phone is ringing we must consider that music could have been paused just before
7028 // by the music application and behave as if music was active if the last music track was
7029 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007030 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007031 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007032 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007033 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007034 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7035 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007036 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007037 float musicVolDb = computeVolume(musicCurves,
7038 musicVolumeSrc,
7039 musicCurves.getVolumeIndex(musicDevice),
7040 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007041 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7042 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7043 if (volumeDb > minVolDb) {
7044 volumeDb = minVolDb;
7045 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007046 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007047 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7048 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7049 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007050 // on A2DP, also ensure notification volume is not too low compared to media when
7051 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007052 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007053 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007054 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7055 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007056 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7057 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007058 }
7059 }
jiabin9a3361e2019-10-01 09:38:30 -07007060 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007061 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007062 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007063 }
7064 }
7065
François Gaffie43c73442018-11-08 08:21:55 +01007066 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007067}
7068
Eric Laurent3839bc02018-07-10 18:33:34 -07007069int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007070 VolumeSource fromVolumeSource,
7071 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007072{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007073 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007074 return srcIndex;
7075 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007076 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7077 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007078 float minSrc = (float)srcCurves.getVolumeIndexMin();
7079 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7080 float minDst = (float)dstCurves.getVolumeIndexMin();
7081 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007082
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007083 // preserve mute request or correct range
7084 if (srcIndex < minSrc) {
7085 if (srcIndex == 0) {
7086 return 0;
7087 }
7088 srcIndex = minSrc;
7089 } else if (srcIndex > maxSrc) {
7090 srcIndex = maxSrc;
7091 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007092 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7093}
7094
François Gaffieaaac0fd2018-11-22 17:56:39 +01007095status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7096 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007097 int index,
7098 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007099 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007100 int delayMs,
7101 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007102{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007103 // do not change actual attributes volume if the attributes is muted
7104 if (outputDesc->isMuted(volumeSource)) {
7105 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7106 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007107 return NO_ERROR;
7108 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007109 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7110 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7111 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7112 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007113
Eric Laurent2517af32020-11-25 15:31:27 +01007114 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07007115 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007116 // if sco and call follow same curves, bypass forceUseForComm
7117 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007118 ((isVoiceVolSrc && isScoRequested) ||
7119 (isBtScoVolSrc && !isScoRequested))) {
7120 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
7121 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07007122 // Do not return an error here as AudioService will always set both voice call
7123 // and bluetooth SCO volumes due to stream aliasing.
7124 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007125 }
jiabin9a3361e2019-10-01 09:38:30 -07007126 if (deviceTypes.empty()) {
7127 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007128 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007129
jiabin9a3361e2019-10-01 09:38:30 -07007130 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7131 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007132 // Force VoIP volume to max for bluetooth SCO device except if muted
7133 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007134 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007135 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007136 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007137 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007138 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007139 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007140
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007141 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007142 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007143 // 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 +01007144 if (isVoiceVolSrc) {
7145 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007146 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007147 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007148 }
Eric Laurent18fba842016-03-31 14:41:26 -07007149 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007150 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7151 mLastVoiceVolume = voiceVolume;
7152 }
7153 }
Eric Laurente552edb2014-03-10 17:42:56 -07007154 return NO_ERROR;
7155}
7156
Eric Laurentc75307b2015-03-17 15:29:32 -07007157void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007158 const DeviceTypeSet& deviceTypes,
7159 int delayMs,
7160 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007161{
jiabincd510522020-01-22 09:40:55 -08007162 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007163 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7164 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7165 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007166 curves.getVolumeIndex(deviceTypes),
7167 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007168 }
7169}
7170
François Gaffiec005e562018-11-06 15:04:49 +01007171void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7172 bool on,
7173 const sp<AudioOutputDescriptor>& outputDesc,
7174 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007175 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007176{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007177 std::vector<VolumeSource> sourcesToMute;
7178 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7179 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7180 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007181 VolumeSource source = toVolumeSource(attributes, false);
7182 if ((source != VOLUME_SOURCE_NONE) &&
7183 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7184 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007185 sourcesToMute.push_back(source);
7186 }
Eric Laurente552edb2014-03-10 17:42:56 -07007187 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007188 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007189 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007190 }
7191
Eric Laurente552edb2014-03-10 17:42:56 -07007192}
7193
François Gaffieaaac0fd2018-11-22 17:56:39 +01007194void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7195 bool on,
7196 const sp<AudioOutputDescriptor>& outputDesc,
7197 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007198 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007199{
jiabin9a3361e2019-10-01 09:38:30 -07007200 if (deviceTypes.empty()) {
7201 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007202 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007203 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007204 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007205 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007206 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007207 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007208 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7209 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007210 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007211 }
7212 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007213 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7214 // ignored
7215 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007216 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007217 if (!outputDesc->isMuted(volumeSource)) {
7218 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007219 return;
7220 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007221 if (outputDesc->decMuteCount(volumeSource) == 0) {
7222 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007223 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007224 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007225 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007226 delayMs);
7227 }
7228 }
7229}
7230
François Gaffie53615e22015-03-19 09:24:12 +01007231bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7232{
François Gaffiec005e562018-11-06 15:04:49 +01007233 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007234 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7235 return true;
7236 }
7237
7238 // has known usage?
7239 switch (paa->usage) {
7240 case AUDIO_USAGE_UNKNOWN:
7241 case AUDIO_USAGE_MEDIA:
7242 case AUDIO_USAGE_VOICE_COMMUNICATION:
7243 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7244 case AUDIO_USAGE_ALARM:
7245 case AUDIO_USAGE_NOTIFICATION:
7246 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7247 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7248 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7249 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7250 case AUDIO_USAGE_NOTIFICATION_EVENT:
7251 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7252 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7253 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7254 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007255 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007256 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007257 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007258 case AUDIO_USAGE_EMERGENCY:
7259 case AUDIO_USAGE_SAFETY:
7260 case AUDIO_USAGE_VEHICLE_STATUS:
7261 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007262 break;
7263 default:
7264 return false;
7265 }
7266 return true;
7267}
7268
François Gaffie2110e042015-03-24 08:41:51 +01007269audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7270{
7271 return mEngine->getForceUse(usage);
7272}
7273
7274bool AudioPolicyManager::isInCall()
7275{
7276 return isStateInCall(mEngine->getPhoneState());
7277}
7278
7279bool AudioPolicyManager::isStateInCall(int state)
7280{
7281 return is_state_in_call(state);
7282}
7283
Eric Laurent74b71512019-11-06 17:21:57 -08007284bool AudioPolicyManager::isCallAudioAccessible()
7285{
7286 audio_mode_t mode = mEngine->getPhoneState();
7287 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007288 || (mode == AUDIO_MODE_CALL_SCREEN)
7289 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007290}
7291
Eric Laurentd60560a2015-04-10 11:31:20 -07007292void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7293{
7294 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007295 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007296 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007297 sourceDesc->sinkDevice()->equals(deviceDesc))
7298 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007299 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007300 }
7301 }
7302
7303 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7304 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7305 bool release = false;
7306 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7307 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7308 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7309 source->ext.device.type == deviceDesc->type()) {
7310 release = true;
7311 }
7312 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007313 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007314 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7315 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7316 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007317 sink->ext.device.type == deviceDesc->type() &&
7318 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7319 || strncmp(sink->ext.device.address, address,
7320 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007321 release = true;
7322 }
7323 }
7324 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007325 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7326 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007327 }
7328 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007329
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007330 mInputs.clearSessionRoutesForDevice(deviceDesc);
7331
Francois Gaffie716e1432019-01-14 16:58:59 +01007332 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007333}
7334
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007335void AudioPolicyManager::modifySurroundFormats(
7336 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007337 std::unordered_set<audio_format_t> enforcedSurround(
7338 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007339 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7340 for (const auto& pair : mConfig.getSurroundFormats()) {
7341 allSurround.insert(pair.first);
7342 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7343 }
Phil Burk09bc4612016-02-24 15:58:15 -08007344
7345 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7346 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007347 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007348 // This is the resulting set of formats depending on the surround mode:
7349 // 'all surround' = allSurround
7350 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7351 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7352 // 'manual surround' = mManualSurroundFormats
7353 // AUTO: formats v 'enforced surround'
7354 // ALWAYS: formats v 'all surround' v 'enforced surround'
7355 // NEVER: formats ^ 'non-surround'
7356 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007357
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007358 std::unordered_set<audio_format_t> formatSet;
7359 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7360 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007361 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007362 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007363 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007364 formatSet.insert(*formatIter);
7365 }
7366 }
7367 } else {
7368 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7369 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007370 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007371
jiabin81772902018-04-02 17:52:27 -07007372 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007373 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007374 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7375 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7376 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007377 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007378 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7379 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7380 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007381 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007382 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007383 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007384 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007385 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007386 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007387}
7388
jiabin06e4bab2019-07-29 10:13:34 -07007389void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7390 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007391 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7392 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7393
7394 // If NEVER, then remove support for channelMasks > stereo.
7395 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007396 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7397 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007398 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007399 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007400 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007401 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007402 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007403 }
7404 }
jiabin81772902018-04-02 17:52:27 -07007405 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7406 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7407 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007408 bool supports5dot1 = false;
7409 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007410 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007411 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7412 supports5dot1 = true;
7413 break;
7414 }
7415 }
7416 // If not then add 5.1 support.
7417 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007418 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007419 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007420 }
Phil Burk09bc4612016-02-24 15:58:15 -08007421 }
7422}
7423
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007424void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007425 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007426 AudioProfileVector &profiles)
7427{
7428 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007429 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007430
François Gaffie112b0af2015-11-19 16:13:25 +01007431 // Format MUST be checked first to update the list of AudioProfile
7432 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007433 reply = mpClientInterface->getParameters(
7434 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007435 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007436 AudioParameter repliedParameters(reply);
7437 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007438 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007439 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7440 return;
7441 }
Phil Burk09bc4612016-02-24 15:58:15 -08007442 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007443 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007444 if (device == AUDIO_DEVICE_OUT_HDMI
7445 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007446 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007447 }
jiabin3e277cc2019-09-10 14:27:34 -07007448 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007449 }
François Gaffie112b0af2015-11-19 16:13:25 +01007450
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007451 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007452 ChannelMaskSet channelMasks;
7453 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007454 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007455 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007456
7457 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007458 reply = mpClientInterface->getParameters(
7459 ioHandle,
7460 requestedParameters.toString() + ";" +
7461 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007462 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007463 AudioParameter repliedParameters(reply);
7464 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007465 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007466 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007467 }
7468 }
7469 if (profiles.hasDynamicChannelsFor(format)) {
7470 reply = mpClientInterface->getParameters(ioHandle,
7471 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007472 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007473 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007474 AudioParameter repliedParameters(reply);
7475 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007476 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007477 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007478 if (device == AUDIO_DEVICE_OUT_HDMI
7479 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007480 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007481 }
François Gaffie112b0af2015-11-19 16:13:25 +01007482 }
7483 }
jiabin3e277cc2019-09-10 14:27:34 -07007484 addDynamicAudioProfileAndSort(
7485 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007486 }
7487}
Eric Laurentd60560a2015-04-10 11:31:20 -07007488
Mikhail Naganovdc769682018-05-04 15:34:08 -07007489status_t AudioPolicyManager::installPatch(const char *caller,
7490 audio_patch_handle_t *patchHandle,
7491 AudioIODescriptorInterface *ioDescriptor,
7492 const struct audio_patch *patch,
7493 int delayMs)
7494{
7495 ssize_t index = mAudioPatches.indexOfKey(
7496 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7497 *patchHandle : ioDescriptor->getPatchHandle());
7498 sp<AudioPatch> patchDesc;
7499 status_t status = installPatch(
7500 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7501 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007502 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007503 }
7504 return status;
7505}
7506
7507status_t AudioPolicyManager::installPatch(const char *caller,
7508 ssize_t index,
7509 audio_patch_handle_t *patchHandle,
7510 const struct audio_patch *patch,
7511 int delayMs,
7512 uid_t uid,
7513 sp<AudioPatch> *patchDescPtr)
7514{
7515 sp<AudioPatch> patchDesc;
7516 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7517 if (index >= 0) {
7518 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007519 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007520 }
7521
7522 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7523 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7524 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7525 if (status == NO_ERROR) {
7526 if (index < 0) {
7527 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007528 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007529 } else {
7530 patchDesc->mPatch = *patch;
7531 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007532 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007533 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007534 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007535 }
7536 nextAudioPortGeneration();
7537 mpClientInterface->onAudioPatchListUpdate();
7538 }
7539 if (patchDescPtr) *patchDescPtr = patchDesc;
7540 return status;
7541}
7542
jiabinbce0c1d2020-10-05 11:20:18 -07007543bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7544{
7545 const TrackClientVector activeClients = output->getActiveClients();
7546 if (activeClients.empty()) {
7547 return true;
7548 }
7549 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7550 if (index < 0) {
7551 ALOGE("%s, no audio patch found while there are active clients on output %d",
7552 __func__, output->getId());
7553 return false;
7554 }
7555 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7556 DeviceVector routedDevices;
7557 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7558 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7559 patchDesc->mPatch.sinks[i].id);
7560 if (device == nullptr) {
7561 ALOGE("%s, no audio device found with id(%d)",
7562 __func__, patchDesc->mPatch.sinks[i].id);
7563 return false;
7564 }
7565 routedDevices.add(device);
7566 }
7567 for (const auto& client : activeClients) {
7568 // TODO: b/175343099 only travel the valid client
7569 sp<DeviceDescriptor> preferredDevice =
7570 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7571 if (mEngine->getOutputDevicesForAttributes(
7572 client->attributes(), preferredDevice, false) == routedDevices) {
7573 return false;
7574 }
7575 }
7576 return true;
7577}
7578
7579sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007580 const sp<IOProfile>& profile, const DeviceVector& devices,
7581 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007582{
7583 for (const auto& device : devices) {
7584 // TODO: This should be checking if the profile supports the device combo.
7585 if (!profile->supportsDevice(device)) {
7586 return nullptr;
7587 }
7588 }
7589 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7590 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007591 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007592 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7593 if (status != NO_ERROR) {
7594 return nullptr;
7595 }
7596
7597 // Here is where the out_set_parameters() for card & device gets called
7598 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7599 const audio_devices_t deviceType = device->type();
7600 const String8 &address = String8(device->address().c_str());
7601 if (!address.isEmpty()) {
7602 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7603 mpClientInterface->setParameters(output, String8(param));
7604 free(param);
7605 }
7606 updateAudioProfiles(device, output, profile->getAudioProfiles());
7607 if (!profile->hasValidAudioProfile()) {
7608 ALOGW("%s() missing param", __func__);
7609 desc->close();
7610 return nullptr;
7611 } else if (profile->hasDynamicAudioProfile()) {
7612 desc->close();
7613 output = AUDIO_IO_HANDLE_NONE;
7614 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7615 profile->pickAudioProfile(
7616 config.sample_rate, config.channel_mask, config.format);
7617 config.offload_info.sample_rate = config.sample_rate;
7618 config.offload_info.channel_mask = config.channel_mask;
7619 config.offload_info.format = config.format;
7620
Eric Laurentb4f42a92022-01-17 17:37:31 +01007621 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007622 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7623 if (status != NO_ERROR) {
7624 return nullptr;
7625 }
7626 }
7627
7628 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007629
jiabinbce0c1d2020-10-05 11:20:18 -07007630 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7631 sp<AudioPolicyMix> policyMix;
7632 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7633 policyMix->setOutput(desc);
7634 desc->mPolicyMix = policyMix;
7635 } else {
7636 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7637 address.string());
7638 }
7639
Eric Laurentb4f42a92022-01-17 17:37:31 +01007640 } else if (hasPrimaryOutput() && profile->getModule()
7641 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7642 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7643 // no duplicated output for:
7644 // - direct outputs
7645 // - outputs used by dynamic policy mixes
7646 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007647 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7648
7649 //TODO: configure audio effect output stage here
7650
7651 // open a duplicating output thread for the new output and the primary output
7652 sp<SwAudioOutputDescriptor> dupOutputDesc =
7653 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7654 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7655 if (status == NO_ERROR) {
7656 // add duplicated output descriptor
7657 addOutput(duplicatedOutput, dupOutputDesc);
7658 } else {
7659 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7660 mPrimaryOutput->mIoHandle, output);
7661 desc->close();
7662 removeOutput(output);
7663 nextAudioPortGeneration();
7664 return nullptr;
7665 }
7666 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007667 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7668 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7669 mPrimaryOutput = desc;
7670 }
jiabinbce0c1d2020-10-05 11:20:18 -07007671 return desc;
7672}
7673
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007674} // namespace android