blob: 4bade63ba6301243dc1b69153c4f943dd18433d2 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080037#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110038#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070039
40#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010041#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070042#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070044#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070045#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070046#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070047#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070048#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070049#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <utils/Log.h>
51
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010053#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010057using android::media::audio::common::AudioDevice;
58using android::media::audio::common::AudioDeviceAddress;
59using android::media::audio::common::AudioPortDeviceExt;
60using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000061using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070062
Eric Laurentdc462862016-07-19 12:29:53 -070063//FIXME: workaround for truncated touch sounds
64// to be removed when the problem is handled by system UI
65#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070066
67// Largest difference in dB on earpiece in call between the voice volume and another
68// media / notification / system volume.
69constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
70
Mikhail Naganov15be9d22017-11-08 14:18:13 +110071// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110072static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
73 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110074 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
75// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110076static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110077 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
78 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
79 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
80
jiabin06e4bab2019-07-29 10:13:34 -070081template <typename T>
82bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
83{
84 if (left.size() != right.size()) {
85 return false;
86 }
87 for (size_t index = 0; index < right.size(); index++) {
88 if (left[index] != right[index]) {
89 return false;
90 }
91 }
92 return true;
93}
94
95template <typename T>
96bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
97{
98 return !(left == right);
99}
100
Eric Laurente552edb2014-03-10 17:42:56 -0700101// ----------------------------------------------------------------------------
102// AudioPolicyInterface implementation
103// ----------------------------------------------------------------------------
104
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100105status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
106 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
107 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800108 nextAudioPortGeneration();
109 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110}
111
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100112status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
113 audio_policy_dev_state_t state,
114 const char* device_address,
115 const char* device_name,
116 audio_format_t encodedFormat) {
117 media::AudioPort aidlPort;
118 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
119 status == OK) {
120 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
121 } else {
122 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
123 return status;
124 }
125}
126
François Gaffie11d30102018-11-02 16:09:09 +0100127void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
128 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200129{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000130 audio_port_v7 devicePort;
131 device->toAudioPort(&devicePort);
132 if (status_t status = mpClientInterface->setDeviceConnectedState(
133 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
134 status != OK) {
135 ALOGE("Error %d while setting connected state for device %s", status,
136 device->getDeviceTypeAddr().toString(false).c_str());
137 }
François Gaffie44481e72016-04-20 07:49:57 +0200138}
139
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100140status_t AudioPolicyManager::setDeviceConnectionStateInt(
141 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
142 audio_format_t encodedFormat) {
143 // TODO: b/211601178 Forward 'port' to Audio HAL via mHwModules. For now, only device_type,
144 // device_address and device_name are forwarded.
145 if (port.ext.getTag() != AudioPortExt::device) {
146 return BAD_VALUE;
147 }
148 audio_devices_t device_type;
149 std::string device_address;
150 if (status_t status = aidl2legacy_AudioDevice_audio_device(
151 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
152 status != OK) {
153 return status;
154 };
155 const char* device_name = port.name.c_str();
156 // connect/disconnect only 1 device at a time
157 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
158 return BAD_VALUE;
159
160 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
161 device_type, device_address.c_str(), device_name, encodedFormat,
162 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
163 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
164}
165
François Gaffie11d30102018-11-02 16:09:09 +0100166status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800167 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100168 const char* device_address,
169 const char* device_name,
170 audio_format_t encodedFormat) {
171 media::AudioPort aidlPort;
172 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
173 status == OK) {
174 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
175 } else {
176 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
177 return status;
178 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179}
Paul McLeane743a472015-01-28 11:07:31 -0800180
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
182 audio_policy_dev_state_t state)
183{
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700185 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700186 SortedVector <audio_io_handle_t> outputs;
187
François Gaffie11d30102018-11-02 16:09:09 +0100188 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 // save a copy of the opened output descriptors before any output is opened or closed
191 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
192 mPreviousOutputs = mOutputs;
Eric Laurente552edb2014-03-10 17:42:56 -0700193 switch (state)
194 {
195 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800196 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700197 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100198 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700199 return INVALID_OPERATION;
200 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800201 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700202 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Eric Laurente552edb2014-03-10 17:42:56 -0700204 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200205 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700206 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700207 }
208
François Gaffie44481e72016-04-20 07:49:57 +0200209 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
210 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100211 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200212
François Gaffie11d30102018-11-02 16:09:09 +0100213 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
214 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200215
Francois Gaffie716e1432019-01-14 16:58:59 +0100216 mHwModules.cleanUpForDevice(device);
217
François Gaffie11d30102018-11-02 16:09:09 +0100218 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700219 return INVALID_OPERATION;
220 }
François Gaffie2110e042015-03-24 08:41:51 +0100221
jiabin1c4794b2020-05-05 10:08:05 -0700222 // Populate encapsulation information when a output device is connected.
223 device->setEncapsulationInfoFromHal(mpClientInterface);
224
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700225 // outputs should never be empty here
226 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
227 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100228 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800229
Eric Laurent3ae5f312015-02-03 17:12:08 -0800230 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700231 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700232 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700235 return INVALID_OPERATION;
236 }
237
François Gaffie11d30102018-11-02 16:09:09 +0100238 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700239
Paul McLeane743a472015-01-28 11:07:31 -0800240 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100241 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700242
Eric Laurente552edb2014-03-10 17:42:56 -0700243 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100244 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700245
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100246 mOutputs.clearSessionRoutesForDevice(device);
247
François Gaffie11d30102018-11-02 16:09:09 +0100248 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100249
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800250 // Reset active device codec
251 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
252
Kriti Dangef6be8f2020-11-05 11:58:19 +0100253 // remove device from mReportedFormatsMap cache
254 mReportedFormatsMap.erase(device);
255
Eric Laurente552edb2014-03-10 17:42:56 -0700256 } break;
257
258 default:
François Gaffie11d30102018-11-02 16:09:09 +0100259 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700260 return BAD_VALUE;
261 }
262
Eric Laurent736a1022019-03-27 18:28:46 -0700263 // Propagate device availability to Engine
264 setEngineDeviceConnectionState(device, state);
265
Eric Laurentae970022019-01-29 14:25:04 -0800266 // No need to evaluate playback routing when connecting a remote submix
267 // output device used by a dynamic policy of type recorder as no
268 // playback use case is affected.
269 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700270 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800271 for (audio_io_handle_t output : outputs) {
272 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800273 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
274 if (policyMix != nullptr
275 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700276 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800277 doCheckForDeviceAndOutputChanges = false;
278 break;
279 }
280 }
281 }
282
283 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700284 // outputs must be closed after checkOutputForAllStrategies() is executed
285 if (!outputs.isEmpty()) {
286 for (audio_io_handle_t output : outputs) {
287 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100288 // close unused outputs after device disconnection or direct outputs that have
289 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200290 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
291 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurent39095982021-08-24 18:29:27 +0200292 (desc->mDirectOpenCount == 0))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200293 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700294 closeOutput(output);
295 }
Eric Laurente552edb2014-03-10 17:42:56 -0700296 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
298 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700299 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800301 };
302
303 if (doCheckForDeviceAndOutputChanges) {
304 checkForDeviceAndOutputChanges(checkCloseOutputs);
305 } else {
306 checkCloseOutputs();
307 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100308 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700309 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100310 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700311 const DeviceVector activeMediaDevices =
312 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700313 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700314 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530315 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
316 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100317 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700318 // do not force device change on duplicated output because if device is 0, it will
319 // also force a device 0 for the two outputs it is duplicated to which may override
320 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100321 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100322 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700323 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 // always force when disconnecting (a non-duplicated device)
325 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100326 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700327 }
jiabinbce0c1d2020-10-05 11:20:18 -0700328 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000329 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700330 desc->supportsDevicesForPlayback(activeMediaDevices)) {
331 // Reopen the output to query the dynamic profiles when there is not active
332 // clients or all active clients will be rerouted. Otherwise, set the flag
333 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
334 // can be reopened to query dynamic profiles when all clients are inactive.
335 if (areAllActiveTracksRerouted(desc)) {
336 outputsToReopen.push_back(mOutputs.keyAt(i));
337 } else {
338 desc->mPendingReopenToQueryProfiles = true;
339 }
340 }
341 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
342 // Clear the flag that previously set for re-querying profiles.
343 desc->mPendingReopenToQueryProfiles = false;
344 }
345 }
346 for (const auto& output : outputsToReopen) {
347 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
348 closeOutput(output);
349 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700350 }
351
Eric Laurentd60560a2015-04-10 11:31:20 -0700352 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100353 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700354 }
355
Eric Laurent72aa32f2014-05-30 18:51:48 -0700356 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700357 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700358 } // end if is output device
359
Eric Laurente552edb2014-03-10 17:42:56 -0700360 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700361 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100362 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700363 switch (state)
364 {
365 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700366 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700367 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100368 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700369 return INVALID_OPERATION;
370 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700371
372 if (mAvailableInputDevices.add(device) < 0) {
373 return NO_MEMORY;
374 }
375
François Gaffie44481e72016-04-20 07:49:57 +0200376 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
377 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100378 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200379
Eric Laurent0dd51852019-04-19 18:18:58 -0700380 if (checkInputsForDevice(device, state) != NO_ERROR) {
381 mAvailableInputDevices.remove(device);
382
François Gaffie11d30102018-11-02 16:09:09 +0100383 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100384
385 mHwModules.cleanUpForDevice(device);
386
Eric Laurentd4692962014-05-05 18:13:44 -0700387 return INVALID_OPERATION;
388 }
389
Eric Laurentd4692962014-05-05 18:13:44 -0700390 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700391
392 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700393 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700394 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700396 return INVALID_OPERATION;
397 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700398
François Gaffie11d30102018-11-02 16:09:09 +0100399 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700400
401 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100402 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700403
François Gaffie11d30102018-11-02 16:09:09 +0100404 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700405
406 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100407
408 // remove device from mReportedFormatsMap cache
409 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700410 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700411
412 default:
François Gaffie11d30102018-11-02 16:09:09 +0100413 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700414 return BAD_VALUE;
415 }
416
Eric Laurent736a1022019-03-27 18:28:46 -0700417 // Propagate device availability to Engine
418 setEngineDeviceConnectionState(device, state);
419
Eric Laurent0dd51852019-04-19 18:18:58 -0700420 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700421 // As the input device list can impact the output device selection, update
422 // getDeviceForStrategy() cache
423 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700424
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100425 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200426 // Reconnect Audio Source
427 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
428 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
429 checkAudioSourceForAttributes(attributes);
430 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700431 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100432 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700433 }
434
Eric Laurentb52c1522014-05-20 11:27:36 -0700435 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700436 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700437 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700438
François Gaffie11d30102018-11-02 16:09:09 +0100439 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700440 return BAD_VALUE;
441}
442
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100443status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
444 const char* device_name,
445 media::AudioPort* aidlPort) {
446 DeviceDescriptorBase devDescr(device, device_address);
447 devDescr.setName(device_name);
448 return devDescr.writeToParcelable(aidlPort);
449}
450
Eric Laurent736a1022019-03-27 18:28:46 -0700451void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
452 audio_policy_dev_state_t state) {
453
454 // the Engine does not have to know about remote submix devices used by dynamic audio policies
455 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
456 return;
457 }
458 mEngine->setDeviceConnectionState(device, state);
459}
460
461
Eric Laurente0720872014-03-11 09:30:41 -0700462audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100463 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700464{
Eric Laurent634b7142016-04-20 13:48:02 -0700465 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800466 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
467 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700468 (strlen(device_address) != 0)/*matchAddress*/);
469
470 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100471 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700472 device, device_address);
473 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
474 }
François Gaffie53615e22015-03-19 09:24:12 +0100475
Eric Laurent3a4311c2014-03-17 12:00:47 -0700476 DeviceVector *deviceVector;
477
Eric Laurente552edb2014-03-10 17:42:56 -0700478 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700479 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700480 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700481 deviceVector = &mAvailableInputDevices;
482 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100483 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700484 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700485 }
Eric Laurent634b7142016-04-20 13:48:02 -0700486
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800487 return (deviceVector->getDevice(
488 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700489 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800490}
491
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800492status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
493 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800494 const char *device_name,
495 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800496{
497 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700498 String8 reply;
499 AudioParameter param;
500 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800501
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800502 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
503 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800505 // connect/disconnect only 1 device at a time
506 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
507
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700509 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800511 // Nothing to do: device is not connected
512 return NO_ERROR;
513 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800514 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800515
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700516 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 // configure codecs.
518 // Handle two specific cases by sending a set parameter to
519 // configure A2DP codecs. No need to toggle device state.
520 // Case 1: A2DP active device switches from primary to primary
521 // module
522 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200523 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700524 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
526 if (availablePrimaryOutputDevices().contains(devDesc) &&
527 (module != 0 && module->getHandle() == primaryHandle)) {
528 reply = mpClientInterface->getParameters(
529 AUDIO_IO_HANDLE_NONE,
530 String8(AudioParameter::keyReconfigA2dpSupported));
531 AudioParameter repliedParameters(reply);
532 repliedParameters.getInt(
533 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
534 if (isReconfigA2dpSupported) {
535 const String8 key(AudioParameter::keyReconfigA2dp);
536 param.add(key, String8("true"));
537 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
538 devDesc->setEncodedFormat(encodedFormat);
539 return NO_ERROR;
540 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700541 }
542 }
cnx421bd2dcc42020-07-11 14:58:44 +0800543 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
544 for (size_t i = 0; i < mOutputs.size(); i++) {
545 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
546 // mute media strategies and delay device switch by the largest
547 // This avoid sending the music tail into the earpiece or headset.
548 setStrategyMute(musicStrategy, true, desc);
549 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
550 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
551 nullptr, true /*fromCache*/).types());
552 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800553 // Toggle the device state: UNAVAILABLE -> AVAILABLE
554 // This will force reading again the device configuration
555 status = setDeviceConnectionState(device,
556 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800557 device_address, device_name,
558 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800559 if (status != NO_ERROR) {
560 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
561 status);
562 return status;
563 }
564
565 status = setDeviceConnectionState(device,
566 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800567 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 if (status != NO_ERROR) {
569 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
570 status);
571 return status;
572 }
573
574 return NO_ERROR;
575}
576
Pattydd807582021-11-04 21:01:03 +0800577status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
578 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800579{
Pattydd807582021-11-04 21:01:03 +0800580 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800581 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800582 std::unordered_set<audio_format_t> formatSet;
583 sp<HwModule> primaryModule =
584 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700585 if (primaryModule == nullptr) {
586 ALOGE("%s() unable to get primary module", __func__);
587 return NO_INIT;
588 }
Pattydd807582021-11-04 21:01:03 +0800589
590 DeviceTypeSet audioDeviceSet;
591
592 switch(device) {
593 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
594 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
595 break;
596 case AUDIO_DEVICE_OUT_BLE_HEADSET:
597 audioDeviceSet = getAudioDeviceOutAllBleSet();
598 break;
599 default:
600 ALOGE("%s() device type 0x%08x not supported", __func__, device);
601 return BAD_VALUE;
602 }
603
jiabin9a3361e2019-10-01 09:38:30 -0700604 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800605 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800606 for (const auto& device : declaredDevices) {
607 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800608 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800609 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800610 return status;
611}
612
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100613DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
614{
615 DeviceVector rxSinkdevices{};
616 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
617 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
618 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
619 auto rxSinkDevice = rxSinkdevices.itemAt(0);
620 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
621 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
622 // retrieve Rx Source device descriptor
623 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
624 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
625
626 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
627 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
628 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
629 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
630 return DeviceVector(rxSinkDevice);
631 }
632 }
633 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
634 // the device returned is not necessarily reachable via this output
635 // (filter later by setOutputDevices())
636 return getNewOutputDevices(mPrimaryOutput, fromCache);
637}
638
639status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
640{
641 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
642 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
643 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
644 }
645 return INVALID_OPERATION;
646}
647
648status_t AudioPolicyManager::updateCallRoutingInternal(
649 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700650{
651 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100652 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700653 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700654 if(!hasPrimaryOutput() ||
655 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100656 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700657 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100658 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100659
Francois Gaffie716e1432019-01-14 16:58:59 +0100660 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100661 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100663
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100664 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100665 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700666
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200667 disconnectTelephonyRxAudioSource();
Eric Laurentc2730ba2014-07-20 15:47:07 -0700668 // release TX patch if any
669 if (mCallTxPatch != 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +0100670 releaseAudioPatchInternal(mCallTxPatch->getHandle());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700671 mCallTxPatch.clear();
672 }
673
François Gaffie9eb18552018-11-05 10:33:26 +0100674 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700675 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100676 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700677 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100678 // retrieve Rx Source and Tx Sink device descriptors
679 sp<DeviceDescriptor> rxSourceDevice =
680 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
681 String8(),
682 AUDIO_FORMAT_DEFAULT);
683 sp<DeviceDescriptor> txSinkDevice =
684 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
685 String8(),
686 AUDIO_FORMAT_DEFAULT);
687
688 // RX and TX Telephony device are declared by Primary Audio HAL
689 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
690 (telephonyRxModule->getHalVersionMajor() >= 3)) {
691 if (rxSourceDevice == 0 || txSinkDevice == 0) {
692 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100693 ALOGE("%s() no telephony Tx and/or RX device", __func__);
694 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100695 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100696 // createAudioPatchInternal now supports both HW / SW bridging
697 createRxPatch = true;
698 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100699 } else {
700 // If the RX device is on the primary HW module, then use legacy routing method for
701 // voice calls via setOutputDevice() on primary output.
702 // Otherwise, create two audio patches for TX and RX path.
703 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
704 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700705 // If the TX device is also on the primary HW module, setOutputDevice() will take care
706 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100707 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
708 (txSinkDevice != 0);
709 }
710 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
711 // Otherwise, create two audio patches for TX and RX path.
712 if (!createRxPatch) {
713 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700714 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200715 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800716 // If the TX device is on the primary HW module but RX device is
717 // on other HW module, SinkMetaData of telephony input should handle it
718 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700719 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700720 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100721 // terminate active capture if on the same HW module as the call TX source device
722 // FIXME: would be better to refine to only inputs whose profile connects to the
723 // call TX device but this information is not in the audio patch and logic here must be
724 // symmetric to the one in startInput()
725 for (const auto& activeDesc : mInputs.getActiveInputs()) {
726 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
727 closeActiveClients(activeDesc);
728 }
729 }
François Gaffie9eb18552018-11-05 10:33:26 +0100730 mCallTxPatch = createTelephonyPatch(false /*isRx*/, txSourceDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800731 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100732 if (waitMs != nullptr) {
733 *waitMs = muteWaitMs;
734 }
735 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800736}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700737
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800738sp<AudioPatch> AudioPolicyManager::createTelephonyPatch(
François Gaffie11d30102018-11-02 16:09:09 +0100739 bool isRx, const sp<DeviceDescriptor> &device, uint32_t delayMs) {
Mikhail Naganovdc769682018-05-04 15:34:08 -0700740 PatchBuilder patchBuilder;
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741
François Gaffie11d30102018-11-02 16:09:09 +0100742 if (device == nullptr) {
743 return nullptr;
744 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100745
746 // @TODO: still ignoring the address, or not dealing platform with multiple telephony devices
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800747 if (isRx) {
François Gaffie11d30102018-11-02 16:09:09 +0100748 patchBuilder.addSink(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800749 addSource(mAvailableInputDevices.getDevice(
750 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800751 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100752 patchBuilder.addSource(device).
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800753 addSink(mAvailableOutputDevices.getDevice(
754 AUDIO_DEVICE_OUT_TELEPHONY_TX, String8(), AUDIO_FORMAT_DEFAULT));
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800755 }
756
François Gaffieafd4cea2019-11-18 15:50:22 +0100757 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
758 status_t status =
759 createAudioPatchInternal(patchBuilder.patch(), &patchHandle, mUidCached, delayMs);
760 ssize_t index = mAudioPatches.indexOfKey(patchHandle);
761 if (status != NO_ERROR || index < 0) {
762 ALOGW("%s() error %d creating %s audio patch", __func__, status, isRx ? "RX" : "TX");
763 return nullptr;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800764 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100765 return mAudioPatches.valueAt(index);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800766}
767
Mikhail Naganov100f0122018-11-29 11:22:16 -0800768bool AudioPolicyManager::isDeviceOfModule(
769 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
770 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
771 if (module != 0) {
772 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
773 .indexOf(devDesc) != NAME_NOT_FOUND
774 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
775 .indexOf(devDesc) != NAME_NOT_FOUND;
776 }
777 return false;
778}
779
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200780void AudioPolicyManager::connectTelephonyRxAudioSource()
781{
782 disconnectTelephonyRxAudioSource();
783 const struct audio_port_config source = {
784 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
785 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
786 };
787 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
788 status_t status = startAudioSource(&source, &aa, &mCallRxSourceClientPort, 0/*uid*/);
789 ALOGE_IF(status != NO_ERROR, "%s failed to start Telephony Rx AudioSource", __func__);
790}
791
792void AudioPolicyManager::disconnectTelephonyRxAudioSource()
793{
794 stopAudioSource(mCallRxSourceClientPort);
795 mCallRxSourceClientPort = AUDIO_PORT_HANDLE_NONE;
796}
797
Eric Laurente0720872014-03-11 09:30:41 -0700798void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700799{
800 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100801 // store previous phone state for management of sonification strategy below
802 int oldState = mEngine->getPhoneState();
803
804 if (mEngine->setPhoneState(state) != NO_ERROR) {
805 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700806 return;
807 }
François Gaffie2110e042015-03-24 08:41:51 +0100808 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700809 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700810 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700811 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800812 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700813 }
814
François Gaffie2110e042015-03-24 08:41:51 +0100815 /**
816 * Switching to or from incall state or switching between telephony and VoIP lead to force
817 * routing command.
818 */
Eric Laurent74b71512019-11-06 17:21:57 -0800819 bool force = ((isStateInCall(oldState) != isStateInCall(state))
820 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700821
822 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700823 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700824
Eric Laurente552edb2014-03-10 17:42:56 -0700825 int delayMs = 0;
826 if (isStateInCall(state)) {
827 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100828 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
829 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700830 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700831 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700832 // mute media and sonification strategies and delay device switch by the largest
833 // latency of any output where either strategy is active.
834 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100835 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
836 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
837 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700838 (delayMs < (int)desc->latency()*2)) {
839 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700840 }
François Gaffiec005e562018-11-06 15:04:49 +0100841 setStrategyMute(musicStrategy, true, desc);
842 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
843 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
844 nullptr, true /*fromCache*/).types());
845 setStrategyMute(sonificationStrategy, true, desc);
846 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
847 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
848 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700849 }
850 }
851
Eric Laurent87ffa392015-05-22 10:32:38 -0700852 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700853 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100854 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700855 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100856 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
857 // force routing command to audio hardware when ending call
858 // even if no device change is needed
859 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
860 rxDevices = mPrimaryOutput->devices();
861 }
862 if (oldState == AUDIO_MODE_IN_CALL) {
863 disconnectTelephonyRxAudioSource();
864 if (mCallTxPatch != 0) {
865 releaseAudioPatchInternal(mCallTxPatch->getHandle());
866 mCallTxPatch.clear();
867 }
868 }
François Gaffie11d30102018-11-02 16:09:09 +0100869 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700870 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700871 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700872
873 // reevaluate routing on all outputs in case tracks have been started during the call
874 for (size_t i = 0; i < mOutputs.size(); i++) {
875 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100876 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700877 if (state != AUDIO_MODE_IN_CALL || desc != mPrimaryOutput) {
François Gaffie11d30102018-11-02 16:09:09 +0100878 setOutputDevices(desc, newDevices, !newDevices.isEmpty(), 0 /*delayMs*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700879 }
880 }
881
Eric Laurente552edb2014-03-10 17:42:56 -0700882 if (isStateInCall(state)) {
883 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700884 // force reevaluating accessibility routing when call starts
885 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700886 }
887
888 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100889 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
890 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700891}
892
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700893audio_mode_t AudioPolicyManager::getPhoneState() {
894 return mEngine->getPhoneState();
895}
896
Eric Laurente0720872014-03-11 09:30:41 -0700897void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100898 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700899{
François Gaffie2110e042015-03-24 08:41:51 +0100900 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700901 if (config == mEngine->getForceUse(usage)) {
902 return;
903 }
Eric Laurente552edb2014-03-10 17:42:56 -0700904
François Gaffie2110e042015-03-24 08:41:51 +0100905 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
906 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
907 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700908 }
François Gaffie2110e042015-03-24 08:41:51 +0100909 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
910 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
911 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700912
913 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700914 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800915
Eric Laurent22fcda22019-05-17 16:28:47 -0700916 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
917 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
918 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
919 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
920 }
921
Eric Laurentdc462862016-07-19 12:29:53 -0700922 //FIXME: workaround for truncated touch sounds
923 // to be removed when the problem is handled by system UI
924 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700925 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
926 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
927 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700928
929 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100930 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700931}
932
Eric Laurente0720872014-03-11 09:30:41 -0700933void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700934{
935 ALOGV("setSystemProperty() property %s, value %s", property, value);
936}
937
Michael Chana94fbb22018-04-24 14:31:19 +1000938// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
939// search to profiles for direct outputs.
940sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100941 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000942 uint32_t samplingRate,
943 audio_format_t format,
944 audio_channel_mask_t channelMask,
945 audio_output_flags_t flags,
946 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700947{
Michael Chana94fbb22018-04-24 14:31:19 +1000948 if (directOnly) {
949 // only retain flags that will drive the direct output profile selection
950 // if explicitly requested
951 static const uint32_t kRelevantFlags =
952 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Aniket Kumar Lataba810b82019-07-03 11:15:33 -0700953 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
Michael Chana94fbb22018-04-24 14:31:19 +1000954 flags =
955 (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
956 }
Eric Laurent861a6282015-05-18 15:40:16 -0700957
958 sp<IOProfile> profile;
959
Mikhail Naganovd4120142017-12-06 15:49:22 -0800960 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -0800961 for (const auto& curProfile : hwModule->getOutputProfiles()) {
François Gaffie11d30102018-11-02 16:09:09 +0100962 if (!curProfile->isCompatibleProfile(devices,
Andy Hungf129b032015-04-07 13:45:50 -0700963 samplingRate, NULL /*updatedSamplingRate*/,
964 format, NULL /*updatedFormat*/,
965 channelMask, NULL /*updatedChannelMask*/,
Eric Laurent861a6282015-05-18 15:40:16 -0700966 flags)) {
967 continue;
968 }
969 // reject profiles not corresponding to a device currently available
François Gaffie11d30102018-11-02 16:09:09 +0100970 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
Eric Laurent861a6282015-05-18 15:40:16 -0700971 continue;
972 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800973 // reject profiles if connected device does not support codec
jiabin9a3361e2019-10-01 09:38:30 -0700974 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800975 continue;
976 }
Michael Chana94fbb22018-04-24 14:31:19 +1000977 if (!directOnly) return curProfile;
978 // when searching for direct outputs, if several profiles are compatible, give priority
979 // to one with offload capability
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100980 if (profile != 0 && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -0700981 continue;
982 }
983 profile = curProfile;
François Gaffiea8ecc2c2015-11-09 16:10:40 +0100984 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Eric Laurent861a6282015-05-18 15:40:16 -0700985 break;
Eric Laurent3a4311c2014-03-17 12:00:47 -0700986 }
Eric Laurente552edb2014-03-10 17:42:56 -0700987 }
988 }
Eric Laurent861a6282015-05-18 15:40:16 -0700989 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -0700990}
991
Eric Laurentfa0f6742021-08-17 18:39:44 +0200992sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +0200993 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200994{
995 for (const auto& hwModule : mHwModules) {
996 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +0200997 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200998 continue;
999 }
1000 // reject profiles not corresponding to a device currently available
1001 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1002 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1003 continue;
1004 }
1005 if (!devices.empty()) {
1006 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1007 != devices.size()) {
1008 continue;
1009 }
1010 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001011 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1012 return curProfile;
1013 }
1014 }
1015 return nullptr;
1016}
1017
Eric Laurentf4e63452017-11-06 19:31:46 +00001018audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001019{
François Gaffiec005e562018-11-06 15:04:49 +01001020 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001021
1022 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1023 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1024 // format, flags, etc. This may result in some discrepancy for functions that utilize
1025 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1026 // and AudioSystem::getOutputSamplingRate().
1027
François Gaffie11d30102018-11-02 16:09:09 +01001028 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001029 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001030
François Gaffie11d30102018-11-02 16:09:09 +01001031 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1032 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001033 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001034}
1035
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001036status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1037 const audio_attributes_t *srcAttr,
1038 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001039{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001040 if (srcAttr != NULL) {
1041 if (!isValidAttributes(srcAttr)) {
1042 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1043 __func__,
1044 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1045 srcAttr->tags);
1046 return BAD_VALUE;
1047 }
1048 *dstAttr = *srcAttr;
1049 } else {
1050 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1051 ALOGE("%s: invalid stream type", __func__);
1052 return BAD_VALUE;
1053 }
François Gaffiec005e562018-11-06 15:04:49 +01001054 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001055 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001056
1057 // Only honor audibility enforced when required. The client will be
1058 // forced to reconnect if the forced usage changes.
1059 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001060 dstAttr->flags = static_cast<audio_flags_mask_t>(
1061 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001062 }
1063
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001064 return NO_ERROR;
1065}
1066
Kevin Rocard153f92d2018-12-18 18:33:28 -08001067status_t AudioPolicyManager::getOutputForAttrInt(
1068 audio_attributes_t *resultAttr,
1069 audio_io_handle_t *output,
1070 audio_session_t session,
1071 const audio_attributes_t *attr,
1072 audio_stream_type_t *stream,
1073 uid_t uid,
1074 const audio_config_t *config,
1075 audio_output_flags_t *flags,
1076 audio_port_handle_t *selectedDeviceId,
1077 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001078 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001079 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001080{
François Gaffiec005e562018-11-06 15:04:49 +01001081 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001082 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001083 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001084 const sp<DeviceDescriptor> requestedDevice =
1085 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1086
Eric Laurent8a1095a2019-11-08 14:44:16 -08001087 *outputType = API_OUTPUT_INVALID;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001088 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1089 if (status != NO_ERROR) {
1090 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001091 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001092 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001093 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001094 }
François Gaffiec005e562018-11-06 15:04:49 +01001095 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001096
François Gaffiec005e562018-11-06 15:04:49 +01001097 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1098 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001099
Kevin Rocard153f92d2018-12-18 18:33:28 -08001100 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1101 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1102 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001103 sp<AudioPolicyMix> primaryMix;
1104 status = mPolicyMixes.getOutputForAttr(*resultAttr, uid, *flags, primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001105 if (status != OK) {
1106 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001107 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001108
Kevin Rocard153f92d2018-12-18 18:33:28 -08001109 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001110 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001111
1112 // FIXME: in case of RENDER policy, the output capabilities should be checked
Eric Laurentc529cf62020-04-17 18:19:10 -07001113 if ((usePrimaryOutputFromPolicyMixes
1114 || (secondaryMixes != nullptr && !secondaryMixes->empty()))
Kevin Rocardc2afbdf2019-01-31 18:18:06 -08001115 && !audio_is_linear_pcm(config->format)) {
1116 ALOGD("%s: rejecting request as dynamic audio policy only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001117 return BAD_VALUE;
1118 }
1119 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001120 sp<DeviceDescriptor> deviceDesc =
1121 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1122 primaryMix->mDeviceAddress,
1123 AUDIO_FORMAT_DEFAULT);
1124 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Eric Laurentc64e0ab2020-04-30 15:59:34 -07001125 if (deviceDesc != nullptr
1126 && (policyDesc == nullptr || (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001127 audio_io_handle_t newOutput;
1128 status = openDirectOutput(
1129 *stream, session, config,
1130 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1131 DeviceVector(deviceDesc), &newOutput);
1132 if (status != NO_ERROR) {
1133 policyDesc = nullptr;
1134 } else {
1135 policyDesc = mOutputs.valueFor(newOutput);
1136 primaryMix->setOutput(policyDesc);
1137 }
1138 }
1139 if (policyDesc != nullptr) {
1140 policyDesc->mPolicyMix = primaryMix;
1141 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001142 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001143
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001144 ALOGV("getOutputForAttr() returns output %d", *output);
1145 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1146 *outputType = API_OUT_MIX_PLAYBACK;
1147 } else {
1148 *outputType = API_OUTPUT_LEGACY;
1149 }
1150 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001151 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001152 }
François Gaffiec005e562018-11-06 15:04:49 +01001153 // Virtual sources must always be dynamicaly or explicitly routed
1154 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1155 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1156 return BAD_VALUE;
1157 }
1158 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1159 // in order to let the choice of the order to future vendor engine
1160 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001161
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001162 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001163 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001164 }
1165
Nadav Barb2f18162018-07-18 13:01:53 +03001166 // Set incall music only if device was explicitly set, and fallback to the device which is
1167 // chosen by the engine if not.
1168 // FIXME: provide a more generic approach which is not device specific and move this back
1169 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001170 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001171 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001172 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001173 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001174 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001175 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001176 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001177 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001178 }
1179 }
1180
François Gaffiec005e562018-11-06 15:04:49 +01001181 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1182 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1183 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001184
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001185 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001186 if (!msdDevices.isEmpty()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001187 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001188 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001189 ALOGV("%s() Using MSD devices %s instead of devices %s",
1190 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001191 } else {
1192 *output = AUDIO_IO_HANDLE_NONE;
1193 }
1194 }
1195 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001196 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurent42984412019-05-09 17:57:03 -07001197 flags, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001198 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001199 if (*output == AUDIO_IO_HANDLE_NONE) {
1200 return INVALID_OPERATION;
1201 }
Paul McLeanaa981192015-03-21 09:55:15 -07001202
François Gaffiec005e562018-11-06 15:04:49 +01001203 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001204 for (auto &outputDevice : outputDevices) {
1205 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1206 *selectedDeviceId = outputDevice->getId();
1207 break;
1208 }
1209 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001210
Eric Laurent8a1095a2019-11-08 14:44:16 -08001211 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1212 *outputType = API_OUTPUT_TELEPHONY_TX;
1213 } else {
1214 *outputType = API_OUTPUT_LEGACY;
1215 }
1216
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001217 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1218
1219 return NO_ERROR;
1220}
1221
1222status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1223 audio_io_handle_t *output,
1224 audio_session_t session,
1225 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001226 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001227 const audio_config_t *config,
1228 audio_output_flags_t *flags,
1229 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001230 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001231 std::vector<audio_io_handle_t> *secondaryOutputs,
1232 output_type_t *outputType)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001233{
1234 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1235 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1236 return INVALID_OPERATION;
1237 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001238 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001239 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001240 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001241 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001242 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001243 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001244 const sp<DeviceDescriptor> requestedDevice =
1245 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1246
1247 // Prevent from storing invalid requested device id in clients
1248 const audio_port_handle_t sanitizedRequestedPortId =
1249 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1250 *selectedDeviceId = sanitizedRequestedPortId;
1251
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001252 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001253 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001254 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001255 if (status != NO_ERROR) {
1256 return status;
1257 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001258 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001259 if (secondaryOutputs != nullptr) {
1260 for (auto &secondaryMix : secondaryMixes) {
1261 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1262 if (outputDesc != nullptr &&
1263 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1264 secondaryOutputs->push_back(outputDesc->mIoHandle);
1265 weakSecondaryOutputDescs.push_back(outputDesc);
1266 }
1267 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001268 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001269
Eric Laurent8fc147b2018-07-22 19:13:55 -07001270 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001271 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001272 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001273 };
jiabin4ef93452019-09-10 14:29:54 -07001274 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001275
Eric Laurentc209fe42020-06-05 18:11:23 -07001276 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001277 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001278 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001279 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001280 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001281 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001282 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001283 std::move(weakSecondaryOutputDescs),
1284 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001285 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001286
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001287 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1288 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001289
Eric Laurente83b55d2014-11-14 10:06:21 -08001290 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001291}
1292
Eric Laurentc529cf62020-04-17 18:19:10 -07001293status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1294 audio_session_t session,
1295 const audio_config_t *config,
1296 audio_output_flags_t flags,
1297 const DeviceVector &devices,
1298 audio_io_handle_t *output) {
1299
1300 *output = AUDIO_IO_HANDLE_NONE;
1301
1302 // skip direct output selection if the request can obviously be attached to a mixed output
1303 // and not explicitly requested
1304 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1305 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1306 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1307 return NAME_NOT_FOUND;
1308 }
1309
1310 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1311 // This prevents creating an offloaded track and tearing it down immediately after start
1312 // when audioflinger detects there is an active non offloadable effect.
1313 // FIXME: We should check the audio session here but we do not have it in this context.
1314 // This may prevent offloading in rare situations where effects are left active by apps
1315 // in the background.
1316 sp<IOProfile> profile;
1317 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1318 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1319 profile = getProfileForOutput(
1320 devices, config->sample_rate, config->format, config->channel_mask,
1321 flags, true /* directOnly */);
1322 }
1323
1324 if (profile == nullptr) {
1325 return NAME_NOT_FOUND;
1326 }
1327
1328 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1329 for (size_t i = 0; i < mOutputs.size(); i++) {
1330 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1331 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1332 // reuse direct output if currently open by the same client
1333 // and configured with same parameters
1334 if ((config->sample_rate == desc->getSamplingRate()) &&
1335 (config->format == desc->getFormat()) &&
1336 (config->channel_mask == desc->getChannelMask()) &&
1337 (session == desc->mDirectClientSession)) {
1338 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001339 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001340 mOutputs.keyAt(i), session);
1341 *output = mOutputs.keyAt(i);
1342 return NO_ERROR;
1343 }
1344 }
1345 }
1346
1347 if (!profile->canOpenNewIo()) {
1348 return NAME_NOT_FOUND;
1349 }
1350
1351 sp<SwAudioOutputDescriptor> outputDesc =
1352 new SwAudioOutputDescriptor(profile, mpClientInterface);
1353
Michael Chan6fb34492020-12-08 15:44:49 +11001354 // An MSD patch may be using the only output stream that can service this request. Release
1355 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001356 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001357
Eric Laurentf1f22e72021-07-13 14:04:14 +02001358 status_t status =
1359 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001360
1361 // only accept an output with the requested parameters
1362 if (status != NO_ERROR ||
1363 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1364 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1365 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1366 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1367 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1368 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1369 config->channel_mask, outputDesc->getChannelMask());
1370 if (*output != AUDIO_IO_HANDLE_NONE) {
1371 outputDesc->close();
1372 }
1373 // fall back to mixer output if possible when the direct output could not be open
1374 if (audio_is_linear_pcm(config->format) &&
1375 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1376 return NAME_NOT_FOUND;
1377 }
1378 *output = AUDIO_IO_HANDLE_NONE;
1379 return BAD_VALUE;
1380 }
1381 outputDesc->mDirectOpenCount = 1;
1382 outputDesc->mDirectClientSession = session;
1383
1384 addOutput(*output, outputDesc);
1385 mPreviousOutputs = mOutputs;
1386 ALOGV("%s returns new direct output %d", __func__, *output);
1387 mpClientInterface->onAudioPortListUpdate();
1388 return NO_ERROR;
1389}
1390
François Gaffie11d30102018-11-02 16:09:09 +01001391audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1392 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001393 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001394 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001395 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001396 audio_output_flags_t *flags,
1397 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001398{
Andy Hungc88b0642018-04-27 15:42:35 -07001399 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001400
jiabine375d412019-02-26 12:54:53 -08001401 // Discard haptic channel mask when forcing muting haptic channels.
1402 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001403 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1404 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001405
Eric Laurente552edb2014-03-10 17:42:56 -07001406 // open a direct output if required by specified parameters
1407 //force direct flag if offload flag is set: offloading implies a direct output stream
1408 // and all common behaviors are driven by checking only the direct flag
1409 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001410 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1411 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001412 }
Nadav Bar766fb022018-01-07 12:18:03 +02001413 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1414 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001415 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001416
1417 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1418
Eric Laurente83b55d2014-11-14 10:06:21 -08001419 // only allow deep buffering for music stream type
1420 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001421 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001422 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001423 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001424 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1425 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001426 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001427 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001428 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001429 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001430 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001431 audio_is_linear_pcm(config->format) &&
1432 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001433 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001434 AUDIO_OUTPUT_FLAG_DIRECT);
1435 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001436 }
Eric Laurente552edb2014-03-10 17:42:56 -07001437
Carter Hsua3abb402021-10-26 11:11:20 +08001438 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1439 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1440 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1441 }
1442
Eric Laurentfa0f6742021-08-17 18:39:44 +02001443 if (mSpatializerOutput != nullptr
Eric Laurentb4f42a92022-01-17 17:37:31 +01001444 && canBeSpatializedInt(attr, config,
1445 devices.toTypeAddrVector(), false /* allowCurrentOutputReconfig */)) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02001446 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001447 }
1448
Eric Laurentc529cf62020-04-17 18:19:10 -07001449 audio_config_t directConfig = *config;
1450 directConfig.channel_mask = channelMask;
1451 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1452 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001453 return output;
1454 }
1455
Eric Laurent14cbfca2016-03-17 09:42:16 -07001456 // A request for HW A/V sync cannot fallback to a mixed output because time
1457 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001458 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001459 return AUDIO_IO_HANDLE_NONE;
1460 }
1461
Eric Laurente552edb2014-03-10 17:42:56 -07001462 // ignoring channel mask due to downmix capability in mixer
1463
1464 // open a non direct output
1465
1466 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001467 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001468 // get which output is suitable for the specified stream. The actual
1469 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001470 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001471
Eric Laurent8838a382014-09-08 16:44:28 -07001472 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001473 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001474 output = selectOutput(
1475 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001476 }
François Gaffie11d30102018-11-02 16:09:09 +01001477 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001478 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001479 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001480
Eric Laurente552edb2014-03-10 17:42:56 -07001481 return output;
1482}
1483
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001484sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001485 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1486 mAvailableInputDevices);
1487 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1488}
1489
1490DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1491 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1492 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001493}
1494
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001495const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001496 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001497 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1498 if (msdModule != 0) {
1499 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1500 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1501 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1502 const struct audio_port_config *source = &patch->mPatch.sources[j];
1503 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1504 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001505 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001506 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001507 }
1508 }
1509 }
1510 return msdPatches;
1511}
1512
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001513status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1514 const InputProfileCollection &inputProfiles,
1515 const OutputProfileCollection &outputProfiles,
1516 const sp<DeviceDescriptor> &sourceDevice,
1517 const sp<DeviceDescriptor> &sinkDevice,
1518 AudioProfileVector& sourceProfiles,
1519 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001520 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001521 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001522 return NO_INIT;
1523 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001524 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001525 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001526 return NO_INIT;
1527 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001528 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001529 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1530 inProfile->supportsDevice(sourceDevice)) {
1531 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001532 }
1533 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001534 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001535 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001536 outProfile->supportsDevice(sinkDevice)) {
1537 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001538 }
1539 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001540 return NO_ERROR;
1541}
1542
1543status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1544 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1545 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1546{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001547 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001548 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1549 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1550 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001551 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001552 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1553 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001554 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001555 }
1556 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1557 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1558 sinkConfig->format = bestSinkConfig.format;
1559 // For encoded streams force direct flag to prevent downstream mixing.
1560 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1561 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001562 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1563 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001564 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001565 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1566 // raw and IEC61937 framed streams.
1567 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1568 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1569 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001570 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1571 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1572 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1573 sourceConfig->format = bestSinkConfig.format;
1574 // Copy input stream directly without any processing (e.g. resampling).
1575 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1576 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1577 if (hwAvSync) {
1578 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1579 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1580 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1581 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1582 }
1583 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1584 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1585 sinkConfig->config_mask |= config_mask;
1586 sourceConfig->config_mask |= config_mask;
1587 return NO_ERROR;
1588}
1589
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001590PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1591 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001592{
1593 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001594 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1595 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1596 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1597 if (deviceModule == nullptr) {
1598 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1599 return patchBuilder;
1600 }
1601 const InputProfileCollection inputProfiles = msdIsSource ?
1602 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1603 const OutputProfileCollection outputProfiles = msdIsSource ?
1604 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1605
1606 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1607 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1608 device : getMsdAudioOutDevices().itemAt(0);
1609 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1610
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001611 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1612 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001613 AudioProfileVector sourceProfiles;
1614 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001615 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1616 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001617 for (auto hwAvSync : { true, false }) {
1618 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1619 sourceProfiles, sinkProfiles) != NO_ERROR) {
1620 continue;
1621 }
1622 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1623 &sinkConfig) == NO_ERROR) {
1624 // Found a matching config. Re-create PatchBuilder with this config.
1625 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1626 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001627 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001628 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001629 " supporting PCM format conversion.", __func__);
1630 return patchBuilder;
1631}
1632
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001633status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001634 DeviceVector devices;
1635 if (outputDevices != nullptr && outputDevices->size() > 0) {
1636 devices.add(*outputDevices);
1637 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001638 // Use media strategy for unspecified output device. This should only
1639 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1640 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001641 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001642 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001643 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001644 }
Michael Chan6fb34492020-12-08 15:44:49 +11001645 std::vector<PatchBuilder> patchesToCreate;
1646 for (auto i = 0u; i < devices.size(); ++i) {
1647 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001648 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001649 }
1650 // Retain only the MSD patches associated with outputDevices request.
1651 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001652 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001653 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1654 auto retainedPatch = false;
1655 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1656 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1657 patchesToRemove.removeItemsAt(i);
1658 retainedPatch = true;
1659 break;
1660 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001661 }
Michael Chan6fb34492020-12-08 15:44:49 +11001662 if (retainedPatch) {
1663 it = patchesToCreate.erase(it);
1664 continue;
1665 }
1666 ++it;
1667 }
1668 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1669 return NO_ERROR;
1670 }
1671 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1672 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001673 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001674 }
Michael Chan6fb34492020-12-08 15:44:49 +11001675 status_t status = NO_ERROR;
1676 for (const auto &p : patchesToCreate) {
1677 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1678 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1679 char message[256];
1680 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1681 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1682 currStatus == NO_ERROR ? "Success" : "Error",
1683 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1684 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1685 if (currStatus == NO_ERROR) {
1686 ALOGD("%s", message);
1687 } else {
1688 ALOGE("%s", message);
1689 if (status == NO_ERROR) {
1690 status = currStatus;
1691 }
1692 }
1693 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001694 return status;
1695}
1696
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001697void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1698 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001699 for (size_t i = 0; i < msdPatches.size(); i++) {
1700 const auto& patch = msdPatches[i];
1701 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1702 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1703 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1704 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1705 releaseAudioPatch(patch->getHandle(), mUidCached);
1706 break;
1707 }
1708 }
1709 }
1710}
1711
Dorin Drimus94d94412022-02-02 09:05:02 +01001712bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1713 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1714 AudioPatchCollection msdPatches = getMsdOutputPatches();
1715 for (size_t i = 0; i < msdPatches.size(); i++) {
1716 const auto& patch = msdPatches[i];
1717 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1718 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1719 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1720 const auto& foundDevice = devicesToCheck.getDevice(
1721 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1722 if (foundDevice != nullptr) {
1723 devicesToCheck.remove(foundDevice);
1724 if (devicesToCheck.isEmpty()) {
1725 return true;
1726 }
1727 }
1728 }
1729 }
1730 }
1731 return false;
1732}
1733
Eric Laurente0720872014-03-11 09:30:41 -07001734audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001735 audio_output_flags_t flags,
1736 audio_format_t format,
1737 audio_channel_mask_t channelMask,
1738 uint32_t samplingRate,
1739 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001740{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001741 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1742 "%s called with format %#x", __func__, format);
1743
jiabinebb6af42020-06-09 17:31:17 -07001744 // Return the output that haptic-generating attached to when 1) session id is specified,
1745 // 2) haptic-generating effect exists for given session id and 3) the output that
1746 // haptic-generating effect attached to is in given outputs.
1747 if (sessionId != AUDIO_SESSION_NONE) {
1748 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1749 sessionId, FX_IID_HAPTICGENERATOR);
1750 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1751 return hapticGeneratingOutput;
1752 }
1753 }
1754
Eric Laurent16c66dd2019-05-01 17:54:10 -07001755 // Flags disqualifying an output: the match must happen before calling selectOutput()
1756 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1757 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1758
1759 // Flags expressing a functional request: must be honored in priority over
1760 // other criteria
1761 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1762 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001763 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1764 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001765 // Flags expressing a performance request: have lower priority than serving
1766 // requested sampling rate or channel mask
1767 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1768 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1769 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1770
1771 const audio_output_flags_t functionalFlags =
1772 (audio_output_flags_t)(flags & kFunctionalFlags);
1773 const audio_output_flags_t performanceFlags =
1774 (audio_output_flags_t)(flags & kPerformanceFlags);
1775
1776 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1777
Eric Laurente552edb2014-03-10 17:42:56 -07001778 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001779 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001780 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001781 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001782 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001783 // with tiebreak preferring the minimum number of extra functional flags
1784 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001785 // 3: the output supporting the exact channel mask
1786 // 4: the output with a higher channel count than requested
1787 // 5: the output with a higher sampling rate than requested
1788 // 6: the output with the highest number of requested performance flags
1789 // 7: the output with the bit depth the closest to the requested one
1790 // 8: the primary output
1791 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001792
Eric Laurent16c66dd2019-05-01 17:54:10 -07001793 // matching criteria values in priority order for best matching output so far
1794 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001795
Eric Laurent16c66dd2019-05-01 17:54:10 -07001796 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1797 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1798 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001799
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001800 for (audio_io_handle_t output : outputs) {
1801 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001802 // matching criteria values in priority order for current output
1803 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001804
Eric Laurent16c66dd2019-05-01 17:54:10 -07001805 if (outputDesc->isDuplicated()) {
1806 continue;
1807 }
1808 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1809 continue;
1810 }
Eric Laurent8838a382014-09-08 16:44:28 -07001811
Eric Laurent16c66dd2019-05-01 17:54:10 -07001812 // If haptic channel is specified, use the haptic output if present.
1813 // When using haptic output, same audio format and sample rate are required.
1814 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001815 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001816 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1817 continue;
1818 }
1819 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001820 && format == outputDesc->getFormat()
1821 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001822 currentMatchCriteria[0] = outputHapticChannelCount;
1823 }
1824
1825 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001826 const int matchingFunctionalFlags =
1827 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1828 const int totalFunctionalFlags =
1829 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1830 // Prefer matching functional flags, but subtract unnecessary functional flags.
1831 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001832
1833 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001834 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1835 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001836 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1837 channelCount <= outputChannelCount) {
1838 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001839 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1840 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001841 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001842 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001843 currentMatchCriteria[3] = outputChannelCount;
1844 }
1845
1846 // sampling rate match
1847 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT &&
jiabin5740f082019-08-19 15:08:30 -07001848 samplingRate <= outputDesc->getSamplingRate()) {
1849 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001850 }
1851
1852 // performance flags match
1853 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1854
1855 // format match
1856 if (format != AUDIO_FORMAT_INVALID) {
1857 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001858 PolicyAudioPort::kFormatDistanceMax -
1859 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001860 }
1861
1862 // primary output match
1863 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1864
1865 // compare match criteria by priority then value
1866 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1867 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1868 bestMatchCriteria = currentMatchCriteria;
1869 bestOutput = output;
1870
1871 std::stringstream result;
1872 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1873 std::ostream_iterator<int>(result, " "));
1874 ALOGV("%s new bestOutput %d criteria %s",
1875 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001876 }
1877 }
1878
Eric Laurent16c66dd2019-05-01 17:54:10 -07001879 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001880}
1881
Eric Laurent8fc147b2018-07-22 19:13:55 -07001882status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001883{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001884 ALOGV("%s portId %d", __FUNCTION__, portId);
1885
1886 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1887 if (outputDesc == 0) {
1888 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001889 return BAD_VALUE;
1890 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001891 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001892
Eric Laurent8fc147b2018-07-22 19:13:55 -07001893 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001894 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001895
Eric Laurent733ce942017-12-07 12:18:25 -08001896 status_t status = outputDesc->start();
1897 if (status != NO_ERROR) {
1898 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001899 }
1900
Eric Laurent97ac8712018-07-27 18:59:02 -07001901 uint32_t delayMs;
1902 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001903
1904 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08001905 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001906 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07001907 }
Eric Laurentc75307b2015-03-17 15:29:32 -07001908 if (delayMs != 0) {
1909 usleep(delayMs * 1000);
1910 }
1911
1912 return status;
1913}
1914
Eric Laurent97ac8712018-07-27 18:59:02 -07001915status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
1916 const sp<TrackClientDescriptor>& client,
1917 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07001918{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001919 // cannot start playback of STREAM_TTS if any other output is being used
1920 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07001921
1922 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07001923 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01001924 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01001925 auto clientStrategy = client->strategy();
1926 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001927 if (stream == AUDIO_STREAM_TTS) {
1928 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01001929 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Eric Laurent83d17c22019-04-02 17:10:01 -07001930 toVolumeSource(AUDIO_STREAM_TTS) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07001931 return INVALID_OPERATION;
1932 } else {
1933 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
1934 }
1935 } else {
1936 // some playback other than beacon starts
1937 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
1938 }
1939
Eric Laurent77305a62016-07-25 16:39:22 -07001940 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001941 // check active before incrementing usage count
Eric Laurent77305a62016-07-25 16:39:22 -07001942 bool force = !outputDesc->isActive() &&
1943 (outputDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE);
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07001944
François Gaffie11d30102018-11-02 16:09:09 +01001945 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08001946 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07001947 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001948 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01001949 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001950 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08001951 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01001952 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001953 } else {
1954 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07001955 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001956 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
1957 AUDIO_FORMAT_DEFAULT);
1958 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
1959 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07001960 }
1961
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00001962 // requiresMuteCheck is false when we can bypass mute strategy.
1963 // It covers a common case when there is no materially active audio
1964 // and muting would result in unnecessary delay and dropped audio.
1965 const uint32_t outputLatencyMs = outputDesc->latency();
1966 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
1967
Eric Laurente552edb2014-03-10 17:42:56 -07001968 // increment usage count for this stream on the requested output:
1969 // NOTE that the usage count is the same for duplicated output and hardware output which is
1970 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07001971 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07001972
1973 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02001974 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
1975 client->isPreferredDeviceForExclusiveUse()) {
1976 // Preferred device may be exclusive, use only if no other active clients on this output
1977 devices = DeviceVector(
1978 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
1979 } else {
1980 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
1981 }
François Gaffie11d30102018-11-02 16:09:09 +01001982 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01001983 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07001984 }
1985 }
Eric Laurente552edb2014-03-10 17:42:56 -07001986
François Gaffiec005e562018-11-06 15:04:49 +01001987 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07001988 selectOutputForMusicEffects();
1989 }
1990
François Gaffie1c878552018-11-22 16:53:21 +01001991 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08001992 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01001993 if (devices.isEmpty()) {
1994 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08001995 }
François Gaffiec005e562018-11-06 15:04:49 +01001996 bool shouldWait =
1997 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
1998 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
1999 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002000 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002001 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002002 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002003 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002004 // An output has a shared device if
2005 // - managed by the same hw module
2006 // - supports the currently selected device
2007 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002008 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002009
Eric Laurent77305a62016-07-25 16:39:22 -07002010 // force a device change if any other output is:
2011 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002012 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002013 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002014 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002015 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002016 // change the device currently selected by the other output.
2017 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002018 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002019 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002020 force = true;
2021 }
2022 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002023 // a notification so that audio focus effect can propagate, or that a mute/unmute
2024 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002025 const uint32_t latencyMs = desc->latency();
2026 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2027
2028 if (shouldWait && isActive && (waitMs < latencyMs)) {
2029 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002030 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002031
2032 // Require mute check if another output is on a shared device
2033 // and currently active to have proper drain and avoid pops.
2034 // Note restoring AudioTracks onto this output needs to invoke
2035 // a volume ramp if there is no mute.
2036 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002037 }
2038 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002039
2040 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002041 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002042
Eric Laurente552edb2014-03-10 17:42:56 -07002043 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002044 auto &curves = getVolumeCurves(client->attributes());
2045 checkAndSetVolume(curves, client->volumeSource(),
2046 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002047 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002048 outputDesc->devices().types(), 0 /*delay*/,
2049 outputDesc->useHwGain() /*force*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002050
2051 // update the outputs if starting an output with a stream that can affect notification
2052 // routing
2053 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002054
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002055 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002056 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002057 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2058 }
Eric Laurentdc462862016-07-19 12:29:53 -07002059
2060 if (waitMs > muteWaitMs) {
2061 *delayMs = waitMs - muteWaitMs;
2062 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002063
2064 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2065 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2066 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2067 // change occurs after the MixerThread starts and causes a stream volume
2068 // glitch.
2069 //
2070 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002071 }
Eric Laurentdc462862016-07-19 12:29:53 -07002072
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002073 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002074 mEngine->getForceUse(
2075 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002076 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002077 }
2078
Eric Laurent97ac8712018-07-27 18:59:02 -07002079 // Automatically enable the remote submix input when output is started on a re routing mix
2080 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002081 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2082 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002083 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2084 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2085 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002086 "remote-submix",
2087 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002088 }
2089
Eric Laurente552edb2014-03-10 17:42:56 -07002090 return NO_ERROR;
2091}
2092
Eric Laurent8fc147b2018-07-22 19:13:55 -07002093status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002094{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002095 ALOGV("%s portId %d", __FUNCTION__, portId);
2096
2097 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2098 if (outputDesc == 0) {
2099 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002100 return BAD_VALUE;
2101 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002102 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002103
Eric Laurent97ac8712018-07-27 18:59:02 -07002104 ALOGV("stopOutput() output %d, stream %d, session %d",
2105 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002106
Eric Laurent97ac8712018-07-27 18:59:02 -07002107 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002108
Eric Laurent733ce942017-12-07 12:18:25 -08002109 if (status == NO_ERROR ) {
2110 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002111 }
2112 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002113}
2114
Eric Laurent97ac8712018-07-27 18:59:02 -07002115status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2116 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002117{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002118 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002119 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002120 auto clientVolSrc = client->volumeSource();
Eric Laurent97ac8712018-07-27 18:59:02 -07002121
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002122 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2123
François Gaffie1c878552018-11-22 16:53:21 +01002124 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2125 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002126 // Automatically disable the remote submix input when output is stopped on a
2127 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002128 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002129 if (isSingleDeviceType(
2130 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002131 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002132 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002133 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2134 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002135 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002136 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002137 }
2138 }
2139 bool forceDeviceUpdate = false;
2140 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002141 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002142 forceDeviceUpdate = true;
2143 }
2144
Eric Laurente552edb2014-03-10 17:42:56 -07002145 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002146 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002147
Eric Laurente552edb2014-03-10 17:42:56 -07002148 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002149 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002150 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002151 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurente552edb2014-03-10 17:42:56 -07002152 // delay the device switch by twice the latency because stopOutput() is executed when
2153 // the track stop() command is received and at that time the audio track buffer can
2154 // still contain data that needs to be drained. The latency only covers the audio HAL
2155 // and kernel buffers. Also the latency does not always include additional delay in the
2156 // audio path (audio DSP, CODEC ...)
François Gaffie11d30102018-11-02 16:09:09 +01002157 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2);
Eric Laurente552edb2014-03-10 17:42:56 -07002158
2159 // force restoring the device selection on other active outputs if it differs from the
2160 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002161 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002162 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002163 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002164 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002165 desc->isActive() &&
2166 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002167 (newDevices != desc->devices())) {
2168 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2169 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002170
François Gaffie11d30102018-11-02 16:09:09 +01002171 setOutputDevices(desc, newDevices2, force, delayMs);
2172
Eric Laurent57de36c2016-09-28 16:59:11 -07002173 // re-apply device specific volume if not done by setOutputDevice()
2174 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002175 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002176 }
Eric Laurente552edb2014-03-10 17:42:56 -07002177 }
2178 }
2179 // update the outputs if stopping one with a stream that can affect notification routing
2180 handleNotificationRoutingForStream(stream);
2181 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002182
2183 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2184 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002185 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002186 }
2187
François Gaffiec005e562018-11-06 15:04:49 +01002188 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002189 selectOutputForMusicEffects();
2190 }
Eric Laurente552edb2014-03-10 17:42:56 -07002191 return NO_ERROR;
2192 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002193 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002194 return INVALID_OPERATION;
2195 }
2196}
2197
jiabinbce0c1d2020-10-05 11:20:18 -07002198bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002199{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002200 ALOGV("%s portId %d", __FUNCTION__, portId);
2201
2202 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2203 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002204 // If an output descriptor is closed due to a device routing change,
2205 // then there are race conditions with releaseOutput from tracks
2206 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2207 // destroyed shortly thereafter.
2208 //
2209 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002210 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002211 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002212 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002213
2214 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002215
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302216 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2217 if (outputDesc->isClientActive(client)) {
2218 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2219 stopOutput(portId);
2220 }
2221
Eric Laurent8fc147b2018-07-22 19:13:55 -07002222 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2223 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002224 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002225 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002226 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002227 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002228 if (--outputDesc->mDirectOpenCount == 0) {
2229 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002230 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002231 }
2232 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302233
Andy Hung39efb7a2018-09-26 15:39:28 -07002234 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002235 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2236 // The output is pending reopened to query dynamic profiles and
2237 // there is no active clients
2238 closeOutput(outputDesc->mIoHandle);
2239 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2240 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2241 if (newOutputDesc == nullptr) {
2242 ALOGE("%s failed to open output", __func__);
2243 }
2244 return true;
2245 }
2246 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002247}
2248
Eric Laurentcaf7f482014-11-25 17:50:47 -08002249status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2250 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002251 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002252 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002253 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002254 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002255 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002256 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002257 input_type_t *inputType,
2258 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002259{
François Gaffiec005e562018-11-06 15:04:49 +01002260 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002261 "flags %#x attributes=%s requested device ID %d",
2262 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2263 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002264
Eric Laurentad2e7b92017-09-14 20:06:42 -07002265 status_t status = NO_ERROR;
Eric Laurentc447ded2015-01-06 08:47:05 -08002266 audio_source_t halInputSource;
Francois Gaffie716e1432019-01-14 16:58:59 +01002267 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002268 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002269 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002270 sp<AudioInputDescriptor> inputDesc;
2271 sp<RecordClientDescriptor> clientDesc;
2272 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002273 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002274 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002275
2276 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2277 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2278 return INVALID_OPERATION;
2279 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002280
Francois Gaffie716e1432019-01-14 16:58:59 +01002281 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2282 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002283 }
2284
Paul McLean466dc8e2015-04-17 13:15:36 -06002285 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002286 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002287 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002288
Eric Laurentad2e7b92017-09-14 20:06:42 -07002289 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2290 // possible
2291 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2292 *input != AUDIO_IO_HANDLE_NONE) {
2293 ssize_t index = mInputs.indexOfKey(*input);
2294 if (index < 0) {
2295 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2296 status = BAD_VALUE;
2297 goto error;
2298 }
2299 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002300 RecordClientVector clients = inputDesc->getClientsForSession(session);
2301 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002302 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2303 status = BAD_VALUE;
2304 goto error;
2305 }
2306 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2307 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002308 // corresponds to a new client and is only permitted from the same UID.
2309 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002310 if (clients.size() > 1) {
2311 for (const auto& client : clients) {
2312 // The client map is ordered by key values (portId) and portIds are allocated
2313 // incrementaly. So the first client in this list is the one opened by audio flinger
2314 // when the mmap stream is created and should be ignored as it does not correspond
2315 // to an actual client
2316 if (client == *clients.cbegin()) {
2317 continue;
2318 }
2319 if (uid != client->uid() && !client->isSilenced()) {
2320 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2321 uid, client->portId(), client->uid());
2322 status = INVALID_OPERATION;
2323 goto error;
2324 }
Eric Laurent331679c2018-04-16 17:03:16 -07002325 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002326 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002327 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002328 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002329
Eric Laurentfecbceb2021-02-09 14:46:43 +01002330 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002331 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002332 }
2333
2334 *input = AUDIO_IO_HANDLE_NONE;
2335 *inputType = API_INPUT_INVALID;
2336
Francois Gaffie716e1432019-01-14 16:58:59 +01002337 halInputSource = attributes.source;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002338
Francois Gaffie716e1432019-01-14 16:58:59 +01002339 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2340 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2341 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002342 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002343 ALOGW("%s could not find input mix for attr %s",
2344 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002345 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002346 }
jiabinc1de2df2019-05-07 14:26:40 -07002347 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2348 String8(attr->tags + strlen("addr=")),
2349 AUDIO_FORMAT_DEFAULT);
2350 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002351 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002352 __func__, attributes.source, attributes.tags);
2353 status = BAD_VALUE;
2354 goto error;
2355 }
2356
Kevin Rocard25f9b052019-02-27 15:08:54 -08002357 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2358 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2359 } else {
2360 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2361 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002362 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002363 if (explicitRoutingDevice != nullptr) {
2364 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002365 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002366 // Prevent from storing invalid requested device id in clients
2367 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002368 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002369 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2370 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002371 }
François Gaffie11d30102018-11-02 16:09:09 +01002372 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002373 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002374 status = BAD_VALUE;
2375 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002376 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002377 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2378 *inputType = API_INPUT_MIX_CAPTURE;
2379 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002380 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2381 // there is an external policy, but this input is attached to a mix of recorders,
2382 // meaning it receives audio injected into the framework, so the recorder doesn't
2383 // know about it and is therefore considered "legacy"
2384 *inputType = API_INPUT_LEGACY;
2385 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002386 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002387 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002388 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002389 } else {
2390 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002391 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002392
Eric Laurent599c7582015-12-07 18:05:55 -08002393 }
2394
François Gaffiec005e562018-11-06 15:04:49 +01002395 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002396 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002397 status = INVALID_OPERATION;
2398 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002399 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002400
Eric Laurent8f42ea12018-08-08 09:08:25 -07002401exit:
2402
François Gaffiec005e562018-11-06 15:04:49 +01002403 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2404 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002405
Francois Gaffie716e1432019-01-14 16:58:59 +01002406 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002407 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002408 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002409
Mikhail Naganov2996f672019-04-18 12:29:59 -07002410 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002411 requestedDeviceId, attributes.source, flags,
2412 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002413 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002414 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002415
2416 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2417 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002418
Eric Laurent599c7582015-12-07 18:05:55 -08002419 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002420
2421error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002422 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002423}
2424
2425
François Gaffie11d30102018-11-02 16:09:09 +01002426audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002427 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002428 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002429 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002430 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002431 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002432{
2433 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002434 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002435 bool isSoundTrigger = false;
2436
François Gaffiec005e562018-11-06 15:04:49 +01002437 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002438 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2439 if (index >= 0) {
2440 input = mSoundTriggerSessions.valueFor(session);
2441 isSoundTrigger = true;
2442 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2443 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2444 } else {
2445 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002446 }
François Gaffiec005e562018-11-06 15:04:49 +01002447 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002448 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002449 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002450 }
2451
Carter Hsua3abb402021-10-26 11:11:20 +08002452 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2453 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2454 }
2455
Andy Hungf129b032015-04-07 13:45:50 -07002456 // find a compatible input profile (not necessarily identical in parameters)
2457 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002458 // sampling rate and flags may be updated by getInputProfile
2459 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2460 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002461 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002462 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002463 audio_input_flags_t profileFlags = flags;
2464 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002465 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002466 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002467 profileFlags);
2468 if (profile != 0) {
2469 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002470 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2471 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002472 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002473 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2474 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002475 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002476 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002477 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002478 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002479 }
Eric Laurente552edb2014-03-10 17:42:56 -07002480 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002481 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002482 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002483 if (samplingRate == 0) {
2484 samplingRate = profileSamplingRate;
2485 }
Eric Laurente552edb2014-03-10 17:42:56 -07002486
Eric Laurent322b4d22015-04-03 15:57:54 -07002487 if (profile->getModuleHandle() == 0) {
2488 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002489 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002490 }
2491
Eric Laurentec376dc2021-04-08 20:41:22 +02002492 // Reuse an already opened input if a client with the same session ID already exists
2493 // on that input
2494 for (size_t i = 0; i < mInputs.size(); i++) {
2495 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2496 if (desc->mProfile != profile) {
2497 continue;
2498 }
2499 RecordClientVector clients = desc->clientsList();
2500 for (const auto &client : clients) {
2501 if (session == client->session()) {
2502 return desc->mIoHandle;
2503 }
2504 }
2505 }
2506
Eric Laurent3974e3b2017-12-07 17:58:43 -08002507 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002508 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002509 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002510 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002511 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002512 continue;
2513 }
2514 // if sound trigger, reuse input if used by other sound trigger on same session
2515 // else
2516 // reuse input if active client app is not in IDLE state
2517 //
2518 RecordClientVector clients = desc->clientsList();
2519 bool doClose = false;
2520 for (const auto& client : clients) {
2521 if (isSoundTrigger != client->isSoundTrigger()) {
2522 continue;
2523 }
2524 if (client->isSoundTrigger()) {
2525 if (session == client->session()) {
2526 return desc->mIoHandle;
2527 }
2528 continue;
2529 }
2530 if (client->active() && client->appState() != APP_STATE_IDLE) {
2531 return desc->mIoHandle;
2532 }
2533 doClose = true;
2534 }
2535 if (doClose) {
2536 closeInput(desc->mIoHandle);
2537 } else {
2538 i++;
2539 }
2540 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002541 }
2542
Eric Laurentfe231122017-11-17 17:48:06 -08002543 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002544
Eric Laurentfe231122017-11-17 17:48:06 -08002545 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2546 lConfig.sample_rate = profileSamplingRate;
2547 lConfig.channel_mask = profileChannelMask;
2548 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002549
François Gaffie11d30102018-11-02 16:09:09 +01002550 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002551
2552 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002553 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002554 (profileSamplingRate != lConfig.sample_rate) ||
2555 !audio_formats_match(profileFormat, lConfig.format) ||
2556 (profileChannelMask != lConfig.channel_mask)) {
2557 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002558 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002559 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002560 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002561 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002562 }
Eric Laurent599c7582015-12-07 18:05:55 -08002563 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002564 }
2565
Eric Laurentc722f302014-12-10 11:21:49 -08002566 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002567
Eric Laurent599c7582015-12-07 18:05:55 -08002568 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002569 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002570
Eric Laurent599c7582015-12-07 18:05:55 -08002571 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002572}
2573
Eric Laurent4eb58f12018-12-07 16:41:02 -08002574status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002575{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002576 ALOGV("%s portId %d", __FUNCTION__, portId);
2577
2578 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2579 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002580 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002581 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002582 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002583 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002584 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002585 if (client->active()) {
2586 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2587 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002588 }
2589
Eric Laurent8f42ea12018-08-08 09:08:25 -07002590 audio_session_t session = client->session();
2591
Eric Laurent4eb58f12018-12-07 16:41:02 -08002592 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002593
Eric Laurent4eb58f12018-12-07 16:41:02 -08002594 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002595
Eric Laurent4eb58f12018-12-07 16:41:02 -08002596 status_t status = inputDesc->start();
2597 if (status != NO_ERROR) {
2598 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002599 }
Eric Laurente552edb2014-03-10 17:42:56 -07002600
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002601 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002602 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002603 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002604
Eric Laurent8f42ea12018-08-08 09:08:25 -07002605 // indicate active capture to sound trigger service if starting capture from a mic on
2606 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002607 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002608 if (device != nullptr) {
2609 status = setInputDevice(input, device, true /* force */);
2610 } else {
2611 ALOGW("%s no new input device can be found for descriptor %d",
2612 __FUNCTION__, inputDesc->getId());
2613 status = BAD_VALUE;
2614 }
Eric Laurente552edb2014-03-10 17:42:56 -07002615
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002616 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002617 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002618 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002619 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002620 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2621 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002622 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002623 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002624
François Gaffie11d30102018-11-02 16:09:09 +01002625 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2626 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002627 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002628 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002629 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002630
Eric Laurent8f42ea12018-08-08 09:08:25 -07002631 // automatically enable the remote submix output when input is started if not
2632 // used by a policy mix of type MIX_TYPE_RECORDERS
2633 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002634 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002635 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002636 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002637 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002638 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2639 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002640 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002641 if (address != "") {
2642 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2643 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002644 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002645 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002646 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002647 } else if (status != NO_ERROR) {
2648 // Restore client activity state.
2649 inputDesc->setClientActive(client, false);
2650 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002651 }
2652
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002653 ALOGV("%s input %d source = %d status = %d exit",
2654 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002655
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002656 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002657}
2658
Eric Laurent8fc147b2018-07-22 19:13:55 -07002659status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002660{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002661 ALOGV("%s portId %d", __FUNCTION__, portId);
2662
2663 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2664 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002665 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002666 return BAD_VALUE;
2667 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002668 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002669 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002670 if (!client->active()) {
2671 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002672 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002673 }
Carter Hsue6139d52021-07-08 10:30:20 +08002674 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002675 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002676
Eric Laurent8f42ea12018-08-08 09:08:25 -07002677 inputDesc->stop();
2678 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002679 auto current_source = inputDesc->source();
2680 setInputDevice(input, getNewInputDevice(inputDesc),
2681 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002682 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002683 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002684 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002685 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002686 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2687 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002688 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002689 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002690
2691 // automatically disable the remote submix output when input is stopped if not
2692 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002693 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002694 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002695 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002696 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002697 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2698 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002699 }
2700 if (address != "") {
2701 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2702 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002703 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002704 }
2705 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002706 resetInputDevice(input);
2707
2708 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2709 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002710 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2711 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002712 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002713 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002714 }
2715 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002716 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002717 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002718}
2719
Eric Laurent8fc147b2018-07-22 19:13:55 -07002720void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002721{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002722 ALOGV("%s portId %d", __FUNCTION__, portId);
2723
2724 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2725 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002726 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002727 return;
2728 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002729 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002730 audio_io_handle_t input = inputDesc->mIoHandle;
2731
Eric Laurent8f42ea12018-08-08 09:08:25 -07002732 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002733
Andy Hung39efb7a2018-09-26 15:39:28 -07002734 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002735
Andy Hung39efb7a2018-09-26 15:39:28 -07002736 if (inputDesc->getClientCount() > 0) {
2737 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002738 return;
2739 }
2740
Eric Laurent05b90f82014-08-27 15:32:29 -07002741 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002742 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002743 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002744}
2745
Eric Laurent8f42ea12018-08-08 09:08:25 -07002746void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002747{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002748 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002749
2750 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002751 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002752 }
2753}
2754
Eric Laurent8f42ea12018-08-08 09:08:25 -07002755void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2756{
2757 stopInput(portId);
2758 releaseInput(portId);
2759}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002760
Eric Laurent0dd51852019-04-19 18:18:58 -07002761void AudioPolicyManager::checkCloseInputs() {
2762 // After connecting or disconnecting an input device, close input if:
2763 // - it has no client (was just opened to check profile) OR
2764 // - none of its supported devices are connected anymore OR
2765 // - one of its clients cannot be routed to one of its supported
2766 // devices anymore. Otherwise update device selection
2767 std::vector<audio_io_handle_t> inputsToClose;
2768 for (size_t i = 0; i < mInputs.size(); i++) {
2769 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2770 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002771 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002772 inputsToClose.push_back(mInputs.keyAt(i));
2773 } else {
2774 bool close = false;
2775 for (const auto& client : input->clientsList()) {
2776 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002777 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002778 if (!input->supportedDevices().contains(device)) {
2779 close = true;
2780 break;
2781 }
2782 }
2783 if (close) {
2784 inputsToClose.push_back(mInputs.keyAt(i));
2785 } else {
2786 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2787 }
2788 }
2789 }
2790
2791 for (const audio_io_handle_t handle : inputsToClose) {
2792 ALOGV("%s closing input %d", __func__, handle);
2793 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002794 }
Eric Laurentd4692962014-05-05 18:13:44 -07002795}
2796
François Gaffie251c7f02018-11-07 10:41:08 +01002797void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002798{
2799 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002800 if (indexMin < 0 || indexMax < 0) {
2801 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2802 return;
2803 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002804 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002805
2806 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002807 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2808 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002809 continue;
2810 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002811 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002812 }
Eric Laurente552edb2014-03-10 17:42:56 -07002813}
2814
Eric Laurente0720872014-03-11 09:30:41 -07002815status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002816 int index,
2817 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002818{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002819 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002820 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2821 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2822 return NO_ERROR;
2823 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002824 ALOGV("%s: stream %s attributes=%s", __func__,
2825 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002826 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002827}
2828
Eric Laurente0720872014-03-11 09:30:41 -07002829status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002830 int *index,
2831 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002832{
François Gaffiec005e562018-11-06 15:04:49 +01002833 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2834 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002835 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002836 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002837 deviceTypes = mEngine->getOutputDevicesForStream(
2838 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002839 }
jiabin9a3361e2019-10-01 09:38:30 -07002840 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002841}
2842
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002843status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002844 int index,
2845 audio_devices_t device)
2846{
2847 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002848 auto group = mEngine->getVolumeGroupForAttributes(attributes);
2849 if (group == VOLUME_GROUP_NONE) {
2850 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002851 return BAD_VALUE;
2852 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002853 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01002854 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002855 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01002856 VolumeSource vs = toVolumeSource(group);
2857 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
2858
2859 status = setVolumeCurveIndex(index, device, curves);
2860 if (status != NO_ERROR) {
2861 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
2862 return status;
2863 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002864
jiabin9a3361e2019-10-01 09:38:30 -07002865 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002866 auto curCurvAttrs = curves.getAttributes();
2867 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
2868 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07002869 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002870 } else if (!curves.getStreamTypes().empty()) {
2871 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07002872 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002873 } else {
2874 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
2875 return BAD_VALUE;
2876 }
jiabin9a3361e2019-10-01 09:38:30 -07002877 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
2878 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002879
François Gaffiecfe17322018-11-07 13:41:29 +01002880 // update volume on all outputs and streams matching the following:
2881 // - The requested stream (or a stream matching for volume control) is active on the output
2882 // - The device (or devices) selected by the engine for this stream includes
2883 // the requested device
2884 // - For non default requested device, currently selected device on the output is either the
2885 // requested device or one of the devices selected by the engine for this stream
2886 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
2887 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002888 for (size_t i = 0; i < mOutputs.size(); i++) {
2889 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07002890 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01002891
jiabin9a3361e2019-10-01 09:38:30 -07002892 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
2893 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08002894 }
François Gaffieed91f582020-01-31 10:35:37 +01002895 if (!(desc->isActive(vs) || isInCall())) {
2896 continue;
2897 }
2898 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
2899 curDevices.find(device) == curDevices.end()) {
2900 continue;
2901 }
2902 bool applyVolume = false;
2903 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
2904 curSrcDevices.insert(device);
2905 applyVolume = (curSrcDevices.find(
2906 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
2907 } else {
2908 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
2909 }
2910 if (!applyVolume) {
2911 continue; // next output
2912 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002913 // Inter / intra volume group priority management: Loop on strategies arranged by priority
2914 // If a higher priority strategy is active, and the output is routed to a device with a
2915 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01002916 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01002917 applyVolume = false;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002918 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
2919 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
2920 false /*preferredDevice*/);
2921 if (activeClients.empty()) {
2922 continue;
2923 }
2924 bool isPreempted = false;
2925 bool isHigherPriority = productStrategy < strategy;
2926 for (const auto &client : activeClients) {
2927 if (isHigherPriority && (client->volumeSource() != vs)) {
2928 ALOGV("%s: Strategy=%d (\nrequester:\n"
2929 " group %d, volumeGroup=%d attributes=%s)\n"
2930 " higher priority source active:\n"
2931 " volumeGroup=%d attributes=%s) \n"
2932 " on output %zu, bailing out", __func__, productStrategy,
2933 group, group, toString(attributes).c_str(),
2934 client->volumeSource(), toString(client->attributes()).c_str(), i);
2935 applyVolume = false;
2936 isPreempted = true;
2937 break;
2938 }
2939 // However, continue for loop to ensure no higher prio clients running on output
2940 if (client->volumeSource() == vs) {
2941 applyVolume = true;
2942 }
2943 }
2944 if (isPreempted || applyVolume) {
2945 break;
2946 }
2947 }
2948 if (!applyVolume) {
2949 continue; // next output
2950 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002951 }
François Gaffieed91f582020-01-31 10:35:37 +01002952 //FIXME: workaround for truncated touch sounds
2953 // delayed volume change for system stream to be removed when the problem is
2954 // handled by system UI
2955 status_t volStatus = checkAndSetVolume(
2956 curves, vs, index, desc, curDevices,
2957 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM))?
2958 TOUCH_SOUND_FIXED_DELAY_MS : 0));
2959 if (volStatus != NO_ERROR) {
2960 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01002961 }
2962 }
François Gaffiecfe17322018-11-07 13:41:29 +01002963 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
2964 return status;
2965}
2966
François Gaffieaaac0fd2018-11-22 17:56:39 +01002967status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01002968 audio_devices_t device,
2969 IVolumeCurves &volumeCurves)
2970{
2971 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
2972 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01002973 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
2974 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01002975 (index > volumeCurves.getVolumeIndexMax())) {
2976 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
2977 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
2978 return BAD_VALUE;
2979 }
2980 if (!audio_is_output_device(device)) {
2981 return BAD_VALUE;
2982 }
2983
2984 // Force max volume if stream cannot be muted
2985 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
2986
François Gaffieaaac0fd2018-11-22 17:56:39 +01002987 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01002988 volumeCurves.addCurrentVolumeIndex(device, index);
2989 return NO_ERROR;
2990}
2991
2992status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
2993 int &index,
2994 audio_devices_t device)
2995{
2996 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2997 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002998 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01002999 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003000 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3001 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003002 }
jiabin9a3361e2019-10-01 09:38:30 -07003003 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003004}
3005
3006status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3007 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003008 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003009{
jiabin9a3361e2019-10-01 09:38:30 -07003010 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003011 return BAD_VALUE;
3012 }
jiabin9a3361e2019-10-01 09:38:30 -07003013 index = curves.getVolumeIndex(deviceTypes);
3014 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003015 return NO_ERROR;
3016}
3017
3018status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3019 int &index)
3020{
3021 index = getVolumeCurves(attr).getVolumeIndexMin();
3022 return NO_ERROR;
3023}
3024
3025status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3026 int &index)
3027{
3028 index = getVolumeCurves(attr).getVolumeIndexMax();
3029 return NO_ERROR;
3030}
3031
Eric Laurent36829f92017-04-07 19:04:42 -07003032audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003033{
3034 // select one output among several suitable for global effects.
3035 // The priority is as follows:
3036 // 1: An offloaded output. If the effect ends up not being offloadable,
3037 // AudioFlinger will invalidate the track and the offloaded output
3038 // will be closed causing the effect to be moved to a PCM output.
3039 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003040 // 3: The primary output
3041 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003042
François Gaffiec005e562018-11-06 15:04:49 +01003043 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3044 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003045 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003046
Eric Laurent36829f92017-04-07 19:04:42 -07003047 if (outputs.size() == 0) {
3048 return AUDIO_IO_HANDLE_NONE;
3049 }
Eric Laurente552edb2014-03-10 17:42:56 -07003050
Eric Laurent36829f92017-04-07 19:04:42 -07003051 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3052 bool activeOnly = true;
3053
3054 while (output == AUDIO_IO_HANDLE_NONE) {
3055 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3056 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3057 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3058
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003059 for (audio_io_handle_t output : outputs) {
3060 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003061 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003062 continue;
3063 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003064 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3065 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003066 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003067 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003068 }
3069 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003070 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003071 }
3072 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003073 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003074 }
3075 }
3076 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3077 output = outputOffloaded;
3078 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3079 output = outputDeepBuffer;
3080 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3081 output = outputPrimary;
3082 } else {
3083 output = outputs[0];
3084 }
3085 activeOnly = false;
3086 }
3087
3088 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003089 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003090 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3091 mMusicEffectOutput = output;
3092 }
3093
3094 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003095 return output;
3096}
3097
Eric Laurent36829f92017-04-07 19:04:42 -07003098audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3099{
3100 return selectOutputForMusicEffects();
3101}
3102
Eric Laurente0720872014-03-11 09:30:41 -07003103status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003104 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003105 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003106 int session,
3107 int id)
3108{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003109 if (session != AUDIO_SESSION_DEVICE) {
3110 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003111 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003112 index = mInputs.indexOfKey(io);
3113 if (index < 0) {
3114 ALOGW("registerEffect() unknown io %d", io);
3115 return INVALID_OPERATION;
3116 }
Eric Laurente552edb2014-03-10 17:42:56 -07003117 }
3118 }
François Gaffiec005e562018-11-06 15:04:49 +01003119 return mEffects.registerEffect(desc, io, session, id,
3120 (strategy == streamToStrategy(AUDIO_STREAM_MUSIC) ||
3121 strategy == PRODUCT_STRATEGY_NONE));
Eric Laurente552edb2014-03-10 17:42:56 -07003122}
3123
Eric Laurentc241b0d2018-11-28 09:08:49 -08003124status_t AudioPolicyManager::unregisterEffect(int id)
3125{
3126 if (mEffects.getEffect(id) == nullptr) {
3127 return INVALID_OPERATION;
3128 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003129 if (mEffects.isEffectEnabled(id)) {
3130 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3131 setEffectEnabled(id, false);
3132 }
3133 return mEffects.unregisterEffect(id);
3134}
3135
3136status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3137{
3138 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3139 if (effect == nullptr) {
3140 return INVALID_OPERATION;
3141 }
3142
3143 status_t status = mEffects.setEffectEnabled(id, enabled);
3144 if (status == NO_ERROR) {
3145 mInputs.trackEffectEnabled(effect, enabled);
3146 }
3147 return status;
3148}
3149
Eric Laurent6c796322019-04-09 14:13:17 -07003150
3151status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3152{
3153 mEffects.moveEffects(ids, io);
3154 return NO_ERROR;
3155}
3156
Eric Laurentc75307b2015-03-17 15:29:32 -07003157bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3158{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003159 return mOutputs.isActive(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003160}
3161
3162bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3163{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003164 return mOutputs.isActiveRemotely(toVolumeSource(stream), inPastMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07003165}
3166
Eric Laurente0720872014-03-11 09:30:41 -07003167bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003168{
3169 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003170 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003171 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003172 return true;
3173 }
3174 }
3175 return false;
3176}
3177
Eric Laurent275e8e92014-11-30 15:14:47 -08003178// Register a list of custom mixes with their attributes and format.
3179// When a mix is registered, corresponding input and output profiles are
3180// added to the remote submix hw module. The profile contains only the
3181// parameters (sampling rate, format...) specified by the mix.
3182// The corresponding input remote submix device is also connected.
3183//
3184// When a remote submix device is connected, the address is checked to select the
3185// appropriate profile and the corresponding input or output stream is opened.
3186//
3187// When capture starts, getInputForAttr() will:
3188// - 1 look for a mix matching the address passed in attribtutes tags if any
3189// - 2 if none found, getDeviceForInputSource() will:
3190// - 2.1 look for a mix matching the attributes source
3191// - 2.2 if none found, default to device selection by policy rules
3192// At this time, the corresponding output remote submix device is also connected
3193// and active playback use cases can be transferred to this mix if needed when reconnecting
3194// after AudioTracks are invalidated
3195//
3196// When playback starts, getOutputForAttr() will:
3197// - 1 look for a mix matching the address passed in attribtutes tags if any
3198// - 2 if none found, look for a mix matching the attributes usage
3199// - 3 if none found, default to device and output selection by policy rules.
3200
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003201status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003202{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003203 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3204 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003205 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003206 sp<HwModule> rSubmixModule;
3207 // examine each mix's route type
3208 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003209 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003210 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3211 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3212 ALOGE("Unsupported Policy Mix %zu of %zu: "
3213 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3214 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003215 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003216 break;
3217 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003218 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3219 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003220 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003221 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3222 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003223 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003224 rSubmixModule = mHwModules.getModuleFromName(
3225 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3226 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003227 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003228 i);
3229 res = INVALID_OPERATION;
3230 break;
3231 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003232 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003233
Eric Laurent97ac8712018-07-27 18:59:02 -07003234 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003235 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003236 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003237 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003238 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3239 } else {
3240 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3241 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003242 }
François Gaffie036e1e92015-03-19 10:16:24 +01003243
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003244 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003245 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003246 res = INVALID_OPERATION;
3247 break;
3248 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003249 audio_config_t outputConfig = mix.mFormat;
3250 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003251 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3252 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003253 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3254 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003255 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003256 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003257 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003258 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003259
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003260 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003261 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3262 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3263 ALOGE("Failed to set remote submix device available, type %u, address %s",
3264 mix.mDeviceType, address.string());
3265 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003266 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003267 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3268 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003269 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003270 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003271 i, mixes.size(), type, address.string());
3272
3273 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3274 mix.mDeviceType, mix.mDeviceAddress,
3275 String8(), AUDIO_FORMAT_DEFAULT);
3276 if (device == nullptr) {
3277 res = INVALID_OPERATION;
3278 break;
3279 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003280
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003281 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003282 // First try to find an already opened output supporting the device
3283 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003284 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003285
Eric Laurentc529cf62020-04-17 18:19:10 -07003286 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003287 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003288 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3289 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003290 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003291 } else {
3292 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003293 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003294 }
3295 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003296 // If no output found, try to find a direct output profile supporting the device
3297 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3298 sp<HwModule> module = mHwModules[i];
3299 for (size_t j = 0;
3300 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3301 j++) {
3302 sp<IOProfile> profile = module->getOutputProfiles()[j];
3303 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3304 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3305 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3306 address.string());
3307 res = INVALID_OPERATION;
3308 } else {
3309 foundOutput = true;
3310 }
3311 }
3312 }
3313 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003314 if (res != NO_ERROR) {
3315 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003316 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003317 res = INVALID_OPERATION;
3318 break;
3319 } else if (!foundOutput) {
3320 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003321 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003322 res = INVALID_OPERATION;
3323 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003324 } else {
3325 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003326 }
Eric Laurentc722f302014-12-10 11:21:49 -08003327 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003328 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003329 if (res != NO_ERROR) {
3330 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003331 } else if (checkOutputs) {
3332 checkForDeviceAndOutputChanges();
3333 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003334 }
3335 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003336}
3337
3338status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3339{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003340 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003341 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003342 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003343 sp<HwModule> rSubmixModule;
3344 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003345 for (const auto& mix : mixes) {
3346 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003347
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003348 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003349 rSubmixModule = mHwModules.getModuleFromName(
3350 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3351 if (rSubmixModule == 0) {
3352 res = INVALID_OPERATION;
3353 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003354 }
3355 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003356
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003357 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003358
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003359 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003360 res = INVALID_OPERATION;
3361 continue;
3362 }
3363
Kevin Rocard04ed0462019-05-02 17:53:24 -07003364 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3365 if (getDeviceConnectionState(device, address.string()) ==
3366 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3367 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3368 address.string(), "remote-submix",
3369 AUDIO_FORMAT_DEFAULT);
3370 if (res != OK) {
3371 ALOGE("Error making RemoteSubmix device unavailable for mix "
3372 "with type %d, address %s", device, address.string());
3373 }
3374 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003375 }
jiabin5740f082019-08-19 15:08:30 -07003376 rSubmixModule->removeOutputProfile(address.c_str());
3377 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003378
Kevin Rocard153f92d2018-12-18 18:33:28 -08003379 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003380 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003381 res = INVALID_OPERATION;
3382 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003383 } else {
3384 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003385 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003386 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003387 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003388 if (res == NO_ERROR && checkOutputs) {
3389 checkForDeviceAndOutputChanges();
3390 updateCallAndOutputRouting();
3391 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003392 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003393}
3394
Mikhail Naganov100f0122018-11-29 11:22:16 -08003395void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3396{
3397 size_t i = 0;
3398 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3399 for (const auto& fmt : mManualSurroundFormats) {
3400 if (i++ != 0) dst->append(", ");
3401 std::string sfmt;
3402 FormatConverter::toString(fmt, sfmt);
3403 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3404 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3405 }
3406}
3407
Eric Laurentc529cf62020-04-17 18:19:10 -07003408// Returns true if all devices types match the predicate and are supported by one HW module
3409bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003410 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003411 std::function<bool(audio_devices_t)> predicate,
3412 const char *context) {
3413 for (size_t i = 0; i < devices.size(); i++) {
3414 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003415 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003416 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003417 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003418 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003419 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003420 return false;
3421 }
3422 }
3423 return true;
3424}
3425
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003426status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003427 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003428 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003429 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3430 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003431 }
3432 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003433 if (res != NO_ERROR) {
3434 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3435 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003436 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003437
3438 checkForDeviceAndOutputChanges();
3439 updateCallAndOutputRouting();
3440
3441 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003442}
3443
3444status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3445 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003446 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3447 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003448 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003449 __FUNCTION__, uid);
3450 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003451 }
3452
Eric Laurentc529cf62020-04-17 18:19:10 -07003453 checkForDeviceAndOutputChanges();
3454 updateCallAndOutputRouting();
3455
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003456 return res;
3457}
3458
Eric Laurent2517af32020-11-25 15:31:27 +01003459
jiabin0a488932020-08-07 17:32:40 -07003460status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3461 device_role_t role,
3462 const AudioDeviceTypeAddrVector &devices) {
3463 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3464 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003465
Eric Laurentc529cf62020-04-17 18:19:10 -07003466 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003467 return BAD_VALUE;
3468 }
jiabin0a488932020-08-07 17:32:40 -07003469 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003470 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003471 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3472 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003473 return status;
3474 }
3475
3476 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003477
3478 bool forceVolumeReeval = false;
3479 // FIXME: workaround for truncated touch sounds
3480 // to be removed when the problem is handled by system UI
3481 uint32_t delayMs = 0;
3482 if (strategy == mCommunnicationStrategy) {
3483 forceVolumeReeval = true;
3484 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3485 updateInputRouting();
3486 }
3487 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003488
3489 return NO_ERROR;
3490}
3491
3492void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3493{
3494 uint32_t waitMs = 0;
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003495 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003496 // Only apply special touch sound delay once
3497 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003498 }
3499 for (size_t i = 0; i < mOutputs.size(); i++) {
3500 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3501 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
3502 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) || (outputDesc != mPrimaryOutput)) {
3503 // As done in setDeviceConnectionState, we could also fix default device issue by
3504 // preventing the force re-routing in case of default dev that distinguishes on address.
3505 // Let's give back to engine full device choice decision however.
3506 waitMs = setOutputDevices(outputDesc, newDevices, !newDevices.isEmpty(), delayMs);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003507 // Only apply special touch sound delay once
3508 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003509 }
3510 if (forceVolumeReeval && !newDevices.isEmpty()) {
3511 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3512 }
3513 }
3514}
3515
Eric Laurent2517af32020-11-25 15:31:27 +01003516void AudioPolicyManager::updateInputRouting() {
3517 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303518 // Skip for hotword recording as the input device switch
3519 // is handled within sound trigger HAL
3520 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3521 continue;
3522 }
Eric Laurent2517af32020-11-25 15:31:27 +01003523 auto newDevice = getNewInputDevice(activeDesc);
3524 // Force new input selection if the new device can not be reached via current input
3525 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3526 setInputDevice(activeDesc->mIoHandle, newDevice);
3527 } else {
3528 closeInput(activeDesc->mIoHandle);
3529 }
3530 }
3531}
3532
jiabin0a488932020-08-07 17:32:40 -07003533status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3534 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003535{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003536 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003537
jiabin0a488932020-08-07 17:32:40 -07003538 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003539 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003540 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3541 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003542 return status;
3543 }
3544
3545 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003546
3547 bool forceVolumeReeval = false;
3548 // FIXME: workaround for truncated touch sounds
3549 // to be removed when the problem is handled by system UI
3550 uint32_t delayMs = 0;
3551 if (strategy == mCommunnicationStrategy) {
3552 forceVolumeReeval = true;
3553 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3554 updateInputRouting();
3555 }
3556 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003557
3558 return NO_ERROR;
3559}
3560
jiabin0a488932020-08-07 17:32:40 -07003561status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3562 device_role_t role,
3563 AudioDeviceTypeAddrVector &devices) {
3564 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003565}
3566
Jiabin Huang3b98d322020-09-03 17:54:16 +00003567status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3568 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3569 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3570 dumpAudioDeviceTypeAddrVector(devices).c_str());
3571
Mikhail Naganov55773032020-10-01 15:08:13 -07003572 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003573 return BAD_VALUE;
3574 }
3575 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3576 ALOGW_IF(status != NO_ERROR,
3577 "Engine could not set preferred devices %s for audio source %d role %d",
3578 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3579
3580 return status;
3581}
3582
3583status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3584 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3585 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3586 dumpAudioDeviceTypeAddrVector(devices).c_str());
3587
Mikhail Naganov55773032020-10-01 15:08:13 -07003588 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003589 return BAD_VALUE;
3590 }
3591 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3592 ALOGW_IF(status != NO_ERROR,
3593 "Engine could not add preferred devices %s for audio source %d role %d",
3594 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3595
Eric Laurent2517af32020-11-25 15:31:27 +01003596 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003597 return status;
3598}
3599
3600status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3601 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3602{
3603 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3604 dumpAudioDeviceTypeAddrVector(devices).c_str());
3605
Mikhail Naganov55773032020-10-01 15:08:13 -07003606 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003607 return BAD_VALUE;
3608 }
3609
3610 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3611 audioSource, role, devices);
3612 ALOGW_IF(status != NO_ERROR,
3613 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3614
Eric Laurent2517af32020-11-25 15:31:27 +01003615 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003616 return status;
3617}
3618
3619status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3620 device_role_t role) {
3621 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3622
3623 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3624 ALOGW_IF(status != NO_ERROR,
3625 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3626
Eric Laurent2517af32020-11-25 15:31:27 +01003627 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003628 return status;
3629}
3630
3631status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3632 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3633 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3634}
3635
Oscar Azucena90e77632019-11-27 17:12:28 -08003636status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003637 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003638 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003639 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3640 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003641 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003642 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3643 if (status != NO_ERROR) {
3644 ALOGE("%s() could not set device affinity for userId %d",
3645 __FUNCTION__, userId);
3646 return status;
3647 }
3648
3649 // reevaluate outputs for all devices
3650 checkForDeviceAndOutputChanges();
3651 updateCallAndOutputRouting();
3652
3653 return NO_ERROR;
3654}
3655
3656status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003657 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003658 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3659 if (status != NO_ERROR) {
3660 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3661 __FUNCTION__, userId);
3662 return status;
3663 }
3664
3665 // reevaluate outputs for all devices
3666 checkForDeviceAndOutputChanges();
3667 updateCallAndOutputRouting();
3668
3669 return NO_ERROR;
3670}
3671
Andy Hungc29d82b2018-10-05 12:23:17 -07003672void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003673{
Andy Hungc29d82b2018-10-05 12:23:17 -07003674 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003675 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003676 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003677 std::string stateLiteral;
3678 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003679 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003680 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3681 "communications", "media", "record", "dock", "system",
3682 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3683 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3684 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003685 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3686 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3687 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3688 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3689 dst->append(" (MANUAL: ");
3690 dumpManualSurroundFormats(dst);
3691 dst->append(")");
3692 }
3693 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003694 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003695 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3696 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Eric Laurent2517af32020-11-25 15:31:27 +01003697 dst->appendFormat(" Communnication Strategy: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003698 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003699
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003700 dst->append("\n");
3701 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3702 dst->append("\n");
3703 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003704 mHwModulesAll.dump(dst);
3705 mOutputs.dump(dst);
3706 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003707 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003708 mAudioPatches.dump(dst);
3709 mPolicyMixes.dump(dst);
3710 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003711
Kevin Rocardb99cc752019-03-21 20:52:24 -07003712 dst->appendFormat(" AllowedCapturePolicies:\n");
3713 for (auto& policy : mAllowedCapturePolicies) {
3714 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3715 }
3716
François Gaffiec005e562018-11-06 15:04:49 +01003717 dst->appendFormat("\nPolicy Engine dump:\n");
3718 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003719}
3720
3721status_t AudioPolicyManager::dump(int fd)
3722{
3723 String8 result;
3724 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003725 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003726 return NO_ERROR;
3727}
3728
Kevin Rocardb99cc752019-03-21 20:52:24 -07003729status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3730{
3731 mAllowedCapturePolicies[uid] = capturePolicy;
3732 return NO_ERROR;
3733}
3734
Eric Laurente552edb2014-03-10 17:42:56 -07003735// This function checks for the parameters which can be offloaded.
3736// This can be enhanced depending on the capability of the DSP and policy
3737// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003738audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003739{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003740 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003741 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003742 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003743 offloadInfo.format,
3744 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3745 offloadInfo.has_video);
3746
jiabin2b9d5a12021-12-10 01:06:29 +00003747 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003748 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003749 }
3750
3751 // See if there is a profile to support this.
3752 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003753 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003754 offloadInfo.sample_rate,
3755 offloadInfo.format,
3756 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003757 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3758 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003759 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3760 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3761 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003762 if (profile == nullptr) {
3763 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3764 }
3765 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3766 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3767 }
3768 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003769}
3770
Michael Chana94fbb22018-04-24 14:31:19 +10003771bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3772 const audio_attributes_t& attributes) {
3773 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003774 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003775 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3776 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003777 config.sample_rate,
3778 config.format,
3779 config.channel_mask,
3780 output_flags,
3781 true /* directOnly */);
3782 ALOGV("%s() profile %sfound with name: %s, "
3783 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3784 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003785 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003786 config.sample_rate, config.format, config.channel_mask, output_flags);
3787 return (profile != 0);
3788}
3789
jiabin2b9d5a12021-12-10 01:06:29 +00003790bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3791 bool durationIgnored) {
3792 if (mMasterMono) {
3793 return false; // no offloading if mono is set.
3794 }
3795
3796 // Check if offload has been disabled
3797 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3798 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3799 return false;
3800 }
3801
3802 // Check if stream type is music, then only allow offload as of now.
3803 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3804 {
3805 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3806 return false;
3807 }
3808
3809 //TODO: enable audio offloading with video when ready
3810 const bool allowOffloadWithVideo =
3811 property_get_bool("audio.offload.video", false /* default_value */);
3812 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3813 ALOGV("%s: has_video == true, returning false", __func__);
3814 return false;
3815 }
3816
3817 //If duration is less than minimum value defined in property, return false
3818 const int min_duration_secs = property_get_int32(
3819 "audio.offload.min.duration.secs", -1 /* default_value */);
3820 if (!durationIgnored) {
3821 if (min_duration_secs >= 0) {
3822 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
3823 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
3824 __func__, min_duration_secs);
3825 return false;
3826 }
3827 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
3828 ALOGV("%s: Offload denied by duration < default min(=%u)",
3829 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
3830 return false;
3831 }
3832 }
3833
3834 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
3835 // creating an offloaded track and tearing it down immediately after start when audioflinger
3836 // detects there is an active non offloadable effect.
3837 // FIXME: We should check the audio session here but we do not have it in this context.
3838 // This may prevent offloading in rare situations where effects are left active by apps
3839 // in the background.
3840 if (mEffects.isNonOffloadableEffectEnabled()) {
3841 return false;
3842 }
3843
3844 return true;
3845}
3846
3847audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
3848 const audio_config_t *config) {
3849 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
3850 offloadInfo.format = config->format;
3851 offloadInfo.sample_rate = config->sample_rate;
3852 offloadInfo.channel_mask = config->channel_mask;
3853 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
3854 offloadInfo.has_video = false;
3855 offloadInfo.is_streaming = false;
3856 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
3857
3858 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
3859 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
3860 audio_flags_to_audio_output_flags(attr->flags, &flags);
3861 // only retain flags that will drive compressed offload or passthrough
3862 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
3863 if (offloadPossible) {
3864 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
3865 }
3866 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
3867
jiabinc8f7dfc2022-01-06 18:42:08 +00003868 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00003869 for (const auto& hwModule : mHwModules) {
3870 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00003871 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00003872 config->sample_rate, nullptr /*updatedSamplingRate*/,
3873 config->format, nullptr /*updatedFormat*/,
3874 config->channel_mask, nullptr /*updatedChannelMask*/,
3875 flags)) {
3876 continue;
3877 }
3878 // reject profiles not corresponding to a device currently available
3879 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
3880 continue;
3881 }
3882 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
3883 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00003884 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00003885 != AUDIO_DIRECT_NOT_SUPPORTED) {
3886 // Already reports offload gapless supported. No need to report offload support.
3887 continue;
3888 }
3889 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
3890 != AUDIO_OUTPUT_FLAG_NONE) {
3891 // If offload gapless is reported, no need to report offload support.
3892 directMode = (audio_direct_mode_t) ((directMode &
3893 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
3894 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
3895 } else {
3896 directMode = (audio_direct_mode_t)(directMode |AUDIO_DIRECT_OFFLOAD_SUPPORTED);
3897 }
3898 } else {
3899 directMode = (audio_direct_mode_t) (directMode |
3900 AUDIO_DIRECT_BITSTREAM_SUPPORTED);
3901 }
3902 }
3903 }
3904 return directMode;
3905}
3906
Dorin Drimusf2196d82022-01-03 12:11:18 +01003907status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
3908 AudioProfileVector& audioProfilesVector) {
3909 AudioDeviceTypeAddrVector devices;
3910 status_t status = getDevicesForAttributes(*attr, &devices);
3911 if (status != OK) {
3912 return status;
3913 }
3914 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
3915 if (devices.empty()) {
3916 return OK; // no output devices for the attributes
3917 }
3918
3919 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01003920 // the MSD module checks for different conditions
3921 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
3922 continue;
3923 }
3924 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
3925 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01003926 continue;
3927 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003928 // allow only profiles that support all the available and routed devices
3929 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01003930 != devices.size()) {
3931 continue;
3932 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003933 audioProfilesVector.addAllValidProfiles(
3934 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01003935 }
3936 }
Dorin Drimus94d94412022-02-02 09:05:02 +01003937
3938 // add the direct profiles from MSD if present and has audio patches to all the output(s)
3939 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
3940 if (msdModule != nullptr) {
3941 if (msdHasPatchesToAllDevices(devices)) {
3942 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
3943 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
3944 if (!outputProfile->asAudioPort()->isDirectOutput()) {
3945 continue;
3946 }
3947 audioProfilesVector.addAllValidProfiles(
3948 outputProfile->asAudioPort()->getAudioProfiles());
3949 }
3950 } else {
3951 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
3952 }
3953 }
3954
Dorin Drimusf2196d82022-01-03 12:11:18 +01003955 return NO_ERROR;
3956}
3957
Eric Laurent6a94d692014-05-20 11:18:06 -07003958status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
3959 audio_port_type_t type,
3960 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08003961 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07003962 unsigned int *generation)
3963{
jiabin19cdba52020-11-24 11:28:58 -08003964 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
3965 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003966 return BAD_VALUE;
3967 }
3968 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08003969 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07003970 *num_ports = 0;
3971 }
3972
3973 size_t portsWritten = 0;
3974 size_t portsMax = *num_ports;
3975 *num_ports = 0;
3976 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003977 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
3978 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07003979 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003980 for (const auto& dev : mAvailableOutputDevices) {
3981 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003982 continue;
3983 }
3984 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003985 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003986 }
3987 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003988 }
Eric Laurent6a94d692014-05-20 11:18:06 -07003989 }
3990 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003991 for (const auto& dev : mAvailableInputDevices) {
3992 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07003993 continue;
3994 }
3995 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003996 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07003997 }
3998 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07003999 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004000 }
4001 }
4002 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4003 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4004 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4005 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4006 }
4007 *num_ports += mInputs.size();
4008 }
4009 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004010 size_t numOutputs = 0;
4011 for (size_t i = 0; i < mOutputs.size(); i++) {
4012 if (!mOutputs[i]->isDuplicated()) {
4013 numOutputs++;
4014 if (portsWritten < portsMax) {
4015 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4016 }
4017 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004018 }
Eric Laurent84c70242014-06-23 08:46:27 -07004019 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004020 }
4021 }
4022 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004023 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004024 return NO_ERROR;
4025}
4026
jiabin19cdba52020-11-24 11:28:58 -08004027status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004028{
Eric Laurent99fcae42018-05-17 16:59:18 -07004029 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4030 return BAD_VALUE;
4031 }
4032 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4033 if (dev != 0) {
4034 dev->toAudioPort(port);
4035 return NO_ERROR;
4036 }
4037 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4038 if (dev != 0) {
4039 dev->toAudioPort(port);
4040 return NO_ERROR;
4041 }
4042 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4043 if (out != 0) {
4044 out->toAudioPort(port);
4045 return NO_ERROR;
4046 }
4047 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4048 if (in != 0) {
4049 in->toAudioPort(port);
4050 return NO_ERROR;
4051 }
4052 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004053}
4054
François Gaffieafd4cea2019-11-18 15:50:22 +01004055status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4056 audio_patch_handle_t *handle,
4057 uid_t uid, uint32_t delayMs,
4058 const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurent6a94d692014-05-20 11:18:06 -07004059{
François Gaffieafd4cea2019-11-18 15:50:22 +01004060 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004061 if (handle == NULL || patch == NULL) {
4062 return BAD_VALUE;
4063 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004064 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004065
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004066 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004067 return BAD_VALUE;
4068 }
4069 // only one source per audio patch supported for now
4070 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004071 return INVALID_OPERATION;
4072 }
Eric Laurent874c42872014-08-08 15:13:39 -07004073
4074 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004075 return INVALID_OPERATION;
4076 }
Eric Laurent874c42872014-08-08 15:13:39 -07004077 for (size_t i = 0; i < patch->num_sinks; i++) {
4078 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4079 return INVALID_OPERATION;
4080 }
4081 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004082
4083 sp<AudioPatch> patchDesc;
4084 ssize_t index = mAudioPatches.indexOfKey(*handle);
4085
François Gaffieafd4cea2019-11-18 15:50:22 +01004086 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4087 patch->sources[0].role,
4088 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004089#if LOG_NDEBUG == 0
4090 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004091 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4092 patch->sinks[i].role,
4093 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004094 }
4095#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004096
4097 if (index >= 0) {
4098 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004099 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4100 __func__, mUidCached, patchDesc->getUid(), uid);
4101 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004102 return INVALID_OPERATION;
4103 }
4104 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004105 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004106 }
4107
4108 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004109 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004110 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004111 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004112 return BAD_VALUE;
4113 }
Eric Laurent84c70242014-06-23 08:46:27 -07004114 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4115 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004116 if (patchDesc != 0) {
4117 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004118 ALOGV("%s source id differs for patch current id %d new id %d",
4119 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004120 return BAD_VALUE;
4121 }
4122 }
Eric Laurent874c42872014-08-08 15:13:39 -07004123 DeviceVector devices;
4124 for (size_t i = 0; i < patch->num_sinks; i++) {
4125 // Only support mix to devices connection
4126 // TODO add support for mix to mix connection
4127 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004128 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004129 return INVALID_OPERATION;
4130 }
4131 sp<DeviceDescriptor> devDesc =
4132 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4133 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004134 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004135 return BAD_VALUE;
4136 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004137
François Gaffie11d30102018-11-02 16:09:09 +01004138 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004139 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004140 NULL, // updatedSamplingRate
4141 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004142 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004143 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004144 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004145 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004146 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004147 return INVALID_OPERATION;
4148 }
4149 devices.add(devDesc);
4150 }
4151 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004152 return INVALID_OPERATION;
4153 }
Eric Laurent874c42872014-08-08 15:13:39 -07004154
Eric Laurent6a94d692014-05-20 11:18:06 -07004155 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004156 ALOGV("%s setting device %s on output %d",
4157 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004158 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004159 index = mAudioPatches.indexOfKey(*handle);
4160 if (index >= 0) {
4161 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004162 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004163 }
4164 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004165 patchDesc->setUid(uid);
4166 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004167 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004168 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004169 return INVALID_OPERATION;
4170 }
4171 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4172 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4173 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004174 // only one sink supported when connecting an input device to a mix
4175 if (patch->num_sinks > 1) {
4176 return INVALID_OPERATION;
4177 }
François Gaffie53615e22015-03-19 09:24:12 +01004178 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004179 if (inputDesc == NULL) {
4180 return BAD_VALUE;
4181 }
4182 if (patchDesc != 0) {
4183 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4184 return BAD_VALUE;
4185 }
4186 }
François Gaffie11d30102018-11-02 16:09:09 +01004187 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004188 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004189 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004190 return BAD_VALUE;
4191 }
4192
François Gaffie11d30102018-11-02 16:09:09 +01004193 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004194 patch->sinks[0].sample_rate,
4195 NULL, /*updatedSampleRate*/
4196 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004197 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004198 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004199 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004200 // FIXME for the parameter type,
4201 // and the NONE
4202 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004203 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004204 return INVALID_OPERATION;
4205 }
4206 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004207 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004208 device->toString().c_str(), inputDesc->mIoHandle);
4209 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004210 index = mAudioPatches.indexOfKey(*handle);
4211 if (index >= 0) {
4212 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004213 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004214 }
4215 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004216 patchDesc->setUid(uid);
4217 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004218 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004219 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004220 return INVALID_OPERATION;
4221 }
4222 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4223 // device to device connection
4224 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004225 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004226 return BAD_VALUE;
4227 }
4228 }
François Gaffie11d30102018-11-02 16:09:09 +01004229 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004230 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004231 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004232 return BAD_VALUE;
4233 }
Eric Laurent874c42872014-08-08 15:13:39 -07004234
Eric Laurent6a94d692014-05-20 11:18:06 -07004235 //update source and sink with our own data as the data passed in the patch may
4236 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004237 PatchBuilder patchBuilder;
4238 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004239
4240 // if first sink is to MSD, establish single MSD patch
4241 if (getMsdAudioOutDevices().contains(
4242 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4243 ALOGV("%s patching to MSD", __FUNCTION__);
4244 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4245 goto installPatch;
4246 }
4247
François Gaffieafd4cea2019-11-18 15:50:22 +01004248 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4249 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004250
Eric Laurent874c42872014-08-08 15:13:39 -07004251 for (size_t i = 0; i < patch->num_sinks; i++) {
4252 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004253 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004254 return INVALID_OPERATION;
4255 }
François Gaffie11d30102018-11-02 16:09:09 +01004256 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004257 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004258 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004259 return BAD_VALUE;
4260 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004261 audio_port_config sinkPortConfig = {};
4262 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4263 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004264
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004265 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4266 // volume management purpose (tracking activity)
4267 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4268 // in config XML to reach the sink so that is can be declared as available.
4269 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4270 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4271 if (sourceDesc != nullptr) {
4272 // take care of dynamic routing for SwOutput selection,
4273 audio_attributes_t attributes = sourceDesc->attributes();
4274 audio_stream_type_t stream = sourceDesc->stream();
4275 audio_attributes_t resultAttr;
4276 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4277 config.sample_rate = sourceDesc->config().sample_rate;
4278 config.channel_mask = sourceDesc->config().channel_mask;
4279 config.format = sourceDesc->config().format;
4280 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4281 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4282 bool isRequestedDeviceForExclusiveUse = false;
4283 output_type_t outputType;
4284 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4285 &stream, sourceDesc->uid(), &config, &flags,
4286 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
4287 nullptr, &outputType);
4288 if (output == AUDIO_IO_HANDLE_NONE) {
4289 ALOGV("%s no output for device %s",
4290 __FUNCTION__, sinkDevice->toString().c_str());
4291 return INVALID_OPERATION;
4292 }
4293 outputDesc = mOutputs.valueFor(output);
4294 if (outputDesc->isDuplicated()) {
4295 ALOGE("%s output is duplicated", __func__);
4296 return INVALID_OPERATION;
4297 }
4298 sourceDesc->setSwOutput(outputDesc);
4299 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004300 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004301 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004302 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004303 // - audio HAL version is >= 3.0 but no route has been declared between devices
François Gaffieafd4cea2019-11-18 15:50:22 +01004304 // - called from startAudioSource (aka sourceDesc != nullptr) and source device does
4305 // not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004306 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4307 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004308 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
4309 (sourceDesc != nullptr &&
4310 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004311 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004312 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004313 return INVALID_OPERATION;
4314 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004315 if (sourceDesc == nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004316 SortedVector<audio_io_handle_t> outputs =
4317 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4318 // if the sink device is reachable via an opened output stream, request to
4319 // go via this output stream by adding a second source to the patch
4320 // description
4321 output = selectOutput(outputs);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004322 if (output != AUDIO_IO_HANDLE_NONE) {
4323 outputDesc = mOutputs.valueFor(output);
4324 if (outputDesc->isDuplicated()) {
4325 ALOGV("%s output for device %s is duplicated",
4326 __FUNCTION__, sinkDevice->toString().c_str());
4327 return INVALID_OPERATION;
4328 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004329 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004330 }
4331 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004332 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004333 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004334 // for volume control, we may need a valid stream
4335 srcMixPortConfig.ext.mix.usecase.stream = sourceDesc != nullptr ?
4336 sourceDesc->stream() : AUDIO_STREAM_PATCH;
4337 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004338 }
Eric Laurent83b88082014-06-20 18:31:16 -07004339 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004340 }
4341 // TODO: check from routing capabilities in config file and other conflicting patches
4342
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004343installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004344 status_t status = installPatch(
4345 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004346 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004347 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004348 return INVALID_OPERATION;
4349 }
4350 } else {
4351 return BAD_VALUE;
4352 }
4353 } else {
4354 return BAD_VALUE;
4355 }
4356 return NO_ERROR;
4357}
4358
4359status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle,
4360 uid_t uid)
4361{
4362 ALOGV("releaseAudioPatch() patch %d", handle);
4363
4364 ssize_t index = mAudioPatches.indexOfKey(handle);
4365
4366 if (index < 0) {
4367 return BAD_VALUE;
4368 }
4369 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004370 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4371 __func__, mUidCached, patchDesc->getUid(), uid);
4372 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004373 return INVALID_OPERATION;
4374 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004375 return releaseAudioPatchInternal(handle);
4376}
Eric Laurent6a94d692014-05-20 11:18:06 -07004377
François Gaffieafd4cea2019-11-18 15:50:22 +01004378status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
4379 uint32_t delayMs)
4380{
4381 ALOGV("%s patch %d", __func__, handle);
4382 if (mAudioPatches.indexOfKey(handle) < 0) {
4383 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4384 return BAD_VALUE;
4385 }
4386 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004387 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004388 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004389 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004390 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004391 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004392 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004393 return BAD_VALUE;
4394 }
4395
François Gaffie11d30102018-11-02 16:09:09 +01004396 setOutputDevices(outputDesc,
4397 getNewOutputDevices(outputDesc, true /*fromCache*/),
4398 true,
4399 0,
4400 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004401 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4402 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004403 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004404 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004405 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004406 return BAD_VALUE;
4407 }
4408 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004409 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004410 true,
4411 NULL);
4412 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004413 status_t status =
4414 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4415 ALOGV("%s patch panel returned %d patchHandle %d",
4416 __func__, status, patchDesc->getAfHandle());
4417 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004418 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004419 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffie7feb8542020-04-06 17:39:47 +02004420 // SW Bridge
4421 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
4422 sp<SwAudioOutputDescriptor> outputDesc =
4423 mOutputs.getOutputFromId(patch->sources[1].id);
4424 if (outputDesc == NULL) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02004425 ALOGW("%s output not found for id %d", __func__, patch->sources[0].id);
4426 // releaseOutput has already called closeOuput in case of direct output
4427 return NO_ERROR;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004428 }
Francois Gaffie8e544542020-05-11 14:12:53 +02004429 if (patchDesc->getHandle() != outputDesc->getPatchHandle()) {
4430 // force SwOutput patch removal as AF counter part patch has already gone.
4431 ALOGV("%s reset patch handle on Output as different from SWBridge", __func__);
4432 removeAudioPatch(outputDesc->getPatchHandle());
4433 }
Francois Gaffie7feb8542020-04-06 17:39:47 +02004434 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
4435 setOutputDevices(outputDesc,
4436 getNewOutputDevices(outputDesc, true /*fromCache*/),
4437 true, /*force*/
4438 0,
4439 NULL);
4440 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004441 } else {
4442 return BAD_VALUE;
4443 }
4444 } else {
4445 return BAD_VALUE;
4446 }
4447 return NO_ERROR;
4448}
4449
4450status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4451 struct audio_patch *patches,
4452 unsigned int *generation)
4453{
François Gaffie53615e22015-03-19 09:24:12 +01004454 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004455 return BAD_VALUE;
4456 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004457 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004458 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004459}
4460
Eric Laurente1715a42014-05-20 11:30:42 -07004461status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004462{
Eric Laurente1715a42014-05-20 11:30:42 -07004463 ALOGV("setAudioPortConfig()");
4464
4465 if (config == NULL) {
4466 return BAD_VALUE;
4467 }
4468 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4469 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004470 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4471 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004472 }
4473
Eric Laurenta121f902014-06-03 13:32:54 -07004474 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004475 if (config->type == AUDIO_PORT_TYPE_MIX) {
4476 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004477 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004478 if (outputDesc == NULL) {
4479 return BAD_VALUE;
4480 }
Eric Laurent84c70242014-06-23 08:46:27 -07004481 ALOG_ASSERT(!outputDesc->isDuplicated(),
4482 "setAudioPortConfig() called on duplicated output %d",
4483 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004484 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004485 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004486 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004487 if (inputDesc == NULL) {
4488 return BAD_VALUE;
4489 }
Eric Laurenta121f902014-06-03 13:32:54 -07004490 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004491 } else {
4492 return BAD_VALUE;
4493 }
4494 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4495 sp<DeviceDescriptor> deviceDesc;
4496 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4497 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4498 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4499 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4500 } else {
4501 return BAD_VALUE;
4502 }
4503 if (deviceDesc == NULL) {
4504 return BAD_VALUE;
4505 }
Eric Laurenta121f902014-06-03 13:32:54 -07004506 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004507 } else {
4508 return BAD_VALUE;
4509 }
4510
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004511 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004512 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4513 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004514 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004515 audioPortConfig->toAudioPortConfig(&newConfig, config);
4516 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004517 }
Eric Laurenta121f902014-06-03 13:32:54 -07004518 if (status != NO_ERROR) {
4519 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004520 }
Eric Laurente1715a42014-05-20 11:30:42 -07004521
4522 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004523}
4524
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004525void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4526{
Eric Laurentd60560a2015-04-10 11:31:20 -07004527 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004528 clearAudioPatches(uid);
4529 clearSessionRoutes(uid);
4530}
4531
Eric Laurent6a94d692014-05-20 11:18:06 -07004532void AudioPolicyManager::clearAudioPatches(uid_t uid)
4533{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004534 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004535 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004536 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004537 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004538 }
4539 }
4540}
4541
François Gaffiec005e562018-11-06 15:04:49 +01004542void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004543{
François Gaffiec005e562018-11-06 15:04:49 +01004544 // Take the first attributes following the product strategy as it is used to retrieve the routed
4545 // device. All attributes wihin a strategy follows the same "routing strategy"
4546 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4547 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004548 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004549 for (size_t j = 0; j < mOutputs.size(); j++) {
4550 if (mOutputs.keyAt(j) == ouptutToSkip) {
4551 continue;
4552 }
4553 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004554 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004555 continue;
4556 }
4557 // If the default device for this strategy is on another output mix,
4558 // invalidate all tracks in this strategy to force re connection.
4559 // Otherwise select new device on the output mix.
4560 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004561 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4562 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004563 }
4564 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004565 setOutputDevices(
4566 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004567 }
4568 }
4569}
4570
4571void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4572{
4573 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004574 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004575 for (size_t i = 0; i < mOutputs.size(); i++) {
4576 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004577 for (const auto& client : outputDesc->getClientIterable()) {
4578 if (client->hasPreferredDevice() && client->uid() == uid) {
4579 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004580 auto clientStrategy = client->strategy();
4581 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4582 end(affectedStrategies)) {
4583 continue;
4584 }
4585 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004586 }
4587 }
4588 }
4589 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004590 for (const auto& strategy : affectedStrategies) {
4591 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004592 }
4593
4594 // remove input routes associated with this uid
4595 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004596 for (size_t i = 0; i < mInputs.size(); i++) {
4597 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004598 for (const auto& client : inputDesc->getClientIterable()) {
4599 if (client->hasPreferredDevice() && client->uid() == uid) {
4600 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4601 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004602 }
4603 }
4604 }
4605 // reroute inputs if necessary
4606 SortedVector<audio_io_handle_t> inputsToClose;
4607 for (size_t i = 0; i < mInputs.size(); i++) {
4608 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004609 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004610 inputsToClose.add(inputDesc->mIoHandle);
4611 }
4612 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004613 for (const auto& input : inputsToClose) {
4614 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004615 }
4616}
4617
Eric Laurentd60560a2015-04-10 11:31:20 -07004618void AudioPolicyManager::clearAudioSources(uid_t uid)
4619{
4620 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004621 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4622 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004623 stopAudioSource(mAudioSources.keyAt(i));
4624 }
4625 }
4626}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004627
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004628status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4629 audio_io_handle_t *ioHandle,
4630 audio_devices_t *device)
4631{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004632 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4633 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004634 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004635 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004636
François Gaffiedf372692015-03-19 10:43:27 +01004637 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004638}
4639
Eric Laurentd60560a2015-04-10 11:31:20 -07004640status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004641 const audio_attributes_t *attributes,
4642 audio_port_handle_t *portId,
4643 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004644{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004645 ALOGV("%s", __FUNCTION__);
4646 *portId = AUDIO_PORT_HANDLE_NONE;
4647
4648 if (source == NULL || attributes == NULL || portId == NULL) {
4649 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4650 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004651 return BAD_VALUE;
4652 }
4653
Eric Laurentd60560a2015-04-10 11:31:20 -07004654 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4655 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004656 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4657 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004658 return INVALID_OPERATION;
4659 }
4660
François Gaffie11d30102018-11-02 16:09:09 +01004661 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004662 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004663 String8(source->ext.device.address),
4664 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004665 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004666 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004667 return BAD_VALUE;
4668 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004669
jiabin4ef93452019-09-10 14:29:54 -07004670 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004671
François Gaffieaaac0fd2018-11-22 17:56:39 +01004672 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004673 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004674 mEngine->getStreamTypeForAttributes(*attributes),
4675 mEngine->getProductStrategyForAttributes(*attributes),
4676 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004677
4678 status_t status = connectAudioSource(sourceDesc);
4679 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004680 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004681 }
4682 return status;
4683}
4684
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004685status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004686{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004687 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004688
4689 // make sure we only have one patch per source.
4690 disconnectAudioSource(sourceDesc);
4691
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004692 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004693 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4694 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4695 sourceDesc->srcDevice()->type(),
4696 String8(sourceDesc->srcDevice()->address().c_str()),
4697 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004698 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004699 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004700 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004701 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004702 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4703 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4704 return INVALID_OPERATION;
4705 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004706 PatchBuilder patchBuilder;
4707 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4708 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
4709 status_t status =
4710 createAudioPatchInternal(patchBuilder.patch(), &handle, mUidCached, 0, sourceDesc);
4711 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4712 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4713 return INVALID_OPERATION;
4714 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004715 sourceDesc->connect(handle, sinkDevice);
François Gaffieafd4cea2019-11-18 15:50:22 +01004716 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4717 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4718 if (swOutput != 0) {
4719 status = swOutput->start();
Eric Laurent733ce942017-12-07 12:18:25 -08004720 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004721 goto FailureSourceAdded;
Eric Laurent733ce942017-12-07 12:18:25 -08004722 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004723 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004724 ALOGW("%s source portId has already been attached to outputDesc", __func__);
François Gaffieafd4cea2019-11-18 15:50:22 +01004725 goto FailureReleasePatch;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07004726 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004727 swOutput->addClient(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004728 uint32_t delayMs = 0;
François Gaffieafd4cea2019-11-18 15:50:22 +01004729 status = startSource(swOutput, sourceDesc, &delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07004730 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004731 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4732 goto FailureSourceActive;
Eric Laurentd60560a2015-04-10 11:31:20 -07004733 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004734 if (delayMs != 0) {
4735 usleep(delayMs * 1000);
4736 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004737 } else {
4738 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
4739 if (hwOutputDesc != 0) {
4740 // create Hwoutput and add to mHwOutputs
4741 } else {
4742 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
4743 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004744 }
Eric Laurentd60560a2015-04-10 11:31:20 -07004745 return NO_ERROR;
François Gaffieafd4cea2019-11-18 15:50:22 +01004746
4747FailureSourceActive:
4748 swOutput->stop();
4749 releaseOutput(sourceDesc->portId());
4750FailureSourceAdded:
4751 sourceDesc->setSwOutput(nullptr);
4752FailureReleasePatch:
4753 releaseAudioPatchInternal(handle);
4754 return INVALID_OPERATION;
Eric Laurent554a2772015-04-10 11:29:24 -07004755}
4756
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004757status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07004758{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004759 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
4760 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004761 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004762 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004763 return BAD_VALUE;
4764 }
4765 status_t status = disconnectAudioSource(sourceDesc);
4766
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004767 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004768 return status;
4769}
4770
Andy Hung2ddee192015-12-18 17:34:44 -08004771status_t AudioPolicyManager::setMasterMono(bool mono)
4772{
4773 if (mMasterMono == mono) {
4774 return NO_ERROR;
4775 }
4776 mMasterMono = mono;
4777 // if enabling mono we close all offloaded devices, which will invalidate the
4778 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
4779 // for recreating the new AudioTrack as non-offloaded PCM.
4780 //
4781 // If disabling mono, we leave all tracks as is: we don't know which clients
4782 // and tracks are able to be recreated as offloaded. The next "song" should
4783 // play back offloaded.
4784 if (mMasterMono) {
4785 Vector<audio_io_handle_t> offloaded;
4786 for (size_t i = 0; i < mOutputs.size(); ++i) {
4787 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
4788 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
4789 offloaded.push(desc->mIoHandle);
4790 }
4791 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004792 for (const auto& handle : offloaded) {
4793 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08004794 }
4795 }
4796 // update master mono for all remaining outputs
4797 for (size_t i = 0; i < mOutputs.size(); ++i) {
4798 updateMono(mOutputs.keyAt(i));
4799 }
4800 return NO_ERROR;
4801}
4802
4803status_t AudioPolicyManager::getMasterMono(bool *mono)
4804{
4805 *mono = mMasterMono;
4806 return NO_ERROR;
4807}
4808
Eric Laurentac9cef52017-06-09 15:46:26 -07004809float AudioPolicyManager::getStreamVolumeDB(
4810 audio_stream_type_t stream, int index, audio_devices_t device)
4811{
jiabin9a3361e2019-10-01 09:38:30 -07004812 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07004813}
4814
jiabin81772902018-04-02 17:52:27 -07004815status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
4816 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01004817 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07004818{
Kriti Dang6537def2021-03-02 13:46:59 +01004819 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
4820 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07004821 return BAD_VALUE;
4822 }
Kriti Dang6537def2021-03-02 13:46:59 +01004823 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
4824 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07004825
4826 size_t formatsWritten = 0;
4827 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01004828
Kriti Dang6537def2021-03-02 13:46:59 +01004829 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08004830 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
4831 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01004832 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07004833 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01004834 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004835 bool formatEnabled = true;
4836 switch (forceUse) {
4837 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01004838 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08004839 break;
4840 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
4841 formatEnabled = false;
4842 break;
4843 default: // AUTO or ALWAYS => true
4844 break;
jiabin81772902018-04-02 17:52:27 -07004845 }
4846 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
4847 }
jiabin81772902018-04-02 17:52:27 -07004848 }
4849 return NO_ERROR;
4850}
4851
Kriti Dang6537def2021-03-02 13:46:59 +01004852status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
4853 audio_format_t *surroundFormats) {
4854 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
4855 return BAD_VALUE;
4856 }
4857 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
4858 __func__, *numSurroundFormats, surroundFormats);
4859
4860 size_t formatsWritten = 0;
4861 size_t formatsMax = *numSurroundFormats;
4862 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
4863
4864 // Return formats from all device profiles that have already been resolved by
4865 // checkOutputsForDevice().
4866 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
4867 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
4868 audio_devices_t deviceType = device->type();
4869 // Enabling/disabling formats are applied to only HDMI devices. So, this function
4870 // returns formats reported by HDMI devices.
4871 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
4872 continue;
4873 }
4874 // Formats reported by sink devices
4875 std::unordered_set<audio_format_t> formatset;
4876 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
4877 formatset.insert(it->second.begin(), it->second.end());
4878 }
4879
4880 // Formats hard-coded in the in policy configuration file (if any).
4881 FormatVector encodedFormats = device->encodedFormats();
4882 formatset.insert(encodedFormats.begin(), encodedFormats.end());
4883 // Filter the formats which are supported by the vendor hardware.
4884 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
4885 if (mConfig.getSurroundFormats().count(*it) != 0) {
4886 formats.insert(*it);
4887 } else {
4888 for (const auto& pair : mConfig.getSurroundFormats()) {
4889 if (pair.second.count(*it) != 0) {
4890 formats.insert(pair.first);
4891 break;
4892 }
4893 }
4894 }
4895 }
4896 }
4897 *numSurroundFormats = formats.size();
4898 for (const auto& format: formats) {
4899 if (formatsWritten < formatsMax) {
4900 surroundFormats[formatsWritten++] = format;
4901 }
4902 }
4903 return NO_ERROR;
4904}
4905
jiabin81772902018-04-02 17:52:27 -07004906status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
4907{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004908 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004909 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
4910 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004911 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07004912 return BAD_VALUE;
4913 }
4914
Mikhail Naganov100f0122018-11-29 11:22:16 -08004915 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
4916 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004917 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07004918 return INVALID_OPERATION;
4919 }
4920
Mikhail Naganov100f0122018-11-29 11:22:16 -08004921 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07004922 return NO_ERROR;
4923 }
4924
Mikhail Naganov100f0122018-11-29 11:22:16 -08004925 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07004926 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004927 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004928 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004929 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07004930 }
4931 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004932 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07004933 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004934 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07004935 }
4936 }
4937
4938 sp<SwAudioOutputDescriptor> outputDesc;
4939 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07004940 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
4941 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07004942 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
4943 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004944 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004945 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004946 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4947 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4948 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004949 name.c_str(),
4950 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004951 if (status != NO_ERROR) {
4952 continue;
4953 }
4954 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
4955 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4956 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004957 name.c_str(),
4958 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004959 profileUpdated |= (status == NO_ERROR);
4960 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08004961 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07004962 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07004963 AUDIO_DEVICE_IN_HDMI);
4964 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
4965 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07004966 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07004967 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07004968 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4969 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4970 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004971 name.c_str(),
4972 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004973 if (status != NO_ERROR) {
4974 continue;
4975 }
4976 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
4977 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
4978 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004979 name.c_str(),
4980 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07004981 profileUpdated |= (status == NO_ERROR);
4982 }
4983
jiabin81772902018-04-02 17:52:27 -07004984 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07004985 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08004986 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07004987 }
4988
4989 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
4990}
4991
Eric Laurent5ada82e2019-08-29 17:53:54 -07004992void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004993{
Eric Laurent5ada82e2019-08-29 17:53:54 -07004994 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08004995 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07004996 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08004997 }
4998}
4999
jiabin6012f912018-11-02 17:06:30 -07005000bool AudioPolicyManager::isHapticPlaybackSupported()
5001{
5002 for (const auto& hwModule : mHwModules) {
5003 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5004 for (const auto &outProfile : outputProfiles) {
5005 struct audio_port audioPort;
5006 outProfile->toAudioPort(&audioPort);
5007 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5008 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5009 return true;
5010 }
5011 }
5012 }
5013 }
5014 return false;
5015}
5016
Carter Hsu325a8eb2022-01-19 19:56:51 +08005017bool AudioPolicyManager::isUltrasoundSupported()
5018{
5019 bool hasUltrasoundOutput = false;
5020 bool hasUltrasoundInput = false;
5021 for (const auto& hwModule : mHwModules) {
5022 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5023 if (!hasUltrasoundOutput) {
5024 for (const auto &outProfile : outputProfiles) {
5025 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5026 hasUltrasoundOutput = true;
5027 break;
5028 }
5029 }
5030 }
5031
5032 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5033 if (!hasUltrasoundInput) {
5034 for (const auto &inputProfile : inputProfiles) {
5035 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5036 hasUltrasoundInput = true;
5037 break;
5038 }
5039 }
5040 }
5041
5042 if (hasUltrasoundOutput && hasUltrasoundInput)
5043 return true;
5044 }
5045 return false;
5046}
5047
Eric Laurent8340e672019-11-06 11:01:08 -08005048bool AudioPolicyManager::isCallScreenModeSupported()
5049{
5050 return getConfig().isCallScreenModeSupported();
5051}
5052
5053
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005054status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005055{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005056 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005057 if (!sourceDesc->isConnected()) {
5058 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5059 return NO_ERROR;
5060 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005061 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5062 if (swOutput != 0) {
5063 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005064 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005065 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005066 }
jiabinbce0c1d2020-10-05 11:20:18 -07005067 if (releaseOutput(sourceDesc->portId())) {
5068 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5069 // no need to release audio patch here but just return NO_ERROR.
5070 return NO_ERROR;
5071 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005072 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005073 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005074 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005075 // close Hwoutput and remove from mHwOutputs
5076 } else {
5077 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5078 }
5079 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005080 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle());
5081 sourceDesc->disconnect();
5082 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005083}
5084
François Gaffiec005e562018-11-06 15:04:49 +01005085sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5086 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005087{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005088 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005089 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005090 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005091 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005092 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5093 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005094 source = sourceDesc;
5095 break;
5096 }
5097 }
5098 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005099}
5100
Eric Laurent39095982021-08-24 18:29:27 +02005101/* static */
5102bool AudioPolicyManager::isChannelMaskSpatialized(audio_channel_mask_t channels) {
5103 switch (channels) {
5104 case AUDIO_CHANNEL_OUT_5POINT1:
5105 case AUDIO_CHANNEL_OUT_5POINT1POINT2:
5106 case AUDIO_CHANNEL_OUT_5POINT1POINT4:
5107 case AUDIO_CHANNEL_OUT_7POINT1:
5108 case AUDIO_CHANNEL_OUT_7POINT1POINT2:
5109 case AUDIO_CHANNEL_OUT_7POINT1POINT4:
5110 return true;
5111 default:
5112 return false;
5113 }
5114}
5115
Eric Laurentb4f42a92022-01-17 17:37:31 +01005116bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005117 const audio_config_t *config,
Eric Laurentb4f42a92022-01-17 17:37:31 +01005118 const AudioDeviceTypeAddrVector &devices,
5119 bool allowCurrentOutputReconfig) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005120{
5121 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5122 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005123 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005124 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005125 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5126 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5127 return false;
5128 }
5129 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5130 return false;
5131 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005132 }
5133
5134 // The caller can have the devices criteria ignored by passing and empty vector, and
Eric Laurentfa0f6742021-08-17 18:39:44 +02005135 // getSpatializerOutputProfile() will ignore the devices when looking for a match.
5136 // Otherwise an output profile supporting a spatializer effect that can be routed
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005137 // to the specified devices must exist.
5138 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005139 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005140 if (profile == nullptr) {
5141 return false;
5142 }
5143
5144 // The caller can have the audio config criteria ignored by either passing a null ptr or
5145 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005146 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005147 // some positional channel masks.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005148 // If the spatializer output is already opened, only channel masks included in the
5149 // spatializer output mixer channel mask are allowed.
Eric Laurent39095982021-08-24 18:29:27 +02005150
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005151 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Eric Laurent39095982021-08-24 18:29:27 +02005152 if (!isChannelMaskSpatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005153 return false;
5154 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005155 if (!allowCurrentOutputReconfig && mSpatializerOutput != nullptr
5156 && mSpatializerOutput->mProfile == profile) {
Eric Laurentfa0f6742021-08-17 18:39:44 +02005157 if ((config->channel_mask & mSpatializerOutput->mMixerChannelMask)
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005158 != config->channel_mask) {
5159 return false;
5160 }
5161 }
5162 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005163 return true;
5164}
5165
5166void AudioPolicyManager::checkVirtualizerClientRoutes() {
5167 std::set<audio_stream_type_t> streamsToInvalidate;
5168 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005169 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5170 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005171 audio_attributes_t attr = client->attributes();
5172 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5173 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5174 audio_config_base_t clientConfig = client->config();
5175 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005176 if (desc != mSpatializerOutput
Eric Laurentb4f42a92022-01-17 17:37:31 +01005177 && canBeSpatializedInt(&attr, &config,
5178 devicesTypeAddress, false /* allowCurrentOutputReconfig */)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005179 streamsToInvalidate.insert(client->stream());
5180 }
5181 }
5182 }
5183
5184 for (audio_stream_type_t stream : streamsToInvalidate) {
5185 mpClientInterface->invalidateStream(stream);
5186 }
5187}
5188
Eric Laurentfa0f6742021-08-17 18:39:44 +02005189status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005190 const audio_attributes_t *attr,
5191 audio_io_handle_t *output) {
5192 *output = AUDIO_IO_HANDLE_NONE;
5193
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005194 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5195 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5196 audio_config_t *configPtr = nullptr;
5197 audio_config_t config;
5198 if (mixerConfig != nullptr) {
5199 config = audio_config_initializer(mixerConfig);
5200 configPtr = &config;
5201 }
Eric Laurentb4f42a92022-01-17 17:37:31 +01005202 if (!canBeSpatializedInt(
5203 attr, configPtr, devicesTypeAddress)) {
Eric Laurent39095982021-08-24 18:29:27 +02005204 ALOGW("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005205 return BAD_VALUE;
5206 }
5207
5208 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005209 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005210 if (profile == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005211 ALOGW("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005212 return BAD_VALUE;
5213 }
5214
Eric Laurent39095982021-08-24 18:29:27 +02005215 if (mSpatializerOutput != nullptr && mSpatializerOutput->mProfile == profile
5216 && configPtr != nullptr
5217 && configPtr->channel_mask == mSpatializerOutput->mMixerChannelMask) {
5218 *output = mSpatializerOutput->mIoHandle;
5219 ALOGV("%s returns current spatializer output %d", __func__, *output);
5220 return NO_ERROR;
5221 }
5222 mSpatializerOutput.clear();
5223 for (size_t i = 0; i < mOutputs.size(); i++) {
5224 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5225 if (!desc->isDuplicated() && desc->mProfile == profile) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005226 ALOGV("%s found output %d for spatializer profile", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005227 mSpatializerOutput = desc;
5228 break;
5229 }
5230 }
5231 if (mSpatializerOutput == nullptr) {
5232 ALOGW("%s no opened spatializer output for profile %s",
5233 __func__, profile->getName().c_str());
5234 return BAD_VALUE;
5235 }
5236
5237 if (configPtr != nullptr
5238 && configPtr->channel_mask != mSpatializerOutput->mMixerChannelMask) {
5239 audio_config_base_t savedMixerConfig = {
5240 .sample_rate = mSpatializerOutput->getSamplingRate(),
5241 .format = mSpatializerOutput->getFormat(),
5242 .channel_mask = mSpatializerOutput->mMixerChannelMask,
5243 };
5244 DeviceVector savedDevices = mSpatializerOutput->devices();
5245
Eric Laurentb4f42a92022-01-17 17:37:31 +01005246 ALOGV("%s reopening spatializer output to match channel mask %#x (current mask %#x)",
5247 __func__, configPtr->channel_mask, mSpatializerOutput->mMixerChannelMask);
Eric Laurent39095982021-08-24 18:29:27 +02005248
Eric Laurentb4f42a92022-01-17 17:37:31 +01005249 closeOutput(mSpatializerOutput->mIoHandle);
5250 //from now on mSpatializerOutput is null
5251
5252 sp<SwAudioOutputDescriptor> desc =
5253 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
5254 if (desc == nullptr) {
Eric Laurent39095982021-08-24 18:29:27 +02005255 // re open the spatializer output with previous channel mask
Eric Laurentb4f42a92022-01-17 17:37:31 +01005256 desc = openOutputWithProfileAndDevice(profile, savedDevices, &savedMixerConfig);
5257 if (desc == nullptr) {
5258 ALOGE("%s failed to restore mSpatializerOutput with previous config", __func__);
Eric Laurent39095982021-08-24 18:29:27 +02005259 } else {
5260 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005261 }
5262 mPreviousOutputs = mOutputs;
5263 mpClientInterface->onAudioPortListUpdate();
5264 *output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005265 ALOGW("%s could not open spatializer output with requested config", __func__);
5266 return BAD_VALUE;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005267 }
Eric Laurent39095982021-08-24 18:29:27 +02005268 mSpatializerOutput = desc;
Eric Laurent39095982021-08-24 18:29:27 +02005269 mPreviousOutputs = mOutputs;
5270 mpClientInterface->onAudioPortListUpdate();
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005271 }
5272
5273 checkVirtualizerClientRoutes();
5274
Eric Laurent39095982021-08-24 18:29:27 +02005275 *output = mSpatializerOutput->mIoHandle;
Eric Laurentfa0f6742021-08-17 18:39:44 +02005276 ALOGV("%s returns new spatializer output %d", __func__, *output);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005277 return NO_ERROR;
5278}
5279
Eric Laurentfa0f6742021-08-17 18:39:44 +02005280status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5281 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005282 return INVALID_OPERATION;
5283 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005284 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005285 return BAD_VALUE;
5286 }
Eric Laurent39095982021-08-24 18:29:27 +02005287
Eric Laurentfa0f6742021-08-17 18:39:44 +02005288 mSpatializerOutput.clear();
Eric Laurent39095982021-08-24 18:29:27 +02005289
5290 checkVirtualizerClientRoutes();
5291
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005292 return NO_ERROR;
5293}
5294
Eric Laurente552edb2014-03-10 17:42:56 -07005295// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005296// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005297// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005298uint32_t AudioPolicyManager::nextAudioPortGeneration()
5299{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005300 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005301}
5302
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005303static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005304 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5305 !audioPolicyXmlConfigFile.empty()) {
5306 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5307 if (ret == NO_ERROR) {
5308 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005309 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005310 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005311 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005312 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005313}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005314
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005315AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5316 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005317 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005318 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005319 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005320 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005321 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005322 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005323 mAudioPortGeneration(1),
5324 mBeaconMuteRefCount(0),
5325 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005326 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005327 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005328 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005329 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005330{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005331}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005332
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005333AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5334 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5335{
5336 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005337}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005338
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005339void AudioPolicyManager::loadConfig() {
5340 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005341 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005342 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005343 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005344}
5345
5346status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005347 {
5348 auto engLib = EngineLibrary::load(
5349 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5350 if (!engLib) {
5351 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5352 return NO_INIT;
5353 }
5354 mEngine = engLib->createEngine();
5355 if (mEngine == nullptr) {
5356 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5357 return NO_INIT;
5358 }
François Gaffie2110e042015-03-24 08:41:51 +01005359 }
5360 mEngine->setObserver(this);
5361 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005362 if (status != NO_ERROR) {
5363 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5364 return status;
5365 }
François Gaffie2110e042015-03-24 08:41:51 +01005366
Eric Laurent1d69c872021-01-11 18:53:01 +01005367 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5368 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5369
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005370 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005371 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005372 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005373
Eric Laurent3a4311c2014-03-17 12:00:47 -07005374 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005375 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5376 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5377 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005378 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005379 }
jiabin9ff780e2018-03-19 18:19:52 -07005380 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005381 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005382 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005383 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005384 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005385 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005386 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005387 }
5388 }
5389 }
Eric Laurente552edb2014-03-10 17:42:56 -07005390
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005391 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005392
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005393 // Silence ALOGV statements
5394 property_set("log.tag." LOG_TAG, "D");
5395
Eric Laurente552edb2014-03-10 17:42:56 -07005396 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005397 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005398}
5399
Eric Laurente0720872014-03-11 09:30:41 -07005400AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005401{
Eric Laurente552edb2014-03-10 17:42:56 -07005402 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005403 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005404 }
5405 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005406 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005407 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005408 mAvailableOutputDevices.clear();
5409 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005410 mOutputs.clear();
5411 mInputs.clear();
5412 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005413 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005414 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005415}
5416
Eric Laurente0720872014-03-11 09:30:41 -07005417status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005418{
Eric Laurent87ffa392015-05-22 10:32:38 -07005419 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005420}
5421
Eric Laurente552edb2014-03-10 17:42:56 -07005422// ---
5423
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005424void AudioPolicyManager::onNewAudioModulesAvailable()
5425{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005426 DeviceVector newDevices;
5427 onNewAudioModulesAvailableInt(&newDevices);
5428 if (!newDevices.empty()) {
5429 nextAudioPortGeneration();
5430 mpClientInterface->onAudioPortListUpdate();
5431 }
5432}
5433
5434void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5435{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005436 for (const auto& hwModule : mHwModulesAll) {
5437 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5438 continue;
5439 }
5440 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5441 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5442 ALOGW("could not open HW module %s", hwModule->getName());
5443 continue;
5444 }
5445 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005446 // open all output streams needed to access attached devices.
5447 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005448 // This also validates mAvailableOutputDevices list
5449 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5450 if (!outProfile->canOpenNewIo()) {
5451 ALOGE("Invalid Output profile max open count %u for profile %s",
5452 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5453 continue;
5454 }
5455 if (!outProfile->hasSupportedDevices()) {
5456 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5457 continue;
5458 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005459 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5460 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005461 mTtsOutputAvailable = true;
5462 }
5463
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005464 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5465 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5466 sp<DeviceDescriptor> supportedDevice = 0;
5467 if (supportedDevices.contains(mDefaultOutputDevice)) {
5468 supportedDevice = mDefaultOutputDevice;
5469 } else {
5470 // choose first device present in profile's SupportedDevices also part of
5471 // mAvailableOutputDevices.
5472 if (availProfileDevices.isEmpty()) {
5473 continue;
5474 }
5475 supportedDevice = availProfileDevices.itemAt(0);
5476 }
5477 if (!mOutputDevicesAll.contains(supportedDevice)) {
5478 continue;
5479 }
5480 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5481 mpClientInterface);
5482 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005483 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5484 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005485 AUDIO_STREAM_DEFAULT,
5486 AUDIO_OUTPUT_FLAG_NONE, &output);
5487 if (status != NO_ERROR) {
5488 ALOGW("Cannot open output stream for devices %s on hw module %s",
5489 supportedDevice->toString().c_str(), hwModule->getName());
5490 continue;
5491 }
5492 for (const auto &device : availProfileDevices) {
5493 // give a valid ID to an attached device once confirmed it is reachable
5494 if (!device->isAttached()) {
5495 device->attach(hwModule);
5496 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005497 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005498 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005499 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5500 }
5501 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005502 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005503 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5504 mPrimaryOutput = outputDesc;
5505 }
Eric Laurent39095982021-08-24 18:29:27 +02005506 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005507 outputDesc->close();
5508 } else {
5509 addOutput(output, outputDesc);
5510 setOutputDevices(outputDesc,
5511 DeviceVector(supportedDevice),
5512 true,
5513 0,
5514 NULL);
5515 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005516 }
5517 // open input streams needed to access attached devices to validate
5518 // mAvailableInputDevices list
5519 for (const auto& inProfile : hwModule->getInputProfiles()) {
5520 if (!inProfile->canOpenNewIo()) {
5521 ALOGE("Invalid Input profile max open count %u for profile %s",
5522 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5523 continue;
5524 }
5525 if (!inProfile->hasSupportedDevices()) {
5526 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5527 continue;
5528 }
5529 // chose first device present in profile's SupportedDevices also part of
5530 // available input devices
5531 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5532 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5533 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005534 ALOGV("%s: Input device list is empty! for profile %s",
5535 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005536 continue;
5537 }
5538 sp<AudioInputDescriptor> inputDesc =
5539 new AudioInputDescriptor(inProfile, mpClientInterface);
5540
5541 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5542 status_t status = inputDesc->open(nullptr,
5543 availProfileDevices.itemAt(0),
5544 AUDIO_SOURCE_MIC,
5545 AUDIO_INPUT_FLAG_NONE,
5546 &input);
5547 if (status != NO_ERROR) {
5548 ALOGW("Cannot open input stream for device %s on hw module %s",
5549 availProfileDevices.toString().c_str(),
5550 hwModule->getName());
5551 continue;
5552 }
5553 for (const auto &device : availProfileDevices) {
5554 // give a valid ID to an attached device once confirmed it is reachable
5555 if (!device->isAttached()) {
5556 device->attach(hwModule);
5557 device->importAudioPortAndPickAudioProfile(inProfile, true);
5558 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005559 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005560 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5561 }
5562 }
5563 inputDesc->close();
5564 }
5565 }
5566}
5567
Eric Laurent98e38192018-02-15 18:31:53 -08005568void AudioPolicyManager::addOutput(audio_io_handle_t output,
5569 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005570{
Eric Laurent1c333e22014-05-20 10:48:17 -07005571 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005572 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005573 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005574 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005575 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005576}
5577
François Gaffie53615e22015-03-19 09:24:12 +01005578void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5579{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005580 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5581 ALOGV("%s: removing primary output", __func__);
5582 mPrimaryOutput = nullptr;
5583 }
François Gaffie53615e22015-03-19 09:24:12 +01005584 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005585 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005586}
5587
Eric Laurent98e38192018-02-15 18:31:53 -08005588void AudioPolicyManager::addInput(audio_io_handle_t input,
5589 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005590{
Eric Laurent1c333e22014-05-20 10:48:17 -07005591 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005592 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005593}
Eric Laurente552edb2014-03-10 17:42:56 -07005594
François Gaffie11d30102018-11-02 16:09:09 +01005595status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005596 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005597 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005598{
François Gaffie11d30102018-11-02 16:09:09 +01005599 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005600 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005601 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005602
François Gaffie11d30102018-11-02 16:09:09 +01005603 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005604 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005605 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005606 }
Eric Laurente552edb2014-03-10 17:42:56 -07005607
Eric Laurent3b73df72014-03-11 09:06:29 -07005608 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005609 // first call getAudioPort to get the supported attributes from the HAL
5610 struct audio_port_v7 port = {};
5611 device->toAudioPort(&port);
5612 status_t status = mpClientInterface->getAudioPort(&port);
5613 if (status == NO_ERROR) {
5614 device->importAudioPort(port);
5615 }
5616
5617 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005618 for (size_t i = 0; i < mOutputs.size(); i++) {
5619 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005620 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005621 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005622 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5623 mOutputs.keyAt(i), device->toString().c_str());
5624 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005625 }
5626 }
5627 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005628 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005629 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005630 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5631 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005632 if (profile->supportsDevice(device)) {
5633 profiles.add(profile);
5634 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5635 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005636 }
5637 }
5638 }
5639
Eric Laurent7b279bb2015-12-14 10:18:23 -08005640 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005641
Eric Laurente552edb2014-03-10 17:42:56 -07005642 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005643 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005644 return BAD_VALUE;
5645 }
5646
5647 // open outputs for matching profiles if needed. Direct outputs are also opened to
5648 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5649 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005650 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005651
5652 // nothing to do if one output is already opened for this profile
5653 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005654 for (j = 0; j < outputs.size(); j++) {
5655 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005656 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005657 // matching profile: save the sample rates, format and channel masks supported
5658 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005659 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005660 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005661 }
Eric Laurente552edb2014-03-10 17:42:56 -07005662 break;
5663 }
5664 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005665 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005666 continue;
5667 }
5668
Eric Laurent3974e3b2017-12-07 17:58:43 -08005669 if (!profile->canOpenNewIo()) {
5670 ALOGW("Max Output number %u already opened for this profile %s",
5671 profile->maxOpenCount, profile->getTagName().c_str());
5672 continue;
5673 }
5674
Eric Laurent83efe1c2017-07-09 16:51:08 -07005675 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005676 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005677 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5678 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005679 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005680 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005681 profiles.removeAt(profile_index);
5682 profile_index--;
5683 } else {
5684 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005685 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005686 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005687 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5688 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005689 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005690 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005691
François Gaffie11d30102018-11-02 16:09:09 +01005692 if (device_distinguishes_on_address(deviceType)) {
5693 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5694 device->toString().c_str());
5695 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5696 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005697 }
Eric Laurente552edb2014-03-10 17:42:56 -07005698 ALOGV("checkOutputsForDevice(): adding output %d", output);
5699 }
5700 }
5701
5702 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005703 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005704 return BAD_VALUE;
5705 }
Eric Laurentd4692962014-05-05 18:13:44 -07005706 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005707 // check if one opened output is not needed any more after disconnecting one device
5708 for (size_t i = 0; i < mOutputs.size(); i++) {
5709 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005710 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005711 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005712 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005713 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005714 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005715 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005716 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5717 mOutputs.keyAt(i));
5718 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005719 }
Eric Laurente552edb2014-03-10 17:42:56 -07005720 }
5721 }
Eric Laurentd4692962014-05-05 18:13:44 -07005722 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005723 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005724 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5725 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005726 if (!profile->supportsDevice(device)) {
5727 continue;
5728 }
5729 ALOGV("checkOutputsForDevice(): "
5730 "clearing direct output profile %zu on module %s",
5731 j, hwModule->getName());
5732 profile->clearAudioProfiles();
5733 if (!profile->hasDynamicAudioProfile()) {
5734 continue;
5735 }
5736 // When a device is disconnected, if there is an IOProfile that contains dynamic
5737 // profiles and supports the disconnected device, call getAudioPort to repopulate
5738 // the capabilities of the devices that is supported by the IOProfile.
5739 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5740 if (supportedDevice == device ||
5741 !mAvailableOutputDevices.contains(supportedDevice)) {
5742 continue;
5743 }
5744 struct audio_port_v7 port;
5745 supportedDevice->toAudioPort(&port);
5746 status_t status = mpClientInterface->getAudioPort(&port);
5747 if (status == NO_ERROR) {
5748 supportedDevice->importAudioPort(port);
5749 }
Eric Laurente552edb2014-03-10 17:42:56 -07005750 }
5751 }
5752 }
5753 }
5754 return NO_ERROR;
5755}
5756
François Gaffie11d30102018-11-02 16:09:09 +01005757status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07005758 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07005759{
Eric Laurent1f2f2232014-06-02 12:01:23 -07005760 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005761
François Gaffie11d30102018-11-02 16:09:09 +01005762 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005763 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005764 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005765 }
5766
Eric Laurentd4692962014-05-05 18:13:44 -07005767 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07005768 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005769 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005770 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005771 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005772 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005773 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005774 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08005775
François Gaffie11d30102018-11-02 16:09:09 +01005776 if (profile->supportsDevice(device)) {
5777 profiles.add(profile);
5778 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
5779 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07005780 }
5781 }
5782 }
5783
Eric Laurent0dd51852019-04-19 18:18:58 -07005784 if (profiles.isEmpty()) {
5785 ALOGW("%s: No input profile available for device %s",
5786 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005787 return BAD_VALUE;
5788 }
5789
5790 // open inputs for matching profiles if needed. Direct inputs are also opened to
5791 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5792 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
5793
Eric Laurent1c333e22014-05-20 10:48:17 -07005794 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08005795
Eric Laurentd4692962014-05-05 18:13:44 -07005796 // nothing to do if one input is already opened for this profile
5797 size_t input_index;
5798 for (input_index = 0; input_index < mInputs.size(); input_index++) {
5799 desc = mInputs.valueAt(input_index);
5800 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01005801 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005802 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005803 }
Eric Laurentd4692962014-05-05 18:13:44 -07005804 break;
5805 }
5806 }
5807 if (input_index != mInputs.size()) {
5808 continue;
5809 }
5810
Eric Laurent3974e3b2017-12-07 17:58:43 -08005811 if (!profile->canOpenNewIo()) {
5812 ALOGW("Max Input number %u already opened for this profile %s",
5813 profile->maxOpenCount, profile->getTagName().c_str());
5814 continue;
5815 }
5816
Eric Laurentfe231122017-11-17 17:48:06 -08005817 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005818 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08005819 status_t status = desc->open(nullptr,
5820 device,
Eric Laurentfe231122017-11-17 17:48:06 -08005821 AUDIO_SOURCE_MIC,
5822 AUDIO_INPUT_FLAG_NONE,
5823 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07005824
Eric Laurentcf2c0212014-07-25 16:20:43 -07005825 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07005826 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005827 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005828 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07005829 mpClientInterface->setParameters(input, String8(param));
5830 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07005831 }
François Gaffie11d30102018-11-02 16:09:09 +01005832 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01005833 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07005834 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08005835 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07005836 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07005837 }
5838
Eric Laurent0dd51852019-04-19 18:18:58 -07005839 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07005840 addInput(input, desc);
5841 }
5842 } // endif input != 0
5843
Eric Laurentcf2c0212014-07-25 16:20:43 -07005844 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08005845 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005846 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005847 profiles.removeAt(profile_index);
5848 profile_index--;
5849 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005850 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07005851 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005852 }
Eric Laurentd4692962014-05-05 18:13:44 -07005853 ALOGV("checkInputsForDevice(): adding input %d", input);
5854 }
5855 } // end scan profiles
5856
5857 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005858 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07005859 return BAD_VALUE;
5860 }
5861 } else {
5862 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07005863 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08005864 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07005865 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005866 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07005867 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005868 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01005869 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08005870 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
5871 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01005872 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07005873 }
5874 }
5875 }
5876 } // end disconnect
5877
5878 return NO_ERROR;
5879}
5880
5881
Eric Laurente0720872014-03-11 09:30:41 -07005882void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07005883{
5884 ALOGV("closeOutput(%d)", output);
5885
François Gaffie1c878552018-11-22 16:53:21 +01005886 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
5887 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07005888 ALOGW("closeOutput() unknown output %d", output);
5889 return;
5890 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005891 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01005892 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08005893
Eric Laurente552edb2014-03-10 17:42:56 -07005894 // look for duplicated outputs connected to the output being removed.
5895 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01005896 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
5897 if (dupOutput->isDuplicated() &&
5898 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
5899 sp<SwAudioOutputDescriptor> remainingOutput =
5900 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07005901 // As all active tracks on duplicated output will be deleted,
5902 // and as they were also referenced on the other output, the reference
5903 // count for their stream type must be adjusted accordingly on
5904 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01005905 const bool wasActive = remainingOutput->isActive();
5906 // Note: no-op on the closing output where all clients has already been set inactive
5907 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08005908 // stop() will be a no op if the output is still active but is needed in case all
5909 // active streams refcounts where cleared above
5910 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01005911 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005912 }
Eric Laurente552edb2014-03-10 17:42:56 -07005913 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
5914 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
5915
5916 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01005917 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07005918 }
5919 }
5920
Eric Laurent05b90f82014-08-27 15:32:29 -07005921 nextAudioPortGeneration();
5922
François Gaffie1c878552018-11-22 16:53:21 +01005923 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005924 if (index >= 0) {
5925 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005926 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5927 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005928 mAudioPatches.removeItemsAt(index);
5929 mpClientInterface->onAudioPatchListUpdate();
5930 }
5931
Mikhail Naganov32ebca32019-03-22 15:42:52 -07005932 if (closingOutputWasActive) {
5933 closingOutput->stop();
5934 }
François Gaffie1c878552018-11-22 16:53:21 +01005935 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005936
François Gaffie53615e22015-03-19 09:24:12 +01005937 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07005938 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01005939 if (closingOutput == mSpatializerOutput) {
5940 mSpatializerOutput.clear();
5941 }
Dean Wheatley3023b382018-08-09 07:42:40 +10005942
5943 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
5944 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01005945 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10005946 bool directOutputOpen = false;
5947 for (size_t i = 0; i < mOutputs.size(); i++) {
5948 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
5949 directOutputOpen = true;
5950 break;
5951 }
5952 }
5953 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11005954 ALOGV("no direct outputs open, reset MSD patches");
5955 // TODO: The MSD patches to be established here may differ to current MSD patches due to
5956 // how output devices for patching are resolved. Avoid by caching and reusing the
5957 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
5958 // devices to patch to. This may be complicated by the fact that devices may become
5959 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005960 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10005961 }
5962 }
Eric Laurent05b90f82014-08-27 15:32:29 -07005963}
5964
5965void AudioPolicyManager::closeInput(audio_io_handle_t input)
5966{
5967 ALOGV("closeInput(%d)", input);
5968
5969 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
5970 if (inputDesc == NULL) {
5971 ALOGW("closeInput() unknown input %d", input);
5972 return;
5973 }
5974
Eric Laurent6a94d692014-05-20 11:18:06 -07005975 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07005976
François Gaffie11d30102018-11-02 16:09:09 +01005977 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08005978 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07005979 if (index >= 0) {
5980 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005981 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
5982 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07005983 mAudioPatches.removeItemsAt(index);
5984 mpClientInterface->onAudioPatchListUpdate();
5985 }
5986
Eric Laurentfe231122017-11-17 17:48:06 -08005987 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07005988 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005989
François Gaffie11d30102018-11-02 16:09:09 +01005990 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
5991 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005992 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07005993 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07005994 }
Eric Laurente552edb2014-03-10 17:42:56 -07005995}
5996
François Gaffie11d30102018-11-02 16:09:09 +01005997SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
5998 const DeviceVector &devices,
5999 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006000{
6001 SortedVector<audio_io_handle_t> outputs;
6002
François Gaffie11d30102018-11-02 16:09:09 +01006003 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006004 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006005 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006006 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006007 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006008 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006009 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006010 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006011 outputs.add(openOutputs.keyAt(i));
6012 }
6013 }
6014 return outputs;
6015}
6016
Mikhail Naganov37977152018-07-11 15:54:44 -07006017void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6018{
6019 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6020 // output is suspended before any tracks are moved to it
6021 checkA2dpSuspend();
6022 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006023 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006024 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006025 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006026 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006027 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6028 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6029 // configuration changes will ultimately be rerouted correctly. We can still avoid
6030 // unnecessary rerouting by caching and reusing the arguments to
6031 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6032 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006033 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006034 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006035 // an event that changed routing likely occurred, inform upper layers
6036 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006037}
6038
François Gaffiec005e562018-11-06 15:04:49 +01006039bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6040 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006041{
François Gaffiec005e562018-11-06 15:04:49 +01006042 return mEngine->getProductStrategyForAttributes(lAttr) ==
6043 mEngine->getProductStrategyForAttributes(rAttr);
6044}
6045
Francois Gaffieff1eb522020-05-06 18:37:04 +02006046void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6047{
6048 for (size_t i = 0; i < mAudioSources.size(); i++) {
6049 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6050 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006051 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
6052 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006053 connectAudioSource(sourceDesc);
6054 }
6055 }
6056}
6057
6058void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6059{
6060 for (size_t i = 0; i < mAudioSources.size(); i++) {
6061 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6062 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6063 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6064 disconnectAudioSource(sourceDesc);
6065 }
6066 }
6067}
6068
François Gaffiec005e562018-11-06 15:04:49 +01006069void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6070{
6071 auto psId = mEngine->getProductStrategyForAttributes(attr);
6072
6073 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6074 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006075
François Gaffie11d30102018-11-02 16:09:09 +01006076 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6077 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006078
Eric Laurentc209fe42020-06-05 18:11:23 -07006079 uint32_t maxLatency = 0;
6080 bool invalidate = false;
6081 // take into account dynamic audio policies related changes: if a client is now associated
6082 // to a different policy mix than at creation time, invalidate corresponding stream
6083 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6084 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6085 if (desc->isDuplicated()) {
6086 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006087 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006088 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6089 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6090 continue;
6091 }
6092 sp<AudioPolicyMix> primaryMix;
6093 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
6094 client->flags(), primaryMix, nullptr);
6095 if (status != OK) {
6096 continue;
6097 }
yucliuf4de36d2020-09-14 14:57:56 -07006098 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006099 invalidate = true;
6100 if (desc->isStrategyActive(psId)) {
6101 maxLatency = desc->latency();
6102 }
6103 break;
6104 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006105 }
6106 }
6107
Eric Laurentc209fe42020-06-05 18:11:23 -07006108 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006109 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6110 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006111 for (audio_io_handle_t srcOut : srcOutputs) {
6112 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006113 if (desc == nullptr) continue;
6114
6115 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006116 maxLatency = desc->latency();
6117 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006118
6119 if (invalidate) continue;
6120
6121 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006122 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006123 // a client on a non direct outputs has necessarily a linear PCM format
6124 // so we can call selectOutput() safely
6125 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6126 client->flags(),
6127 client->config().format,
6128 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006129 client->config().sample_rate,
6130 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006131 if (newOutput != srcOut) {
6132 invalidate = true;
6133 break;
6134 }
6135 } else {
6136 sp<IOProfile> profile = getProfileForOutput(newDevices,
6137 client->config().sample_rate,
6138 client->config().format,
6139 client->config().channel_mask,
6140 client->flags(),
6141 true /* directOnly */);
6142 if (profile != desc->mProfile) {
6143 invalidate = true;
6144 break;
6145 }
6146 }
6147 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006148 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006149
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006150 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006151 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006152 std::to_string(srcOutputs[0]).c_str(),
6153 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006154 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006155 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006156 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006157 if (desc == nullptr) continue;
6158
6159 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006160 setStrategyMute(psId, true, desc);
6161 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006162 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006163 }
François Gaffiec005e562018-11-06 15:04:49 +01006164 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006165 if (source != nullptr && !isCallRxAudioSource(source)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006166 connectAudioSource(source);
6167 }
Eric Laurente552edb2014-03-10 17:42:56 -07006168 }
6169
François Gaffiec005e562018-11-06 15:04:49 +01006170 // Move effects associated to this stream from previous output to new output
6171 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006172 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006173 }
François Gaffiec005e562018-11-06 15:04:49 +01006174 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006175 if (invalidate) {
6176 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6177 mpClientInterface->invalidateStream(stream);
6178 }
Eric Laurente552edb2014-03-10 17:42:56 -07006179 }
6180 }
6181}
6182
Eric Laurente0720872014-03-11 09:30:41 -07006183void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006184{
François Gaffiec005e562018-11-06 15:04:49 +01006185 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6186 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6187 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006188 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006189 }
Eric Laurente552edb2014-03-10 17:42:56 -07006190}
6191
Kevin Rocard153f92d2018-12-18 18:33:28 -08006192void AudioPolicyManager::checkSecondaryOutputs() {
6193 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006194 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006195 for (size_t i = 0; i < mOutputs.size(); i++) {
6196 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6197 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006198 sp<AudioPolicyMix> primaryMix;
6199 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Kevin Rocard94114a22019-04-01 19:38:23 -07006200 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->uid(),
Eric Laurentc529cf62020-04-17 18:19:10 -07006201 client->flags(), primaryMix, &secondaryMixes);
6202 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6203 for (auto &secondaryMix : secondaryMixes) {
6204 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6205 if (outputDesc != nullptr &&
6206 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6207 secondaryDescs.push_back(outputDesc);
6208 }
6209 }
6210
jiabin10a03f12021-05-07 23:46:28 +00006211 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006212 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006213 } else if (!std::equal(
6214 client->getSecondaryOutputs().begin(),
6215 client->getSecondaryOutputs().end(),
6216 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006217 if (!audio_is_linear_pcm(client->config().format)) {
6218 // If the format is not PCM, the tracks should be invalidated to get correct
6219 // behavior when the secondary output is changed.
6220 streamsToInvalidate.insert(client->stream());
6221 } else {
6222 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6223 std::vector<audio_io_handle_t> secondaryOutputIds;
6224 for (const auto &secondaryDesc: secondaryDescs) {
6225 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6226 weakSecondaryDescs.push_back(secondaryDesc);
6227 }
6228 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6229 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006230 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006231 }
6232 }
6233 }
jiabin10a03f12021-05-07 23:46:28 +00006234 if (!trackSecondaryOutputs.empty()) {
6235 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6236 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006237 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006238 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006239 mpClientInterface->invalidateStream(stream);
6240 }
6241}
6242
Eric Laurent2517af32020-11-25 15:31:27 +01006243bool AudioPolicyManager::isScoRequestedForComm() const {
6244 AudioDeviceTypeAddrVector devices;
6245 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6246 for (const auto &device : devices) {
6247 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6248 return true;
6249 }
6250 }
6251 return false;
6252}
6253
Eric Laurente0720872014-03-11 09:30:41 -07006254void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006255{
François Gaffie53615e22015-03-19 09:24:12 +01006256 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006257 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006258 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006259 return;
6260 }
6261
Eric Laurent3a4311c2014-03-17 12:00:47 -07006262 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006263 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6264 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006265 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006266
6267 // if suspended, restore A2DP output if:
6268 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006269 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006270 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006271 //
Eric Laurentf732e072016-08-03 19:30:28 -07006272 // if not suspended, suspend A2DP output if:
6273 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006274 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006275 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006276 //
6277 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006278 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006279 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006280 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006281 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006282
6283 mpClientInterface->restoreOutput(a2dpOutput);
6284 mA2dpSuspended = false;
6285 }
6286 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006287 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006288 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006289 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006290 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006291
6292 mpClientInterface->suspendOutput(a2dpOutput);
6293 mA2dpSuspended = true;
6294 }
6295 }
6296}
6297
François Gaffie11d30102018-11-02 16:09:09 +01006298DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6299 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006300{
François Gaffie11d30102018-11-02 16:09:09 +01006301 DeviceVector devices;
6302
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006303 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006304 if (index >= 0) {
6305 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006306 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006307 ALOGV("%s device %s forced by patch %d", __func__,
6308 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6309 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006310 }
6311 }
6312
Dean Wheatley514b4312020-06-17 21:45:00 +10006313 // Do not retrieve engine device for outputs through MSD
6314 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6315 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6316 return outputDesc->devices();
6317 }
6318
Eric Laurent97ac8712018-07-27 18:59:02 -07006319 // Honor explicit routing requests only if no client using default routing is active on this
6320 // input: a specific app can not force routing for other apps by setting a preferred device.
6321 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006322 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006323 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006324 if (device != nullptr) {
6325 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006326 }
6327
François Gaffiea807ef92018-11-05 10:44:33 +01006328 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6329 // of setForceUse / Default Bus device here
6330 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6331 if (device != nullptr) {
6332 return DeviceVector(device);
6333 }
6334
François Gaffiec005e562018-11-06 15:04:49 +01006335 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6336 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6337 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306338 auto hasStreamActive = [&](auto stream) {
6339 return hasStream(streams, stream) && isStreamActive(stream, 0);
6340 };
Eric Laurent484e9272018-06-07 17:29:23 -07006341
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306342 auto doGetOutputDevicesForVoice = [&]() {
6343 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
6344 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL))) &&
6345 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006346 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6347 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306348 };
6349
6350 // With low-latency playing on speaker, music on WFD, when the first low-latency
6351 // output is stopped, getNewOutputDevices checks for a product strategy
6352 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006353 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306354 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6355 // stream is associated to the output descriptor.
6356 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6357 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6358 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6359 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006360 // Retrieval of devices for voice DL is done on primary output profile, cannot
6361 // check the route (would force modifying configuration file for this profile)
6362 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6363 break;
6364 }
Eric Laurente552edb2014-03-10 17:42:56 -07006365 }
François Gaffiec005e562018-11-06 15:04:49 +01006366 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006367 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006368}
6369
François Gaffie11d30102018-11-02 16:09:09 +01006370sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6371 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006372{
François Gaffie11d30102018-11-02 16:09:09 +01006373 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006374
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006375 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006376 if (index >= 0) {
6377 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006378 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006379 ALOGV("getNewInputDevice() device %s forced by patch %d",
6380 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6381 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006382 }
6383 }
6384
Eric Laurent97ac8712018-07-27 18:59:02 -07006385 // Honor explicit routing requests only if no client using default routing is active on this
6386 // input: a specific app can not force routing for other apps by setting a preferred device.
6387 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006388 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6389 if (device != nullptr) {
6390 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006391 }
6392
Eric Laurentdc95a252018-04-12 12:46:56 -07006393 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006394 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006395 audio_attributes_t attributes;
6396 uid_t uid;
6397 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6398 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006399 attributes = topClient->attributes();
6400 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006401 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006402 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6403 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006404 }
6405
Francois Gaffie716e1432019-01-14 16:58:59 +01006406 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6407 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006408 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006409 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006410 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006411 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006412
Eric Laurente552edb2014-03-10 17:42:56 -07006413 return device;
6414}
6415
Eric Laurent794fde22016-03-11 09:50:45 -08006416bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6417 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006418 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006419}
6420
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006421DeviceTypeSet AudioPolicyManager::getDevicesForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006422 // By checking the range of stream before calling getStrategy, we avoid
François Gaffiec005e562018-11-06 15:04:49 +01006423 // getOutputDevicesForStream's behavior for invalid streams.
6424 // engine's getOutputDevicesForStream would fallback on its default behavior (most probably
6425 // device for music stream), but we want to return the empty set.
6426 if (stream < AUDIO_STREAM_MIN || stream >= AUDIO_STREAM_PUBLIC_CNT) {
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006427 return DeviceTypeSet{};
Eric Laurent6a94d692014-05-20 11:18:06 -07006428 }
François Gaffie11d30102018-11-02 16:09:09 +01006429 DeviceVector activeDevices;
6430 DeviceVector devices;
Mikhail Naganovf33115d2020-09-25 23:03:05 +00006431 for (int i = AUDIO_STREAM_MIN; i < AUDIO_STREAM_PUBLIC_CNT; ++i) {
6432 const audio_stream_type_t curStream{static_cast<audio_stream_type_t>(i)};
François Gaffiec005e562018-11-06 15:04:49 +01006433 if (!streamsMatchForvolume(stream, curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08006434 continue;
Eric Laurent6a94d692014-05-20 11:18:06 -07006435 }
François Gaffiec005e562018-11-06 15:04:49 +01006436 DeviceVector curDevices = mEngine->getOutputDevicesForStream(curStream, false/*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01006437 devices.merge(curDevices);
6438 for (audio_io_handle_t output : getOutputsForDevices(curDevices, mOutputs)) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006439 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07006440 if (outputDesc->isActive(toVolumeSource(curStream))) {
François Gaffie11d30102018-11-02 16:09:09 +01006441 activeDevices.merge(outputDesc->devices());
Eric Laurent28d09f02016-03-08 10:43:05 -08006442 }
6443 }
Eric Laurente552edb2014-03-10 17:42:56 -07006444 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006445
Eric Laurentb0688d62018-08-14 15:49:18 -07006446 // Favor devices selected on active streams if any to report correct device in case of
6447 // explicit device selection
François Gaffie11d30102018-11-02 16:09:09 +01006448 if (!activeDevices.isEmpty()) {
Eric Laurentb0688d62018-08-14 15:49:18 -07006449 devices = activeDevices;
6450 }
Jon Eklund11c9fb12014-06-23 14:47:03 -05006451 /*Filter SPEAKER_SAFE out of results, as AudioService doesn't know about it
6452 and doesn't really need to.*/
jiabin9a3361e2019-10-01 09:38:30 -07006453 DeviceVector speakerSafeDevices = devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
François Gaffie11d30102018-11-02 16:09:09 +01006454 if (!speakerSafeDevices.isEmpty()) {
jiabin9a3361e2019-10-01 09:38:30 -07006455 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
François Gaffie11d30102018-11-02 16:09:09 +01006456 devices.remove(speakerSafeDevices);
Jon Eklund11c9fb12014-06-23 14:47:03 -05006457 }
Mikhail Naganov5478fc12021-07-08 16:13:29 -07006458 return devices.types();
Eric Laurente552edb2014-03-10 17:42:56 -07006459}
6460
Dorin Drimusf2196d82022-01-03 12:11:18 +01006461// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006462status_t AudioPolicyManager::getDevicesForAttributes(
6463 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices) {
6464 if (devices == nullptr) {
6465 return BAD_VALUE;
6466 }
6467 // check dynamic policies but only for primary descriptors (secondary not used for audible
6468 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006469 sp<AudioPolicyMix> policyMix;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006470 status_t status = mPolicyMixes.getOutputForAttr(attr, 0 /*uid unknown here*/,
Eric Laurentc529cf62020-04-17 18:19:10 -07006471 AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006472 if (status != OK) {
6473 return status;
6474 }
Eric Laurentc529cf62020-04-17 18:19:10 -07006475 if (policyMix != nullptr && policyMix->getOutput() != nullptr) {
6476 AudioDeviceTypeAddr device(policyMix->mDeviceType, policyMix->mDeviceAddress.c_str());
6477 devices->push_back(device);
6478 return NO_ERROR;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006479 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006480 DeviceVector curDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6481 for (const auto& device : curDevices) {
6482 devices->push_back(device->getDeviceTypeAddr());
6483 }
6484 return NO_ERROR;
6485}
6486
Eric Laurente0720872014-03-11 09:30:41 -07006487void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006488 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006489 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006490 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006491 updateDevicesAndOutputs();
6492 break;
6493 default:
6494 break;
6495 }
6496}
6497
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006498uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006499
6500 // skip beacon mute management if a dedicated TTS output is available
6501 if (mTtsOutputAvailable) {
6502 return 0;
6503 }
6504
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006505 switch(event) {
6506 case STARTING_OUTPUT:
6507 mBeaconMuteRefCount++;
6508 break;
6509 case STOPPING_OUTPUT:
6510 if (mBeaconMuteRefCount > 0) {
6511 mBeaconMuteRefCount--;
6512 }
6513 break;
6514 case STARTING_BEACON:
6515 mBeaconPlayingRefCount++;
6516 break;
6517 case STOPPING_BEACON:
6518 if (mBeaconPlayingRefCount > 0) {
6519 mBeaconPlayingRefCount--;
6520 }
6521 break;
6522 }
6523
6524 if (mBeaconMuteRefCount > 0) {
6525 // any playback causes beacon to be muted
6526 return setBeaconMute(true);
6527 } else {
6528 // no other playback: unmute when beacon starts playing, mute when it stops
6529 return setBeaconMute(mBeaconPlayingRefCount == 0);
6530 }
6531}
6532
6533uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6534 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6535 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6536 // keep track of muted state to avoid repeating mute/unmute operations
6537 if (mBeaconMuted != mute) {
6538 // mute/unmute AUDIO_STREAM_TTS on all outputs
6539 ALOGV("\t muting %d", mute);
6540 uint32_t maxLatency = 0;
François Gaffieaaac0fd2018-11-22 17:56:39 +01006541 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS);
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006542 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006543 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006544 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006545 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006546 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006547 maxLatency = latency;
6548 }
6549 }
6550 mBeaconMuted = mute;
6551 return maxLatency;
6552 }
6553 return 0;
6554}
6555
Eric Laurente0720872014-03-11 09:30:41 -07006556void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006557{
François Gaffiec005e562018-11-06 15:04:49 +01006558 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006559 mPreviousOutputs = mOutputs;
6560}
6561
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006562uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006563 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006564 uint32_t delayMs)
6565{
6566 // mute/unmute strategies using an incompatible device combination
6567 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6568 // if unmuting, unmute only after the specified delay
6569 if (outputDesc->isDuplicated()) {
6570 return 0;
6571 }
6572
6573 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006574 DeviceVector devices = outputDesc->devices();
6575 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006576
François Gaffiec005e562018-11-06 15:04:49 +01006577 auto productStrategies = mEngine->getOrderedProductStrategies();
6578 for (const auto &productStrategy : productStrategies) {
6579 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6580 DeviceVector curDevices =
6581 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6582 curDevices = curDevices.filter(outputDesc->supportedDevices());
6583 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006584 bool doMute = false;
6585
François Gaffiec005e562018-11-06 15:04:49 +01006586 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006587 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006588 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6589 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006590 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006591 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006592 }
Eric Laurent99401132014-05-07 19:48:15 -07006593 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006594 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006595 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006596 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006597 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006598 continue;
6599 }
François Gaffiec005e562018-11-06 15:04:49 +01006600 ALOGVV("%s() %s (curDevice %s)", __func__,
6601 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6602 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6603 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006604 if (mute) {
6605 // FIXME: should not need to double latency if volume could be applied
6606 // immediately by the audioflinger mixer. We must account for the delay
6607 // between now and the next time the audioflinger thread for this output
6608 // will process a buffer (which corresponds to one buffer size,
6609 // usually 1/2 or 1/4 of the latency).
6610 if (muteWaitMs < desc->latency() * 2) {
6611 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006612 }
6613 }
6614 }
6615 }
6616 }
6617 }
6618
Eric Laurent99401132014-05-07 19:48:15 -07006619 // temporary mute output if device selection changes to avoid volume bursts due to
6620 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006621 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006622 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006623
Eric Laurentdc462862016-07-19 12:29:53 -07006624 if (muteWaitMs < tempMuteWaitMs) {
6625 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006626 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006627
6628 // If recommended duration is defined, replace temporary mute duration to avoid
6629 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6630 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6631 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6632 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6633 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6634
François Gaffieaaac0fd2018-11-22 17:56:39 +01006635 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6636 // make sure that we do not start the temporary mute period too early in case of
6637 // delayed device change
6638 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6639 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006640 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006641 }
6642 }
6643
Eric Laurente552edb2014-03-10 17:42:56 -07006644 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6645 if (muteWaitMs > delayMs) {
6646 muteWaitMs -= delayMs;
6647 usleep(muteWaitMs * 1000);
6648 return muteWaitMs;
6649 }
6650 return 0;
6651}
6652
François Gaffie11d30102018-11-02 16:09:09 +01006653uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6654 const DeviceVector &devices,
6655 bool force,
6656 int delayMs,
6657 audio_patch_handle_t *patchHandle,
6658 bool requiresMuteCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006659{
François Gaffie11d30102018-11-02 16:09:09 +01006660 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006661 uint32_t muteWaitMs;
6662
6663 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006664 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6665 nullptr /* patchHandle */, requiresMuteCheck);
6666 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6667 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006668 return muteWaitMs;
6669 }
Eric Laurente552edb2014-03-10 17:42:56 -07006670
6671 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006672 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006673 DeviceVector prevDevices = outputDesc->devices();
Eric Laurente552edb2014-03-10 17:42:56 -07006674
François Gaffie11d30102018-11-02 16:09:09 +01006675 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6676
6677 if (!filteredDevices.isEmpty()) {
6678 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006679 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006680
6681 // if the outputs are not materially active, there is no need to mute.
6682 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006683 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006684 } else {
6685 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6686 muteWaitMs = 0;
6687 }
Eric Laurente552edb2014-03-10 17:42:56 -07006688
Eric Laurent79ea9582020-06-11 18:49:24 -07006689 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6690 // output profile or if new device is not supported AND previous device(s) is(are) still
6691 // available (otherwise reset device must be done on the output)
6692 if (!devices.isEmpty() && filteredDevices.isEmpty() &&
6693 !mAvailableOutputDevices.filter(prevDevices).empty()) {
6694 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6695 // restore previous device after evaluating strategy mute state
6696 outputDesc->setDevices(prevDevices);
6697 return muteWaitMs;
6698 }
6699
Eric Laurente552edb2014-03-10 17:42:56 -07006700 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006701 // the requested device is AUDIO_DEVICE_NONE
6702 // OR the requested device is the same as current device
6703 // AND force is not specified
6704 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006705 // Doing this check here allows the caller to call setOutputDevices() without conditions
Mikhail Naganov2d4e1702019-01-24 12:59:44 -08006706 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) &&
François Gaffie11d30102018-11-02 16:09:09 +01006707 !force && outputDesc->getPatchHandle() != 0) {
6708 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6709 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Eric Laurente552edb2014-03-10 17:42:56 -07006710 return muteWaitMs;
6711 }
6712
François Gaffie11d30102018-11-02 16:09:09 +01006713 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006714
Eric Laurente552edb2014-03-10 17:42:56 -07006715 // do the routing
François Gaffie11d30102018-11-02 16:09:09 +01006716 if (filteredDevices.isEmpty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006717 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006718 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006719 PatchBuilder patchBuilder;
6720 patchBuilder.addSource(outputDesc);
6721 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6722 for (const auto &filteredDevice : filteredDevices) {
6723 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006724 }
6725
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006726 // Add half reported latency to delayMs when muteWaitMs is null in order
6727 // to avoid disordered sequence of muting volume and changing devices.
6728 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6729 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006730 }
Eric Laurente552edb2014-03-10 17:42:56 -07006731
6732 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006733 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006734
6735 return muteWaitMs;
6736}
6737
Eric Laurentc75307b2015-03-17 15:29:32 -07006738status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006739 int delayMs,
6740 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006741{
Eric Laurent6a94d692014-05-20 11:18:06 -07006742 ssize_t index;
6743 if (patchHandle) {
6744 index = mAudioPatches.indexOfKey(*patchHandle);
6745 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006746 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006747 }
6748 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006749 return INVALID_OPERATION;
6750 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006751 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006752 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006753 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006754 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006755 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006756 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006757 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006758 return status;
6759}
6760
6761status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006762 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006763 bool force,
6764 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006765{
6766 status_t status = NO_ERROR;
6767
Eric Laurent1f2f2232014-06-02 12:01:23 -07006768 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006769 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6770 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006771
François Gaffie11d30102018-11-02 16:09:09 +01006772 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006773 PatchBuilder patchBuilder;
6774 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006775 // AUDIO_SOURCE_HOTWORD is for internal use only:
6776 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006777 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
6778 auto result = usecase;
6779 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
6780 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
6781 }
6782 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07006783 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01006784 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07006785 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006786 }
6787 }
6788 return status;
6789}
6790
Eric Laurent6a94d692014-05-20 11:18:06 -07006791status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
6792 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006793{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006794 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07006795 ssize_t index;
6796 if (patchHandle) {
6797 index = mAudioPatches.indexOfKey(*patchHandle);
6798 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006799 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006800 }
6801 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006802 return INVALID_OPERATION;
6803 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006804 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006805 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07006806 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006807 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006808 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006809 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006810 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006811 return status;
6812}
6813
François Gaffie11d30102018-11-02 16:09:09 +01006814sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01006815 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07006816 audio_format_t& format,
6817 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01006818 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07006819{
6820 // Choose an input profile based on the requested capture parameters: select the first available
6821 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07006822 //
6823 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
6824 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07006825
Glenn Kasten730b9262018-03-29 15:01:26 -07006826 sp<IOProfile> firstInexact;
6827 uint32_t updatedSamplingRate = 0;
6828 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
6829 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006830 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006831 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006832 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07006833 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01006834 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07006835 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07006836 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07006837 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07006838 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07006839 &channelMask /*updatedChannelMask*/,
6840 // FIXME ugly cast
6841 (audio_output_flags_t) flags,
6842 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006843 return profile;
6844 }
François Gaffie11d30102018-11-02 16:09:09 +01006845 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07006846 samplingRate,
6847 &updatedSamplingRate,
6848 format,
6849 &updatedFormat,
6850 channelMask,
6851 &updatedChannelMask,
6852 // FIXME ugly cast
6853 (audio_output_flags_t) flags,
6854 false /*exactMatchRequiredForInputFlags*/)) {
6855 firstInexact = profile;
6856 }
6857
Eric Laurente552edb2014-03-10 17:42:56 -07006858 }
6859 }
Glenn Kasten730b9262018-03-29 15:01:26 -07006860 if (firstInexact != nullptr) {
6861 samplingRate = updatedSamplingRate;
6862 format = updatedFormat;
6863 channelMask = updatedChannelMask;
6864 return firstInexact;
6865 }
Eric Laurente552edb2014-03-10 17:42:56 -07006866 return NULL;
6867}
6868
François Gaffieaaac0fd2018-11-22 17:56:39 +01006869float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
6870 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01006871 int index,
jiabin9a3361e2019-10-01 09:38:30 -07006872 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07006873{
jiabin9a3361e2019-10-01 09:38:30 -07006874 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006875
6876 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
6877 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
6878 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
6879 // the ringtone volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01006880 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
6881 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING);
6882 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC);
6883 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM);
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006884 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006885
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006886 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01006887 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
6888 mOutputs.isActive(ringVolumeSrc, 0)) {
6889 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07006890 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006891 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07006892 }
6893
Eric Laurentdcd4ab12018-06-29 17:45:13 -07006894 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01006895 if ((volumeSource != callVolumeSrc && (isInCall() ||
6896 mOutputs.isActiveLocally(callVolumeSrc))) &&
6897 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM) ||
6898 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
6899 volumeSource == alarmVolumeSrc ||
6900 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION) ||
6901 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
6902 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006903 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006904 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07006905 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006906 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07006907 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07006908 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006909 // FIXME: Workaround for call screening applications until a proper audio mode is defined
6910 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
6911 // programmatically muted.
6912 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
6913 // 0. We don't want to cap volume when the system has programmatically muted the voice call
6914 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07006915 bool exemptFromCapping =
6916 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
6917 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07006918 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
6919 volumeSource, volumeDb);
6920 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01006921 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
6922 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
6923 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07006924 }
6925 }
Eric Laurente552edb2014-03-10 17:42:56 -07006926 // if a headset is connected, apply the following rules to ring tones and notifications
6927 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07006928 // - always attenuate notifications volume by 6dB
6929 // - attenuate ring tones volume by 6dB unless music is not playing and
6930 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07006931 // - if music is playing, always limit the volume to current music volume,
6932 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07006933 if (!Intersection(deviceTypes,
6934 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
6935 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07006936 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
6937 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006938 ((volumeSource == alarmVolumeSrc ||
6939 volumeSource == ringVolumeSrc) ||
6940 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION)) ||
6941 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM)) ||
6942 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6943 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
6944 curves.canBeMuted()) {
6945
Eric Laurente552edb2014-03-10 17:42:56 -07006946 // when the phone is ringing we must consider that music could have been paused just before
6947 // by the music application and behave as if music was active if the last music track was
6948 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07006949 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07006950 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01006951 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07006952 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01006953 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
6954 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01006955 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07006956 float musicVolDb = computeVolume(musicCurves,
6957 musicVolumeSrc,
6958 musicCurves.getVolumeIndex(musicDevice),
6959 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01006960 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
6961 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
6962 if (volumeDb > minVolDb) {
6963 volumeDb = minVolDb;
6964 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07006965 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02006966 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
6967 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
6968 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006969 // on A2DP, also ensure notification volume is not too low compared to media when
6970 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01006971 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01006972 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07006973 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
6974 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006975 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
6976 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07006977 }
6978 }
jiabin9a3361e2019-10-01 09:38:30 -07006979 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01006980 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01006981 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07006982 }
6983 }
6984
François Gaffie43c73442018-11-08 08:21:55 +01006985 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07006986}
6987
Eric Laurent3839bc02018-07-10 18:33:34 -07006988int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006989 VolumeSource fromVolumeSource,
6990 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07006991{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006992 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07006993 return srcIndex;
6994 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01006995 auto &srcCurves = getVolumeCurves(fromVolumeSource);
6996 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08006997 float minSrc = (float)srcCurves.getVolumeIndexMin();
6998 float maxSrc = (float)srcCurves.getVolumeIndexMax();
6999 float minDst = (float)dstCurves.getVolumeIndexMin();
7000 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007001
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007002 // preserve mute request or correct range
7003 if (srcIndex < minSrc) {
7004 if (srcIndex == 0) {
7005 return 0;
7006 }
7007 srcIndex = minSrc;
7008 } else if (srcIndex > maxSrc) {
7009 srcIndex = maxSrc;
7010 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007011 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7012}
7013
François Gaffieaaac0fd2018-11-22 17:56:39 +01007014status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7015 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007016 int index,
7017 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007018 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007019 int delayMs,
7020 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007021{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007022 // do not change actual attributes volume if the attributes is muted
7023 if (outputDesc->isMuted(volumeSource)) {
7024 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7025 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007026 return NO_ERROR;
7027 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007028 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL);
7029 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO);
7030 bool isVoiceVolSrc = callVolSrc == volumeSource;
7031 bool isBtScoVolSrc = btScoVolSrc == volumeSource;
7032
Eric Laurent2517af32020-11-25 15:31:27 +01007033 bool isScoRequested = isScoRequestedForComm();
Eric Laurente552edb2014-03-10 17:42:56 -07007034 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007035 // if sco and call follow same curves, bypass forceUseForComm
7036 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007037 ((isVoiceVolSrc && isScoRequested) ||
7038 (isBtScoVolSrc && !isScoRequested))) {
7039 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
7040 volumeSource, isScoRequested ? " " : "n ot ");
Eric Laurent571ef962020-07-24 11:43:48 -07007041 // Do not return an error here as AudioService will always set both voice call
7042 // and bluetooth SCO volumes due to stream aliasing.
7043 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007044 }
jiabin9a3361e2019-10-01 09:38:30 -07007045 if (deviceTypes.empty()) {
7046 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007047 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007048
jiabin9a3361e2019-10-01 09:38:30 -07007049 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7050 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007051 // Force VoIP volume to max for bluetooth SCO device except if muted
7052 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007053 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007054 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007055 }
jiabin9a3361e2019-10-01 09:38:30 -07007056 outputDesc->setVolume(
7057 volumeDb, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007058
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007059 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007060 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007061 // 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 +01007062 if (isVoiceVolSrc) {
7063 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007064 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007065 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007066 }
Eric Laurent18fba842016-03-31 14:41:26 -07007067 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007068 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7069 mLastVoiceVolume = voiceVolume;
7070 }
7071 }
Eric Laurente552edb2014-03-10 17:42:56 -07007072 return NO_ERROR;
7073}
7074
Eric Laurentc75307b2015-03-17 15:29:32 -07007075void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007076 const DeviceTypeSet& deviceTypes,
7077 int delayMs,
7078 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007079{
jiabincd510522020-01-22 09:40:55 -08007080 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007081 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7082 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7083 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007084 curves.getVolumeIndex(deviceTypes),
7085 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007086 }
7087}
7088
François Gaffiec005e562018-11-06 15:04:49 +01007089void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7090 bool on,
7091 const sp<AudioOutputDescriptor>& outputDesc,
7092 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007093 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007094{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007095 std::vector<VolumeSource> sourcesToMute;
7096 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7097 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7098 toString(attributes).c_str(), on, outputDesc->getId());
7099 VolumeSource source = toVolumeSource(attributes);
7100 if (std::find(begin(sourcesToMute), end(sourcesToMute), source) == end(sourcesToMute)) {
7101 sourcesToMute.push_back(source);
7102 }
Eric Laurente552edb2014-03-10 17:42:56 -07007103 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007104 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007105 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007106 }
7107
Eric Laurente552edb2014-03-10 17:42:56 -07007108}
7109
François Gaffieaaac0fd2018-11-22 17:56:39 +01007110void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7111 bool on,
7112 const sp<AudioOutputDescriptor>& outputDesc,
7113 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007114 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007115{
jiabin9a3361e2019-10-01 09:38:30 -07007116 if (deviceTypes.empty()) {
7117 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007118 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007119 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007120 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007121 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007122 if (curves.canBeMuted() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007123 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE) ||
7124 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7125 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007126 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007127 }
7128 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007129 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7130 // ignored
7131 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007132 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007133 if (!outputDesc->isMuted(volumeSource)) {
7134 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007135 return;
7136 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007137 if (outputDesc->decMuteCount(volumeSource) == 0) {
7138 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007139 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007140 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007141 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007142 delayMs);
7143 }
7144 }
7145}
7146
François Gaffie53615e22015-03-19 09:24:12 +01007147bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7148{
François Gaffiec005e562018-11-06 15:04:49 +01007149 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007150 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7151 return true;
7152 }
7153
7154 // has known usage?
7155 switch (paa->usage) {
7156 case AUDIO_USAGE_UNKNOWN:
7157 case AUDIO_USAGE_MEDIA:
7158 case AUDIO_USAGE_VOICE_COMMUNICATION:
7159 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7160 case AUDIO_USAGE_ALARM:
7161 case AUDIO_USAGE_NOTIFICATION:
7162 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7163 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7164 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7165 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7166 case AUDIO_USAGE_NOTIFICATION_EVENT:
7167 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7168 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7169 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7170 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007171 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007172 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007173 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007174 case AUDIO_USAGE_EMERGENCY:
7175 case AUDIO_USAGE_SAFETY:
7176 case AUDIO_USAGE_VEHICLE_STATUS:
7177 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007178 break;
7179 default:
7180 return false;
7181 }
7182 return true;
7183}
7184
François Gaffie2110e042015-03-24 08:41:51 +01007185audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7186{
7187 return mEngine->getForceUse(usage);
7188}
7189
7190bool AudioPolicyManager::isInCall()
7191{
7192 return isStateInCall(mEngine->getPhoneState());
7193}
7194
7195bool AudioPolicyManager::isStateInCall(int state)
7196{
7197 return is_state_in_call(state);
7198}
7199
Eric Laurent74b71512019-11-06 17:21:57 -08007200bool AudioPolicyManager::isCallAudioAccessible()
7201{
7202 audio_mode_t mode = mEngine->getPhoneState();
7203 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007204 || (mode == AUDIO_MODE_CALL_SCREEN)
7205 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007206}
7207
Eric Laurentd60560a2015-04-10 11:31:20 -07007208void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7209{
7210 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007211 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007212 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007213 sourceDesc->sinkDevice()->equals(deviceDesc))
7214 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007215 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007216 }
7217 }
7218
7219 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7220 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7221 bool release = false;
7222 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7223 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7224 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7225 source->ext.device.type == deviceDesc->type()) {
7226 release = true;
7227 }
7228 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007229 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007230 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7231 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7232 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007233 sink->ext.device.type == deviceDesc->type() &&
7234 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7235 || strncmp(sink->ext.device.address, address,
7236 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007237 release = true;
7238 }
7239 }
7240 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007241 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7242 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007243 }
7244 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007245
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007246 mInputs.clearSessionRoutesForDevice(deviceDesc);
7247
Francois Gaffie716e1432019-01-14 16:58:59 +01007248 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007249}
7250
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007251void AudioPolicyManager::modifySurroundFormats(
7252 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007253 std::unordered_set<audio_format_t> enforcedSurround(
7254 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007255 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7256 for (const auto& pair : mConfig.getSurroundFormats()) {
7257 allSurround.insert(pair.first);
7258 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7259 }
Phil Burk09bc4612016-02-24 15:58:15 -08007260
7261 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7262 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007263 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007264 // This is the resulting set of formats depending on the surround mode:
7265 // 'all surround' = allSurround
7266 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7267 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7268 // 'manual surround' = mManualSurroundFormats
7269 // AUTO: formats v 'enforced surround'
7270 // ALWAYS: formats v 'all surround' v 'enforced surround'
7271 // NEVER: formats ^ 'non-surround'
7272 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007273
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007274 std::unordered_set<audio_format_t> formatSet;
7275 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7276 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007277 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007278 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007279 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007280 formatSet.insert(*formatIter);
7281 }
7282 }
7283 } else {
7284 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7285 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007286 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007287
jiabin81772902018-04-02 17:52:27 -07007288 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007289 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007290 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7291 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7292 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007293 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007294 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7295 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7296 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007297 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007298 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007299 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007300 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007301 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007302 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007303}
7304
jiabin06e4bab2019-07-29 10:13:34 -07007305void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7306 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007307 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7308 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7309
7310 // If NEVER, then remove support for channelMasks > stereo.
7311 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007312 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7313 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007314 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007315 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007316 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007317 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007318 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007319 }
7320 }
jiabin81772902018-04-02 17:52:27 -07007321 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7322 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7323 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007324 bool supports5dot1 = false;
7325 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007326 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007327 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7328 supports5dot1 = true;
7329 break;
7330 }
7331 }
7332 // If not then add 5.1 support.
7333 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007334 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007335 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007336 }
Phil Burk09bc4612016-02-24 15:58:15 -08007337 }
7338}
7339
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007340void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007341 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007342 AudioProfileVector &profiles)
7343{
7344 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007345 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007346
François Gaffie112b0af2015-11-19 16:13:25 +01007347 // Format MUST be checked first to update the list of AudioProfile
7348 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007349 reply = mpClientInterface->getParameters(
7350 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007351 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007352 AudioParameter repliedParameters(reply);
7353 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007354 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007355 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7356 return;
7357 }
Phil Burk09bc4612016-02-24 15:58:15 -08007358 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007359 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007360 if (device == AUDIO_DEVICE_OUT_HDMI
7361 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007362 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007363 }
jiabin3e277cc2019-09-10 14:27:34 -07007364 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007365 }
François Gaffie112b0af2015-11-19 16:13:25 +01007366
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007367 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007368 ChannelMaskSet channelMasks;
7369 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007370 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007371 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007372
7373 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007374 reply = mpClientInterface->getParameters(
7375 ioHandle,
7376 requestedParameters.toString() + ";" +
7377 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007378 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007379 AudioParameter repliedParameters(reply);
7380 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007381 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007382 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007383 }
7384 }
7385 if (profiles.hasDynamicChannelsFor(format)) {
7386 reply = mpClientInterface->getParameters(ioHandle,
7387 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007388 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007389 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007390 AudioParameter repliedParameters(reply);
7391 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007392 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007393 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007394 if (device == AUDIO_DEVICE_OUT_HDMI
7395 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007396 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007397 }
François Gaffie112b0af2015-11-19 16:13:25 +01007398 }
7399 }
jiabin3e277cc2019-09-10 14:27:34 -07007400 addDynamicAudioProfileAndSort(
7401 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007402 }
7403}
Eric Laurentd60560a2015-04-10 11:31:20 -07007404
Mikhail Naganovdc769682018-05-04 15:34:08 -07007405status_t AudioPolicyManager::installPatch(const char *caller,
7406 audio_patch_handle_t *patchHandle,
7407 AudioIODescriptorInterface *ioDescriptor,
7408 const struct audio_patch *patch,
7409 int delayMs)
7410{
7411 ssize_t index = mAudioPatches.indexOfKey(
7412 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7413 *patchHandle : ioDescriptor->getPatchHandle());
7414 sp<AudioPatch> patchDesc;
7415 status_t status = installPatch(
7416 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7417 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007418 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007419 }
7420 return status;
7421}
7422
7423status_t AudioPolicyManager::installPatch(const char *caller,
7424 ssize_t index,
7425 audio_patch_handle_t *patchHandle,
7426 const struct audio_patch *patch,
7427 int delayMs,
7428 uid_t uid,
7429 sp<AudioPatch> *patchDescPtr)
7430{
7431 sp<AudioPatch> patchDesc;
7432 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7433 if (index >= 0) {
7434 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007435 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007436 }
7437
7438 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7439 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7440 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7441 if (status == NO_ERROR) {
7442 if (index < 0) {
7443 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007444 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007445 } else {
7446 patchDesc->mPatch = *patch;
7447 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007448 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007449 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007450 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007451 }
7452 nextAudioPortGeneration();
7453 mpClientInterface->onAudioPatchListUpdate();
7454 }
7455 if (patchDescPtr) *patchDescPtr = patchDesc;
7456 return status;
7457}
7458
jiabinbce0c1d2020-10-05 11:20:18 -07007459bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7460{
7461 const TrackClientVector activeClients = output->getActiveClients();
7462 if (activeClients.empty()) {
7463 return true;
7464 }
7465 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7466 if (index < 0) {
7467 ALOGE("%s, no audio patch found while there are active clients on output %d",
7468 __func__, output->getId());
7469 return false;
7470 }
7471 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7472 DeviceVector routedDevices;
7473 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7474 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7475 patchDesc->mPatch.sinks[i].id);
7476 if (device == nullptr) {
7477 ALOGE("%s, no audio device found with id(%d)",
7478 __func__, patchDesc->mPatch.sinks[i].id);
7479 return false;
7480 }
7481 routedDevices.add(device);
7482 }
7483 for (const auto& client : activeClients) {
7484 // TODO: b/175343099 only travel the valid client
7485 sp<DeviceDescriptor> preferredDevice =
7486 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7487 if (mEngine->getOutputDevicesForAttributes(
7488 client->attributes(), preferredDevice, false) == routedDevices) {
7489 return false;
7490 }
7491 }
7492 return true;
7493}
7494
7495sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007496 const sp<IOProfile>& profile, const DeviceVector& devices,
7497 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007498{
7499 for (const auto& device : devices) {
7500 // TODO: This should be checking if the profile supports the device combo.
7501 if (!profile->supportsDevice(device)) {
7502 return nullptr;
7503 }
7504 }
7505 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7506 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007507 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007508 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7509 if (status != NO_ERROR) {
7510 return nullptr;
7511 }
7512
7513 // Here is where the out_set_parameters() for card & device gets called
7514 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7515 const audio_devices_t deviceType = device->type();
7516 const String8 &address = String8(device->address().c_str());
7517 if (!address.isEmpty()) {
7518 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7519 mpClientInterface->setParameters(output, String8(param));
7520 free(param);
7521 }
7522 updateAudioProfiles(device, output, profile->getAudioProfiles());
7523 if (!profile->hasValidAudioProfile()) {
7524 ALOGW("%s() missing param", __func__);
7525 desc->close();
7526 return nullptr;
7527 } else if (profile->hasDynamicAudioProfile()) {
7528 desc->close();
7529 output = AUDIO_IO_HANDLE_NONE;
7530 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7531 profile->pickAudioProfile(
7532 config.sample_rate, config.channel_mask, config.format);
7533 config.offload_info.sample_rate = config.sample_rate;
7534 config.offload_info.channel_mask = config.channel_mask;
7535 config.offload_info.format = config.format;
7536
Eric Laurentb4f42a92022-01-17 17:37:31 +01007537 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007538 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7539 if (status != NO_ERROR) {
7540 return nullptr;
7541 }
7542 }
7543
7544 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007545
jiabinbce0c1d2020-10-05 11:20:18 -07007546 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7547 sp<AudioPolicyMix> policyMix;
7548 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7549 policyMix->setOutput(desc);
7550 desc->mPolicyMix = policyMix;
7551 } else {
7552 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7553 address.string());
7554 }
7555
Eric Laurentb4f42a92022-01-17 17:37:31 +01007556 } else if (hasPrimaryOutput() && profile->getModule()
7557 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7558 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7559 // no duplicated output for:
7560 // - direct outputs
7561 // - outputs used by dynamic policy mixes
7562 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007563 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7564
7565 //TODO: configure audio effect output stage here
7566
7567 // open a duplicating output thread for the new output and the primary output
7568 sp<SwAudioOutputDescriptor> dupOutputDesc =
7569 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7570 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7571 if (status == NO_ERROR) {
7572 // add duplicated output descriptor
7573 addOutput(duplicatedOutput, dupOutputDesc);
7574 } else {
7575 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7576 mPrimaryOutput->mIoHandle, output);
7577 desc->close();
7578 removeOutput(output);
7579 nextAudioPortGeneration();
7580 return nullptr;
7581 }
7582 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007583 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7584 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7585 mPrimaryOutput = desc;
7586 }
jiabinbce0c1d2020-10-05 11:20:18 -07007587 return desc;
7588}
7589
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007590} // namespace android