blob: 5d5e4cd0ded881753aef72f7742628ffed06e0e6 [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) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100143 if (port.ext.getTag() != AudioPortExt::device) {
144 return BAD_VALUE;
145 }
146 audio_devices_t device_type;
147 std::string device_address;
148 if (status_t status = aidl2legacy_AudioDevice_audio_device(
149 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
150 status != OK) {
151 return status;
152 };
153 const char* device_name = port.name.c_str();
154 // connect/disconnect only 1 device at a time
155 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
156 return BAD_VALUE;
157
158 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
159 device_type, device_address.c_str(), device_name, encodedFormat,
160 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000161 if (device == nullptr) {
162 return INVALID_OPERATION;
163 }
164 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
165 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
166 }
167 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100168}
169
François Gaffie11d30102018-11-02 16:09:09 +0100170status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800171 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100172 const char* device_address,
173 const char* device_name,
174 audio_format_t encodedFormat) {
175 media::AudioPort aidlPort;
176 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
177 status == OK) {
178 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
179 } else {
180 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
181 return status;
182 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700183}
Paul McLeane743a472015-01-28 11:07:31 -0800184
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700185status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
186 audio_policy_dev_state_t state)
187{
Eric Laurente552edb2014-03-10 17:42:56 -0700188 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700189 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700190 SortedVector <audio_io_handle_t> outputs;
191
François Gaffie11d30102018-11-02 16:09:09 +0100192 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700193
Eric Laurente552edb2014-03-10 17:42:56 -0700194 // save a copy of the opened output descriptors before any output is opened or closed
195 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
196 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100197
198 bool wasLeUnicastActive = isLeUnicastActive();
199
Eric Laurente552edb2014-03-10 17:42:56 -0700200 switch (state)
201 {
202 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800203 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700204 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100205 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700206 return INVALID_OPERATION;
207 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800208 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700209 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700210
Eric Laurente552edb2014-03-10 17:42:56 -0700211 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200212 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700213 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700214 }
215
François Gaffie44481e72016-04-20 07:49:57 +0200216 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
217 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100218 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200219
François Gaffie11d30102018-11-02 16:09:09 +0100220 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
221 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200222
Francois Gaffie716e1432019-01-14 16:58:59 +0100223 mHwModules.cleanUpForDevice(device);
224
François Gaffie11d30102018-11-02 16:09:09 +0100225 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700226 return INVALID_OPERATION;
227 }
François Gaffie2110e042015-03-24 08:41:51 +0100228
jiabin1c4794b2020-05-05 10:08:05 -0700229 // Populate encapsulation information when a output device is connected.
230 device->setEncapsulationInfoFromHal(mpClientInterface);
231
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700232 // outputs should never be empty here
233 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
234 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100235 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800236
Eric Laurent3ae5f312015-02-03 17:12:08 -0800237 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700238 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700239 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700240 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100241 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700242 return INVALID_OPERATION;
243 }
244
François Gaffie11d30102018-11-02 16:09:09 +0100245 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700246
Paul McLeane743a472015-01-28 11:07:31 -0800247 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100248 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700249
Eric Laurente552edb2014-03-10 17:42:56 -0700250 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100251 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700252
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100253 mOutputs.clearSessionRoutesForDevice(device);
254
François Gaffie11d30102018-11-02 16:09:09 +0100255 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100256
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800257 // Reset active device codec
258 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
259
Kriti Dangef6be8f2020-11-05 11:58:19 +0100260 // remove device from mReportedFormatsMap cache
261 mReportedFormatsMap.erase(device);
262
jiabina84c3d32022-12-02 18:59:55 +0000263 // remove preferred mixer configurations
264 mPreferredMixerAttrInfos.erase(device->getId());
265
Eric Laurente552edb2014-03-10 17:42:56 -0700266 } break;
267
268 default:
François Gaffie11d30102018-11-02 16:09:09 +0100269 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700270 return BAD_VALUE;
271 }
272
Eric Laurent736a1022019-03-27 18:28:46 -0700273 // Propagate device availability to Engine
274 setEngineDeviceConnectionState(device, state);
275
Eric Laurentae970022019-01-29 14:25:04 -0800276 // No need to evaluate playback routing when connecting a remote submix
277 // output device used by a dynamic policy of type recorder as no
278 // playback use case is affected.
279 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700280 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800281 for (audio_io_handle_t output : outputs) {
282 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800283 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
284 if (policyMix != nullptr
285 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700286 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800287 doCheckForDeviceAndOutputChanges = false;
288 break;
289 }
290 }
291 }
292
293 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700294 // outputs must be closed after checkOutputForAllStrategies() is executed
295 if (!outputs.isEmpty()) {
296 for (audio_io_handle_t output : outputs) {
297 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100298 // close unused outputs after device disconnection or direct outputs that have
299 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200300 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200301 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
302 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200303 (desc->mDirectOpenCount == 0))
304 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
305 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200306 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700307 closeOutput(output);
308 }
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700310 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
311 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700312 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700313 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800314 };
315
316 if (doCheckForDeviceAndOutputChanges) {
317 checkForDeviceAndOutputChanges(checkCloseOutputs);
318 } else {
319 checkCloseOutputs();
320 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100321 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700322 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100323 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700324 const DeviceVector activeMediaDevices =
325 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700326 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700327 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530328 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
329 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100330 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700331 // do not force device change on duplicated output because if device is 0, it will
332 // also force a device 0 for the two outputs it is duplicated to which may override
333 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100334 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100335 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700336 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700337 // always force when disconnecting (a non-duplicated device)
338 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100339 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700340 }
jiabinbce0c1d2020-10-05 11:20:18 -0700341 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000342 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700343 desc->supportsDevicesForPlayback(activeMediaDevices)) {
344 // Reopen the output to query the dynamic profiles when there is not active
345 // clients or all active clients will be rerouted. Otherwise, set the flag
346 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
347 // can be reopened to query dynamic profiles when all clients are inactive.
348 if (areAllActiveTracksRerouted(desc)) {
349 outputsToReopen.push_back(mOutputs.keyAt(i));
350 } else {
351 desc->mPendingReopenToQueryProfiles = true;
352 }
353 }
354 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
355 // Clear the flag that previously set for re-querying profiles.
356 desc->mPendingReopenToQueryProfiles = false;
357 }
358 }
359 for (const auto& output : outputsToReopen) {
360 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
361 closeOutput(output);
362 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700363 }
364
Eric Laurentd60560a2015-04-10 11:31:20 -0700365 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100366 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700367 }
368
Eric Laurent96d1dda2022-03-14 17:14:19 +0100369 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
370
Eric Laurent72aa32f2014-05-30 18:51:48 -0700371 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700372 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700373 } // end if is output device
374
Eric Laurente552edb2014-03-10 17:42:56 -0700375 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700376 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100377 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700378 switch (state)
379 {
380 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700381 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700382 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700384 return INVALID_OPERATION;
385 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700386
387 if (mAvailableInputDevices.add(device) < 0) {
388 return NO_MEMORY;
389 }
390
François Gaffie44481e72016-04-20 07:49:57 +0200391 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
392 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100393 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200394
Eric Laurent0dd51852019-04-19 18:18:58 -0700395 if (checkInputsForDevice(device, state) != NO_ERROR) {
396 mAvailableInputDevices.remove(device);
397
François Gaffie11d30102018-11-02 16:09:09 +0100398 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100399
400 mHwModules.cleanUpForDevice(device);
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 return INVALID_OPERATION;
403 }
404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700406
407 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700408 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700409 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100410 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700411 return INVALID_OPERATION;
412 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700413
François Gaffie11d30102018-11-02 16:09:09 +0100414 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700415
416 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100417 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700418
François Gaffie11d30102018-11-02 16:09:09 +0100419 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700420
421 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100422
423 // remove device from mReportedFormatsMap cache
424 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700425 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700426
427 default:
François Gaffie11d30102018-11-02 16:09:09 +0100428 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700429 return BAD_VALUE;
430 }
431
Eric Laurent736a1022019-03-27 18:28:46 -0700432 // Propagate device availability to Engine
433 setEngineDeviceConnectionState(device, state);
434
Eric Laurent0dd51852019-04-19 18:18:58 -0700435 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700436 // As the input device list can impact the output device selection, update
437 // getDeviceForStrategy() cache
438 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700439
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100440 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200441 // Reconnect Audio Source
442 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
443 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
444 checkAudioSourceForAttributes(attributes);
445 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700446 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100447 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700448 }
449
Eric Laurentb52c1522014-05-20 11:27:36 -0700450 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700451 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700452 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700453
François Gaffie11d30102018-11-02 16:09:09 +0100454 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700455 return BAD_VALUE;
456}
457
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100458status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
459 const char* device_name,
460 media::AudioPort* aidlPort) {
461 DeviceDescriptorBase devDescr(device, device_address);
462 devDescr.setName(device_name);
463 return devDescr.writeToParcelable(aidlPort);
464}
465
Eric Laurent736a1022019-03-27 18:28:46 -0700466void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
467 audio_policy_dev_state_t state) {
468
469 // the Engine does not have to know about remote submix devices used by dynamic audio policies
470 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
471 return;
472 }
473 mEngine->setDeviceConnectionState(device, state);
474}
475
476
Eric Laurente0720872014-03-11 09:30:41 -0700477audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100478 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700479{
Eric Laurent634b7142016-04-20 13:48:02 -0700480 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800481 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
482 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700483 (strlen(device_address) != 0)/*matchAddress*/);
484
485 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100486 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700487 device, device_address);
488 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
489 }
François Gaffie53615e22015-03-19 09:24:12 +0100490
Eric Laurent3a4311c2014-03-17 12:00:47 -0700491 DeviceVector *deviceVector;
492
Eric Laurente552edb2014-03-10 17:42:56 -0700493 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700494 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700495 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700496 deviceVector = &mAvailableInputDevices;
497 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100498 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700499 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700500 }
Eric Laurent634b7142016-04-20 13:48:02 -0700501
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800502 return (deviceVector->getDevice(
503 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700504 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800505}
506
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800507status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
508 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800509 const char *device_name,
510 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800511{
512 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700513 String8 reply;
514 AudioParameter param;
515 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
518 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800520 // connect/disconnect only 1 device at a time
521 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
522
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700524 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800526 // Nothing to do: device is not connected
527 return NO_ERROR;
528 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800530
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700531 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800532 // configure codecs.
533 // Handle two specific cases by sending a set parameter to
534 // configure A2DP codecs. No need to toggle device state.
535 // Case 1: A2DP active device switches from primary to primary
536 // module
537 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200538 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700539 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800540 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
541 if (availablePrimaryOutputDevices().contains(devDesc) &&
542 (module != 0 && module->getHandle() == primaryHandle)) {
543 reply = mpClientInterface->getParameters(
544 AUDIO_IO_HANDLE_NONE,
545 String8(AudioParameter::keyReconfigA2dpSupported));
546 AudioParameter repliedParameters(reply);
547 repliedParameters.getInt(
548 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
549 if (isReconfigA2dpSupported) {
550 const String8 key(AudioParameter::keyReconfigA2dp);
551 param.add(key, String8("true"));
552 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
553 devDesc->setEncodedFormat(encodedFormat);
554 return NO_ERROR;
555 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700556 }
557 }
cnx421bd2dcc42020-07-11 14:58:44 +0800558 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
559 for (size_t i = 0; i < mOutputs.size(); i++) {
560 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
561 // mute media strategies and delay device switch by the largest
562 // This avoid sending the music tail into the earpiece or headset.
563 setStrategyMute(musicStrategy, true, desc);
564 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
565 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
566 nullptr, true /*fromCache*/).types());
567 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800568 // Toggle the device state: UNAVAILABLE -> AVAILABLE
569 // This will force reading again the device configuration
570 status = setDeviceConnectionState(device,
571 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800572 device_address, device_name,
573 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800574 if (status != NO_ERROR) {
575 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
576 status);
577 return status;
578 }
579
580 status = setDeviceConnectionState(device,
581 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800582 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800583 if (status != NO_ERROR) {
584 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
585 status);
586 return status;
587 }
588
589 return NO_ERROR;
590}
591
Pattydd807582021-11-04 21:01:03 +0800592status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
593 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800594{
Pattydd807582021-11-04 21:01:03 +0800595 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800596 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800597 std::unordered_set<audio_format_t> formatSet;
598 sp<HwModule> primaryModule =
599 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700600 if (primaryModule == nullptr) {
601 ALOGE("%s() unable to get primary module", __func__);
602 return NO_INIT;
603 }
Pattydd807582021-11-04 21:01:03 +0800604
605 DeviceTypeSet audioDeviceSet;
606
607 switch(device) {
608 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
609 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
610 break;
611 case AUDIO_DEVICE_OUT_BLE_HEADSET:
612 audioDeviceSet = getAudioDeviceOutAllBleSet();
613 break;
614 default:
615 ALOGE("%s() device type 0x%08x not supported", __func__, device);
616 return BAD_VALUE;
617 }
618
jiabin9a3361e2019-10-01 09:38:30 -0700619 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800620 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800621 for (const auto& device : declaredDevices) {
622 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800623 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800624 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800625 return status;
626}
627
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100628DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
629{
630 DeviceVector rxSinkdevices{};
631 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
632 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
633 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
634 auto rxSinkDevice = rxSinkdevices.itemAt(0);
635 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
636 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
637 // retrieve Rx Source device descriptor
638 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
639 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
640
641 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
642 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
643 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
644 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
645 return DeviceVector(rxSinkDevice);
646 }
647 }
648 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
649 // the device returned is not necessarily reachable via this output
650 // (filter later by setOutputDevices())
651 return getNewOutputDevices(mPrimaryOutput, fromCache);
652}
653
654status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
655{
656 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
657 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
658 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
659 }
660 return INVALID_OPERATION;
661}
662
663status_t AudioPolicyManager::updateCallRoutingInternal(
664 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700665{
666 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100667 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700668 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700669 if(!hasPrimaryOutput() ||
670 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100671 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700672 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100673 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100674
Francois Gaffie716e1432019-01-14 16:58:59 +0100675 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100676 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100677 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100678
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100679 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100680 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700681
Francois Gaffie601801d2021-06-22 13:27:39 +0200682 disconnectTelephonyAudioSource(mCallRxSourceClient);
683 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700684
François Gaffie9eb18552018-11-05 10:33:26 +0100685 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700686 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100687 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700688 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100689 // retrieve Rx Source and Tx Sink device descriptors
690 sp<DeviceDescriptor> rxSourceDevice =
691 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
692 String8(),
693 AUDIO_FORMAT_DEFAULT);
694 sp<DeviceDescriptor> txSinkDevice =
695 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
696 String8(),
697 AUDIO_FORMAT_DEFAULT);
698
699 // RX and TX Telephony device are declared by Primary Audio HAL
700 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
701 (telephonyRxModule->getHalVersionMajor() >= 3)) {
702 if (rxSourceDevice == 0 || txSinkDevice == 0) {
703 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100704 ALOGE("%s() no telephony Tx and/or RX device", __func__);
705 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100706 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100707 // createAudioPatchInternal now supports both HW / SW bridging
708 createRxPatch = true;
709 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100710 } else {
711 // If the RX device is on the primary HW module, then use legacy routing method for
712 // voice calls via setOutputDevice() on primary output.
713 // Otherwise, create two audio patches for TX and RX path.
714 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
715 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700716 // If the TX device is also on the primary HW module, setOutputDevice() will take care
717 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100718 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
719 (txSinkDevice != 0);
720 }
721 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
722 // Otherwise, create two audio patches for TX and RX path.
723 if (!createRxPatch) {
724 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700725 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200726 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800727 // If the TX device is on the primary HW module but RX device is
728 // on other HW module, SinkMetaData of telephony input should handle it
729 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700730 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700731 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100732 // terminate active capture if on the same HW module as the call TX source device
733 // FIXME: would be better to refine to only inputs whose profile connects to the
734 // call TX device but this information is not in the audio patch and logic here must be
735 // symmetric to the one in startInput()
736 for (const auto& activeDesc : mInputs.getActiveInputs()) {
737 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
738 closeActiveClients(activeDesc);
739 }
740 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200741 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800742 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100743 if (waitMs != nullptr) {
744 *waitMs = muteWaitMs;
745 }
746 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800747}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700748
Mikhail Naganov100f0122018-11-29 11:22:16 -0800749bool AudioPolicyManager::isDeviceOfModule(
750 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
751 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
752 if (module != 0) {
753 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
754 .indexOf(devDesc) != NAME_NOT_FOUND
755 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
756 .indexOf(devDesc) != NAME_NOT_FOUND;
757 }
758 return false;
759}
760
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200761void AudioPolicyManager::connectTelephonyRxAudioSource()
762{
Francois Gaffie601801d2021-06-22 13:27:39 +0200763 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200764 const struct audio_port_config source = {
765 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
766 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
767 };
768 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200769 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
770 ALOGE_IF(mCallRxSourceClient == nullptr,
771 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200772}
773
Francois Gaffie601801d2021-06-22 13:27:39 +0200774void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200775{
Francois Gaffie601801d2021-06-22 13:27:39 +0200776 if (clientDesc == nullptr) {
777 return;
778 }
779 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
780 "%s error stopping audio source", __func__);
781 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200782}
783
784void AudioPolicyManager::connectTelephonyTxAudioSource(
785 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
786 uint32_t delayMs)
787{
Francois Gaffie601801d2021-06-22 13:27:39 +0200788 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200789 if (srcDevice == nullptr || sinkDevice == nullptr) {
790 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
791 return;
792 }
793 PatchBuilder patchBuilder;
794 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
795 ALOGV("%s between source %s and sink %s", __func__,
796 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200797 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200798 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
799
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200800 struct audio_port_config source = {};
801 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200802 mCallTxSourceClient = new InternalSourceClientDescriptor(
803 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200804 mCommunnicationStrategy, toVolumeSource(aa));
805 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
806 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200807 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
808 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200809 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
810 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200811 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200812 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200813}
814
Eric Laurente0720872014-03-11 09:30:41 -0700815void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700816{
817 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100818 // store previous phone state for management of sonification strategy below
819 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100820 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100821
822 if (mEngine->setPhoneState(state) != NO_ERROR) {
823 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700824 return;
825 }
François Gaffie2110e042015-03-24 08:41:51 +0100826 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700827 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700828 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700829 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800830 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700831 }
832
François Gaffie2110e042015-03-24 08:41:51 +0100833 /**
834 * Switching to or from incall state or switching between telephony and VoIP lead to force
835 * routing command.
836 */
Eric Laurent74b71512019-11-06 17:21:57 -0800837 bool force = ((isStateInCall(oldState) != isStateInCall(state))
838 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700839
840 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700841 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700842
Eric Laurente552edb2014-03-10 17:42:56 -0700843 int delayMs = 0;
844 if (isStateInCall(state)) {
845 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100846 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
847 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700848 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700849 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700850 // mute media and sonification strategies and delay device switch by the largest
851 // latency of any output where either strategy is active.
852 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100853 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
854 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
855 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700856 (delayMs < (int)desc->latency()*2)) {
857 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700858 }
François Gaffiec005e562018-11-06 15:04:49 +0100859 setStrategyMute(musicStrategy, true, desc);
860 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
861 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
862 nullptr, true /*fromCache*/).types());
863 setStrategyMute(sonificationStrategy, true, desc);
864 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
865 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
866 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700867 }
868 }
869
Eric Laurent87ffa392015-05-22 10:32:38 -0700870 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700871 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100872 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700873 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100874 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
875 // force routing command to audio hardware when ending call
876 // even if no device change is needed
877 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
878 rxDevices = mPrimaryOutput->devices();
879 }
880 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200881 disconnectTelephonyAudioSource(mCallRxSourceClient);
882 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100883 }
François Gaffie11d30102018-11-02 16:09:09 +0100884 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700885 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700886 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700887
888 // reevaluate routing on all outputs in case tracks have been started during the call
889 for (size_t i = 0; i < mOutputs.size(); i++) {
890 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100891 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200892 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
893 bool forceRouting = !newDevices.isEmpty();
894 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
895 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700896 }
897 }
898
Eric Laurent96d1dda2022-03-14 17:14:19 +0100899 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
900
Eric Laurente552edb2014-03-10 17:42:56 -0700901 if (isStateInCall(state)) {
902 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700903 // force reevaluating accessibility routing when call starts
904 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700905 }
906
907 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100908 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
909 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700910}
911
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700912audio_mode_t AudioPolicyManager::getPhoneState() {
913 return mEngine->getPhoneState();
914}
915
Eric Laurente0720872014-03-11 09:30:41 -0700916void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100917 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700918{
François Gaffie2110e042015-03-24 08:41:51 +0100919 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700920 if (config == mEngine->getForceUse(usage)) {
921 return;
922 }
Eric Laurente552edb2014-03-10 17:42:56 -0700923
François Gaffie2110e042015-03-24 08:41:51 +0100924 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
925 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
926 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700927 }
François Gaffie2110e042015-03-24 08:41:51 +0100928 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
929 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
930 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700931
932 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700933 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800934
Eric Laurent22fcda22019-05-17 16:28:47 -0700935 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
936 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
937 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
938 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
939 }
940
Eric Laurentdc462862016-07-19 12:29:53 -0700941 //FIXME: workaround for truncated touch sounds
942 // to be removed when the problem is handled by system UI
943 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700944 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
945 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
946 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700947
948 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100949 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700950}
951
Eric Laurente0720872014-03-11 09:30:41 -0700952void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700953{
954 ALOGV("setSystemProperty() property %s, value %s", property, value);
955}
956
Dorin Drimusecc9f422022-03-09 17:57:40 +0100957// Find an MSD output profile compatible with the parameters passed.
958// When "directOnly" is set, restrict search to profiles for direct outputs.
959sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
960 const DeviceVector& devices,
961 uint32_t samplingRate,
962 audio_format_t format,
963 audio_channel_mask_t channelMask,
964 audio_output_flags_t flags,
965 bool directOnly)
966{
967 flags = getRelevantFlags(flags, directOnly);
968
969 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
970 if (msdModule != nullptr) {
971 // for the msd module check if there are patches to the output devices
972 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
973 HwModuleCollection modules;
974 modules.add(msdModule);
975 return searchCompatibleProfileHwModules(
976 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
977 flags, directOnly);
978 }
979 }
980 return nullptr;
981}
982
Michael Chana94fbb22018-04-24 14:31:19 +1000983// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
984// search to profiles for direct outputs.
985sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100986 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000987 uint32_t samplingRate,
988 audio_format_t format,
989 audio_channel_mask_t channelMask,
990 audio_output_flags_t flags,
991 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700992{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100993 flags = getRelevantFlags(flags, directOnly);
994
995 return searchCompatibleProfileHwModules(
996 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
997}
998
999audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1000 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001001 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001002 // only retain flags that will drive the direct output profile selection
1003 // if explicitly requested
1004 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001005 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001006 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1007 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001008 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001009 return flags;
1010}
Eric Laurent861a6282015-05-18 15:40:16 -07001011
Dorin Drimusecc9f422022-03-09 17:57:40 +01001012sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1013 const HwModuleCollection& hwModules,
1014 const DeviceVector& devices,
1015 uint32_t samplingRate,
1016 audio_format_t format,
1017 audio_channel_mask_t channelMask,
1018 audio_output_flags_t flags,
1019 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001020 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001021 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001022 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001023 if (!curProfile->isCompatibleProfile(devices,
1024 samplingRate, NULL /*updatedSamplingRate*/,
1025 format, NULL /*updatedFormat*/,
1026 channelMask, NULL /*updatedChannelMask*/,
1027 flags)) {
1028 continue;
1029 }
1030 // reject profiles not corresponding to a device currently available
1031 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1032 continue;
1033 }
1034 // reject profiles if connected device does not support codec
1035 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1036 continue;
1037 }
1038 if (!directOnly) {
1039 return curProfile;
1040 }
1041
1042 // when searching for direct outputs, if several profiles are compatible, give priority
1043 // to one with offload capability
1044 if (profile != 0 &&
1045 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001046 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001047 }
1048 profile = curProfile;
1049 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1050 break;
1051 }
Eric Laurente552edb2014-03-10 17:42:56 -07001052 }
1053 }
Eric Laurent861a6282015-05-18 15:40:16 -07001054 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001055}
1056
Eric Laurentfa0f6742021-08-17 18:39:44 +02001057sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001058 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001059{
1060 for (const auto& hwModule : mHwModules) {
1061 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001062 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001063 continue;
1064 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001065 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001066 // reject profiles not corresponding to a device currently available
1067 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1068 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1069 continue;
1070 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001071 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1072 != devices.size()) {
1073 continue;
1074 }
1075 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001076 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1077 return curProfile;
1078 }
1079 }
1080 return nullptr;
1081}
1082
Eric Laurentf4e63452017-11-06 19:31:46 +00001083audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001084{
François Gaffiec005e562018-11-06 15:04:49 +01001085 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001086
1087 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1088 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1089 // format, flags, etc. This may result in some discrepancy for functions that utilize
1090 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1091 // and AudioSystem::getOutputSamplingRate().
1092
François Gaffie11d30102018-11-02 16:09:09 +01001093 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001094 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001095
François Gaffie11d30102018-11-02 16:09:09 +01001096 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1097 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001098 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001099}
1100
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001101status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1102 const audio_attributes_t *srcAttr,
1103 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001104{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001105 if (srcAttr != NULL) {
1106 if (!isValidAttributes(srcAttr)) {
1107 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1108 __func__,
1109 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1110 srcAttr->tags);
1111 return BAD_VALUE;
1112 }
1113 *dstAttr = *srcAttr;
1114 } else {
1115 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1116 ALOGE("%s: invalid stream type", __func__);
1117 return BAD_VALUE;
1118 }
François Gaffiec005e562018-11-06 15:04:49 +01001119 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001120 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001121
1122 // Only honor audibility enforced when required. The client will be
1123 // forced to reconnect if the forced usage changes.
1124 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001125 dstAttr->flags = static_cast<audio_flags_mask_t>(
1126 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001127 }
1128
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001129 return NO_ERROR;
1130}
1131
Kevin Rocard153f92d2018-12-18 18:33:28 -08001132status_t AudioPolicyManager::getOutputForAttrInt(
1133 audio_attributes_t *resultAttr,
1134 audio_io_handle_t *output,
1135 audio_session_t session,
1136 const audio_attributes_t *attr,
1137 audio_stream_type_t *stream,
1138 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001139 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001140 audio_output_flags_t *flags,
1141 audio_port_handle_t *selectedDeviceId,
1142 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001143 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001144 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001145 bool *isSpatialized,
1146 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001147{
François Gaffiec005e562018-11-06 15:04:49 +01001148 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001149 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001150 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001151 const sp<DeviceDescriptor> requestedDevice =
1152 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1153
Eric Laurent8a1095a2019-11-08 14:44:16 -08001154 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001155 *isSpatialized = false;
1156
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001157 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1158 if (status != NO_ERROR) {
1159 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001160 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001161 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001162 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001163 }
François Gaffiec005e562018-11-06 15:04:49 +01001164 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001165
François Gaffiec005e562018-11-06 15:04:49 +01001166 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1167 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001168
Kevin Rocard153f92d2018-12-18 18:33:28 -08001169 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1170 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1171 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001172 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001173 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1174 .channel_mask = config->channel_mask,
1175 .format = config->format,
1176 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001177 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
1178 primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001179 if (status != OK) {
1180 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001181 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001182
Kevin Rocard153f92d2018-12-18 18:33:28 -08001183 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001184 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001185
1186 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001187 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1188 && !audio_is_linear_pcm(config->format)) {
1189 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001190 return BAD_VALUE;
1191 }
1192 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001193 sp<DeviceDescriptor> deviceDesc =
1194 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1195 primaryMix->mDeviceAddress,
1196 AUDIO_FORMAT_DEFAULT);
1197 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001198 bool tryDirectForFlags = policyDesc == nullptr ||
1199 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1200 // if a direct output can be opened to deliver the track's multi-channel content to the
1201 // output rather than being downmixed by the primary output, then use this direct
1202 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1203 // mix.
1204 bool tryDirectForChannelMask = policyDesc != nullptr
1205 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1206 audio_channel_count_from_out_mask(config->channel_mask));
1207 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001208 audio_io_handle_t newOutput;
1209 status = openDirectOutput(
1210 *stream, session, config,
1211 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1212 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001213 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001214 policyDesc = mOutputs.valueFor(newOutput);
1215 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001216 } else if (tryDirectForFlags) {
1217 policyDesc = nullptr;
1218 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001219 }
1220 if (policyDesc != nullptr) {
1221 policyDesc->mPolicyMix = primaryMix;
1222 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001223 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001224
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001225 ALOGV("getOutputForAttr() returns output %d", *output);
1226 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1227 *outputType = API_OUT_MIX_PLAYBACK;
1228 } else {
1229 *outputType = API_OUTPUT_LEGACY;
1230 }
1231 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001232 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001233 }
François Gaffiec005e562018-11-06 15:04:49 +01001234 // Virtual sources must always be dynamicaly or explicitly routed
1235 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1236 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1237 return BAD_VALUE;
1238 }
1239 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1240 // in order to let the choice of the order to future vendor engine
1241 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001242
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001243 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001244 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001245 }
1246
Nadav Barb2f18162018-07-18 13:01:53 +03001247 // Set incall music only if device was explicitly set, and fallback to the device which is
1248 // chosen by the engine if not.
1249 // FIXME: provide a more generic approach which is not device specific and move this back
1250 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001251 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001252 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001253 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001254 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001255 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001256 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001257 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001258 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001259 }
1260 }
1261
François Gaffiec005e562018-11-06 15:04:49 +01001262 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1263 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1264 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001265
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001266 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001267 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001268 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001269 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001270 ALOGV("%s() Using MSD devices %s instead of devices %s",
1271 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001272 } else {
1273 *output = AUDIO_IO_HANDLE_NONE;
1274 }
1275 }
1276 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001277 sp<PreferredMixerAttributesInfo> info = nullptr;
1278 if (outputDevices.size() == 1) {
1279 info = getPreferredMixerAttributesInfo(
1280 outputDevices.itemAt(0)->getId(),
1281 mEngine->getProductStrategyForAttributes(*resultAttr));
1282 if (info != nullptr && info->getUid() != uid && info->getActiveClientCount() == 0) {
1283 // Only use preferred mixer when the requested uid matched or
1284 // there is active client on preferred mixer.
1285 info = nullptr;
1286 }
1287 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001288 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001289 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabinc658e452022-10-21 20:52:21 +00001290 *isBitPerfect = (info != nullptr
1291 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
1292 && *output != AUDIO_IO_HANDLE_NONE);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001293 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001294 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001295 AudioProfileVector profiles;
1296 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1297 if (ret == NO_ERROR && !profiles.empty()) {
1298 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1299 : *profiles[0]->getChannels().begin();
1300 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1301 : *profiles[0]->getSampleRates().begin();
1302 config->format = profiles[0]->getFormat();
1303 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001304 return INVALID_OPERATION;
1305 }
Paul McLeanaa981192015-03-21 09:55:15 -07001306
François Gaffiec005e562018-11-06 15:04:49 +01001307 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001308 for (auto &outputDevice : outputDevices) {
1309 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1310 *selectedDeviceId = outputDevice->getId();
1311 break;
1312 }
1313 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001314
Eric Laurent8a1095a2019-11-08 14:44:16 -08001315 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1316 *outputType = API_OUTPUT_TELEPHONY_TX;
1317 } else {
1318 *outputType = API_OUTPUT_LEGACY;
1319 }
1320
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001321 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1322
1323 return NO_ERROR;
1324}
1325
1326status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1327 audio_io_handle_t *output,
1328 audio_session_t session,
1329 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001330 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001331 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001332 audio_output_flags_t *flags,
1333 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001334 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001335 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001336 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001337 bool *isSpatialized,
1338 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001339{
1340 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1341 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1342 return INVALID_OPERATION;
1343 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001344 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001345 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001346 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001347 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001348 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001349 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001350 const sp<DeviceDescriptor> requestedDevice =
1351 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1352
1353 // Prevent from storing invalid requested device id in clients
1354 const audio_port_handle_t sanitizedRequestedPortId =
1355 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1356 *selectedDeviceId = sanitizedRequestedPortId;
1357
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001358 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001359 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001360 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1361 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001362 if (status != NO_ERROR) {
1363 return status;
1364 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001365 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001366 if (secondaryOutputs != nullptr) {
1367 for (auto &secondaryMix : secondaryMixes) {
1368 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1369 if (outputDesc != nullptr &&
1370 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1371 secondaryOutputs->push_back(outputDesc->mIoHandle);
1372 weakSecondaryOutputDescs.push_back(outputDesc);
1373 }
1374 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001375 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001376
Eric Laurent8fc147b2018-07-22 19:13:55 -07001377 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001378 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001379 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001380 };
jiabin4ef93452019-09-10 14:29:54 -07001381 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001382
Eric Laurentc209fe42020-06-05 18:11:23 -07001383 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001384 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001385 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001386 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001387 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001388 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001389 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001390 std::move(weakSecondaryOutputDescs),
1391 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001392 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001393
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001394 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1395 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001396
Eric Laurente83b55d2014-11-14 10:06:21 -08001397 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001398}
1399
Eric Laurentc529cf62020-04-17 18:19:10 -07001400status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1401 audio_session_t session,
1402 const audio_config_t *config,
1403 audio_output_flags_t flags,
1404 const DeviceVector &devices,
1405 audio_io_handle_t *output) {
1406
1407 *output = AUDIO_IO_HANDLE_NONE;
1408
1409 // skip direct output selection if the request can obviously be attached to a mixed output
1410 // and not explicitly requested
1411 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1412 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1413 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1414 return NAME_NOT_FOUND;
1415 }
1416
1417 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1418 // This prevents creating an offloaded track and tearing it down immediately after start
1419 // when audioflinger detects there is an active non offloadable effect.
1420 // FIXME: We should check the audio session here but we do not have it in this context.
1421 // This may prevent offloading in rare situations where effects are left active by apps
1422 // in the background.
1423 sp<IOProfile> profile;
1424 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1425 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1426 profile = getProfileForOutput(
1427 devices, config->sample_rate, config->format, config->channel_mask,
1428 flags, true /* directOnly */);
1429 }
1430
1431 if (profile == nullptr) {
1432 return NAME_NOT_FOUND;
1433 }
1434
1435 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1436 for (size_t i = 0; i < mOutputs.size(); i++) {
1437 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1438 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1439 // reuse direct output if currently open by the same client
1440 // and configured with same parameters
1441 if ((config->sample_rate == desc->getSamplingRate()) &&
1442 (config->format == desc->getFormat()) &&
1443 (config->channel_mask == desc->getChannelMask()) &&
1444 (session == desc->mDirectClientSession)) {
1445 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001446 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001447 mOutputs.keyAt(i), session);
1448 *output = mOutputs.keyAt(i);
1449 return NO_ERROR;
1450 }
1451 }
1452 }
1453
1454 if (!profile->canOpenNewIo()) {
1455 return NAME_NOT_FOUND;
1456 }
1457
1458 sp<SwAudioOutputDescriptor> outputDesc =
1459 new SwAudioOutputDescriptor(profile, mpClientInterface);
1460
Michael Chan6fb34492020-12-08 15:44:49 +11001461 // An MSD patch may be using the only output stream that can service this request. Release
1462 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001463 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001464
Eric Laurentf1f22e72021-07-13 14:04:14 +02001465 status_t status =
1466 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001467
1468 // only accept an output with the requested parameters
1469 if (status != NO_ERROR ||
1470 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1471 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1472 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1473 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1474 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1475 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1476 config->channel_mask, outputDesc->getChannelMask());
1477 if (*output != AUDIO_IO_HANDLE_NONE) {
1478 outputDesc->close();
1479 }
1480 // fall back to mixer output if possible when the direct output could not be open
1481 if (audio_is_linear_pcm(config->format) &&
1482 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1483 return NAME_NOT_FOUND;
1484 }
1485 *output = AUDIO_IO_HANDLE_NONE;
1486 return BAD_VALUE;
1487 }
1488 outputDesc->mDirectOpenCount = 1;
1489 outputDesc->mDirectClientSession = session;
1490
1491 addOutput(*output, outputDesc);
1492 mPreviousOutputs = mOutputs;
1493 ALOGV("%s returns new direct output %d", __func__, *output);
1494 mpClientInterface->onAudioPortListUpdate();
1495 return NO_ERROR;
1496}
1497
François Gaffie11d30102018-11-02 16:09:09 +01001498audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1499 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001500 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001501 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001502 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001503 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001504 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001505 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001506 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001507{
Andy Hungc88b0642018-04-27 15:42:35 -07001508 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001509
jiabine375d412019-02-26 12:54:53 -08001510 // Discard haptic channel mask when forcing muting haptic channels.
1511 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001512 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1513 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001514
Eric Laurente552edb2014-03-10 17:42:56 -07001515 // open a direct output if required by specified parameters
1516 //force direct flag if offload flag is set: offloading implies a direct output stream
1517 // and all common behaviors are driven by checking only the direct flag
1518 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001519 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1520 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001521 }
Nadav Bar766fb022018-01-07 12:18:03 +02001522 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1523 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001524 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001525
1526 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1527
Eric Laurente83b55d2014-11-14 10:06:21 -08001528 // only allow deep buffering for music stream type
1529 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001530 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001531 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001532 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001533 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1534 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001535 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001536 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001537 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001538 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001539 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001540 audio_is_linear_pcm(config->format) &&
1541 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001542 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001543 AUDIO_OUTPUT_FLAG_DIRECT);
1544 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001545 }
Eric Laurente552edb2014-03-10 17:42:56 -07001546
Carter Hsua3abb402021-10-26 11:11:20 +08001547 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1548 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1549 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1550 }
1551
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001552 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001553 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001554 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001555 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001556 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001557 }
1558
Eric Laurentc529cf62020-04-17 18:19:10 -07001559 audio_config_t directConfig = *config;
1560 directConfig.channel_mask = channelMask;
1561 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1562 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001563 return output;
1564 }
1565
Eric Laurent14cbfca2016-03-17 09:42:16 -07001566 // A request for HW A/V sync cannot fallback to a mixed output because time
1567 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001568 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001569 return AUDIO_IO_HANDLE_NONE;
1570 }
1571
Eric Laurente552edb2014-03-10 17:42:56 -07001572 // ignoring channel mask due to downmix capability in mixer
1573
1574 // open a non direct output
1575
1576 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001577 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001578 // get which output is suitable for the specified stream. The actual
1579 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001580 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001581 if (prefMixerConfigInfo != nullptr) {
1582 for (audio_io_handle_t outputHandle : outputs) {
1583 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1584 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1585 output = outputHandle;
1586 break;
1587 }
1588 }
1589 if (output == AUDIO_IO_HANDLE_NONE) {
1590 // No output open with the preferred profile. Open a new one.
1591 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1592 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1593 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1594 config.format = prefMixerConfigInfo->getConfigBase().format;
1595 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1596 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1597 &config, prefMixerConfigInfo->getFlags());
1598 if (preferredOutput == nullptr) {
1599 ALOGE("%s failed to open output with preferred mixer config", __func__);
1600 } else {
1601 output = preferredOutput->mIoHandle;
1602 }
1603 }
1604 } else {
1605 // at this stage we should ignore the DIRECT flag as no direct output could be
1606 // found earlier
1607 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1608 output = selectOutput(
1609 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1610 }
Eric Laurente552edb2014-03-10 17:42:56 -07001611 }
François Gaffie11d30102018-11-02 16:09:09 +01001612 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001613 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001614 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001615
Eric Laurente552edb2014-03-10 17:42:56 -07001616 return output;
1617}
1618
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001619sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001620 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1621 mAvailableInputDevices);
1622 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1623}
1624
1625DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1626 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1627 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001628}
1629
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001630const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001631 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001632 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1633 if (msdModule != 0) {
1634 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1635 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1636 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1637 const struct audio_port_config *source = &patch->mPatch.sources[j];
1638 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1639 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001640 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001641 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001642 }
1643 }
1644 }
1645 return msdPatches;
1646}
1647
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001648bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1649 ssize_t index = mAudioPatches.indexOfKey(handle);
1650 if (index < 0) {
1651 return false;
1652 }
1653 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1654 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1655 if (msdModule == nullptr) {
1656 return false;
1657 }
1658 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1659 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1660 return true;
1661 }
1662 index = getMsdOutputPatches().indexOfKey(handle);
1663 if (index < 0) {
1664 return false;
1665 }
1666 return true;
1667}
1668
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001669status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1670 const InputProfileCollection &inputProfiles,
1671 const OutputProfileCollection &outputProfiles,
1672 const sp<DeviceDescriptor> &sourceDevice,
1673 const sp<DeviceDescriptor> &sinkDevice,
1674 AudioProfileVector& sourceProfiles,
1675 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001676 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001677 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001678 return NO_INIT;
1679 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001680 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001681 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001682 return NO_INIT;
1683 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001684 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001685 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1686 inProfile->supportsDevice(sourceDevice)) {
1687 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001688 }
1689 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001690 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001691 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001692 outProfile->supportsDevice(sinkDevice)) {
1693 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001694 }
1695 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001696 return NO_ERROR;
1697}
1698
1699status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1700 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1701 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1702{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001703 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001704 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1705 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1706 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001707 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001708 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1709 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001710 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001711 }
1712 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1713 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1714 sinkConfig->format = bestSinkConfig.format;
1715 // For encoded streams force direct flag to prevent downstream mixing.
1716 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1717 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001718 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1719 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001720 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001721 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1722 // raw and IEC61937 framed streams.
1723 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1724 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1725 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001726 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1727 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1728 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1729 sourceConfig->format = bestSinkConfig.format;
1730 // Copy input stream directly without any processing (e.g. resampling).
1731 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1732 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1733 if (hwAvSync) {
1734 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1735 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1736 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1737 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1738 }
1739 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1740 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1741 sinkConfig->config_mask |= config_mask;
1742 sourceConfig->config_mask |= config_mask;
1743 return NO_ERROR;
1744}
1745
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001746PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1747 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001748{
1749 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001750 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1751 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1752 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1753 if (deviceModule == nullptr) {
1754 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1755 return patchBuilder;
1756 }
1757 const InputProfileCollection inputProfiles = msdIsSource ?
1758 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1759 const OutputProfileCollection outputProfiles = msdIsSource ?
1760 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1761
1762 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1763 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1764 device : getMsdAudioOutDevices().itemAt(0);
1765 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1766
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001767 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1768 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001769 AudioProfileVector sourceProfiles;
1770 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1772 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001773 for (auto hwAvSync : { true, false }) {
1774 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1775 sourceProfiles, sinkProfiles) != NO_ERROR) {
1776 continue;
1777 }
1778 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1779 &sinkConfig) == NO_ERROR) {
1780 // Found a matching config. Re-create PatchBuilder with this config.
1781 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1782 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001783 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001784 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001785 " supporting PCM format conversion.", __func__);
1786 return patchBuilder;
1787}
1788
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001789status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001790 DeviceVector devices;
1791 if (outputDevices != nullptr && outputDevices->size() > 0) {
1792 devices.add(*outputDevices);
1793 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001794 // Use media strategy for unspecified output device. This should only
1795 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1796 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001797 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001798 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001799 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001800 }
Michael Chan6fb34492020-12-08 15:44:49 +11001801 std::vector<PatchBuilder> patchesToCreate;
1802 for (auto i = 0u; i < devices.size(); ++i) {
1803 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001804 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001805 }
1806 // Retain only the MSD patches associated with outputDevices request.
1807 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001808 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001809 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1810 auto retainedPatch = false;
1811 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1812 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1813 patchesToRemove.removeItemsAt(i);
1814 retainedPatch = true;
1815 break;
1816 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001817 }
Michael Chan6fb34492020-12-08 15:44:49 +11001818 if (retainedPatch) {
1819 it = patchesToCreate.erase(it);
1820 continue;
1821 }
1822 ++it;
1823 }
1824 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1825 return NO_ERROR;
1826 }
1827 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1828 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001829 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001830 }
Michael Chan6fb34492020-12-08 15:44:49 +11001831 status_t status = NO_ERROR;
1832 for (const auto &p : patchesToCreate) {
1833 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1834 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1835 char message[256];
1836 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1837 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1838 currStatus == NO_ERROR ? "Success" : "Error",
1839 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1840 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1841 if (currStatus == NO_ERROR) {
1842 ALOGD("%s", message);
1843 } else {
1844 ALOGE("%s", message);
1845 if (status == NO_ERROR) {
1846 status = currStatus;
1847 }
1848 }
1849 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001850 return status;
1851}
1852
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001853void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1854 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001855 for (size_t i = 0; i < msdPatches.size(); i++) {
1856 const auto& patch = msdPatches[i];
1857 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1858 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1859 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1860 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1861 releaseAudioPatch(patch->getHandle(), mUidCached);
1862 break;
1863 }
1864 }
1865 }
1866}
1867
Dorin Drimus94d94412022-02-02 09:05:02 +01001868bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1869 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1870 AudioPatchCollection msdPatches = getMsdOutputPatches();
1871 for (size_t i = 0; i < msdPatches.size(); i++) {
1872 const auto& patch = msdPatches[i];
1873 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1874 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1875 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1876 const auto& foundDevice = devicesToCheck.getDevice(
1877 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1878 if (foundDevice != nullptr) {
1879 devicesToCheck.remove(foundDevice);
1880 if (devicesToCheck.isEmpty()) {
1881 return true;
1882 }
1883 }
1884 }
1885 }
1886 }
1887 return false;
1888}
1889
Eric Laurente0720872014-03-11 09:30:41 -07001890audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001891 audio_output_flags_t flags,
1892 audio_format_t format,
1893 audio_channel_mask_t channelMask,
1894 uint32_t samplingRate,
1895 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001896{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001897 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1898 "%s called with format %#x", __func__, format);
1899
jiabinebb6af42020-06-09 17:31:17 -07001900 // Return the output that haptic-generating attached to when 1) session id is specified,
1901 // 2) haptic-generating effect exists for given session id and 3) the output that
1902 // haptic-generating effect attached to is in given outputs.
1903 if (sessionId != AUDIO_SESSION_NONE) {
1904 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1905 sessionId, FX_IID_HAPTICGENERATOR);
1906 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1907 return hapticGeneratingOutput;
1908 }
1909 }
1910
Eric Laurent16c66dd2019-05-01 17:54:10 -07001911 // Flags disqualifying an output: the match must happen before calling selectOutput()
1912 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1913 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1914
1915 // Flags expressing a functional request: must be honored in priority over
1916 // other criteria
1917 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1918 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001919 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1920 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001921 // Flags expressing a performance request: have lower priority than serving
1922 // requested sampling rate or channel mask
1923 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1924 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1925 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1926
1927 const audio_output_flags_t functionalFlags =
1928 (audio_output_flags_t)(flags & kFunctionalFlags);
1929 const audio_output_flags_t performanceFlags =
1930 (audio_output_flags_t)(flags & kPerformanceFlags);
1931
1932 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1933
Eric Laurente552edb2014-03-10 17:42:56 -07001934 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001935 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001936 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001937 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001938 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001939 // with tiebreak preferring the minimum number of extra functional flags
1940 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001941 // 3: the output supporting the exact channel mask
1942 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001943 // 5: the output with the highest sampling rate if the requested sample rate is
1944 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001945 // 6: the output with the highest number of requested performance flags
1946 // 7: the output with the bit depth the closest to the requested one
1947 // 8: the primary output
1948 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001949
Eric Laurent16c66dd2019-05-01 17:54:10 -07001950 // matching criteria values in priority order for best matching output so far
1951 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001952
Eric Laurent16c66dd2019-05-01 17:54:10 -07001953 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1954 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1955 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001956
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001957 for (audio_io_handle_t output : outputs) {
1958 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001959 // matching criteria values in priority order for current output
1960 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001961
Eric Laurent16c66dd2019-05-01 17:54:10 -07001962 if (outputDesc->isDuplicated()) {
1963 continue;
1964 }
1965 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1966 continue;
1967 }
Eric Laurent8838a382014-09-08 16:44:28 -07001968
Eric Laurent16c66dd2019-05-01 17:54:10 -07001969 // If haptic channel is specified, use the haptic output if present.
1970 // When using haptic output, same audio format and sample rate are required.
1971 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001972 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001973 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1974 continue;
1975 }
1976 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001977 && format == outputDesc->getFormat()
1978 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001979 currentMatchCriteria[0] = outputHapticChannelCount;
1980 }
1981
1982 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001983 const int matchingFunctionalFlags =
1984 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1985 const int totalFunctionalFlags =
1986 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1987 // Prefer matching functional flags, but subtract unnecessary functional flags.
1988 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001989
1990 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001991 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1992 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001993 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1994 channelCount <= outputChannelCount) {
1995 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001996 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1997 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001998 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001999 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002000 currentMatchCriteria[3] = outputChannelCount;
2001 }
2002
2003 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002004 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002005 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002006 }
2007
2008 // performance flags match
2009 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2010
2011 // format match
2012 if (format != AUDIO_FORMAT_INVALID) {
2013 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002014 PolicyAudioPort::kFormatDistanceMax -
2015 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002016 }
2017
2018 // primary output match
2019 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2020
2021 // compare match criteria by priority then value
2022 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2023 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2024 bestMatchCriteria = currentMatchCriteria;
2025 bestOutput = output;
2026
2027 std::stringstream result;
2028 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2029 std::ostream_iterator<int>(result, " "));
2030 ALOGV("%s new bestOutput %d criteria %s",
2031 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002032 }
2033 }
2034
Eric Laurent16c66dd2019-05-01 17:54:10 -07002035 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002036}
2037
Eric Laurent8fc147b2018-07-22 19:13:55 -07002038status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002039{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002040 ALOGV("%s portId %d", __FUNCTION__, portId);
2041
2042 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2043 if (outputDesc == 0) {
2044 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002045 return BAD_VALUE;
2046 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002047 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002048
Eric Laurent8fc147b2018-07-22 19:13:55 -07002049 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002050 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002051
Eric Laurent733ce942017-12-07 12:18:25 -08002052 status_t status = outputDesc->start();
2053 if (status != NO_ERROR) {
2054 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002055 }
2056
Eric Laurent97ac8712018-07-27 18:59:02 -07002057 uint32_t delayMs;
2058 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002059
2060 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002061 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002062 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002063 }
jiabina84c3d32022-12-02 18:59:55 +00002064
2065 // If the client is the first one active on preferred mixer parameters, reopen the output
2066 // if the current mixer parameters doesn't match the preferred one.
2067 if (outputDesc->devices().size() == 1) {
2068 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2069 outputDesc->devices()[0]->getId(), client->strategy());
2070 if (info != nullptr && info->getUid() == client->uid()) {
2071 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2072 info->getConfigBase(), info->getFlags())) {
2073 stopSource(outputDesc, client);
2074 outputDesc->stop();
2075 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2076 config.channel_mask = info->getConfigBase().channel_mask;
2077 config.sample_rate = info->getConfigBase().sample_rate;
2078 config.format = info->getConfigBase().format;
2079 status_t status = reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2080 if (status != NO_ERROR) {
2081 return status;
2082 }
2083 // Intentionally return error to let the client side resending request for
2084 // creating and starting.
2085 return DEAD_OBJECT;
2086 }
2087 info->increaseActiveClient();
2088 }
2089 }
2090
Eric Laurentc75307b2015-03-17 15:29:32 -07002091 if (delayMs != 0) {
2092 usleep(delayMs * 1000);
2093 }
2094
2095 return status;
2096}
2097
Eric Laurent96d1dda2022-03-14 17:14:19 +01002098bool AudioPolicyManager::isLeUnicastActive() const {
2099 if (isInCall()) {
2100 return true;
2101 }
2102 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2103}
2104
2105bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2106 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2107 return false;
2108 }
2109 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2110 ALOGV("%s active %d", __func__, active);
2111 return active;
2112}
2113
Eric Laurent97ac8712018-07-27 18:59:02 -07002114status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2115 const sp<TrackClientDescriptor>& client,
2116 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002117{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002118 // cannot start playback of STREAM_TTS if any other output is being used
2119 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002120
2121 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002122 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002123 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002124 auto clientStrategy = client->strategy();
2125 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002126 if (stream == AUDIO_STREAM_TTS) {
2127 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002128 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002129 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002130 return INVALID_OPERATION;
2131 } else {
2132 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2133 }
2134 } else {
2135 // some playback other than beacon starts
2136 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2137 }
2138
Eric Laurent77305a62016-07-25 16:39:22 -07002139 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002140 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002141 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002142
François Gaffie11d30102018-11-02 16:09:09 +01002143 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002144 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002145 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002146 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002147 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002148 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002149 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002150 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002151 } else {
2152 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002153 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002154 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2155 AUDIO_FORMAT_DEFAULT);
2156 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2157 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002158 }
2159
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002160 // requiresMuteCheck is false when we can bypass mute strategy.
2161 // It covers a common case when there is no materially active audio
2162 // and muting would result in unnecessary delay and dropped audio.
2163 const uint32_t outputLatencyMs = outputDesc->latency();
2164 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002165 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002166
Eric Laurente552edb2014-03-10 17:42:56 -07002167 // increment usage count for this stream on the requested output:
2168 // NOTE that the usage count is the same for duplicated output and hardware output which is
2169 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002170 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002171
2172 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002173 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2174 client->isPreferredDeviceForExclusiveUse()) {
2175 // Preferred device may be exclusive, use only if no other active clients on this output
2176 devices = DeviceVector(
2177 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2178 } else {
2179 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2180 }
François Gaffie11d30102018-11-02 16:09:09 +01002181 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002182 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002183 }
2184 }
Eric Laurente552edb2014-03-10 17:42:56 -07002185
François Gaffiec005e562018-11-06 15:04:49 +01002186 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002187 selectOutputForMusicEffects();
2188 }
2189
François Gaffie1c878552018-11-22 16:53:21 +01002190 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002191 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002192 if (devices.isEmpty()) {
2193 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002194 }
François Gaffiec005e562018-11-06 15:04:49 +01002195 bool shouldWait =
2196 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2197 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2198 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002199 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002200 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002201 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002202 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002203 // An output has a shared device if
2204 // - managed by the same hw module
2205 // - supports the currently selected device
2206 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002207 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002208
Eric Laurent77305a62016-07-25 16:39:22 -07002209 // force a device change if any other output is:
2210 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002211 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002212 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002213 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002214 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002215 // change the device currently selected by the other output.
2216 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002217 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002218 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002219 force = true;
2220 }
2221 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002222 // a notification so that audio focus effect can propagate, or that a mute/unmute
2223 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002224 const uint32_t latencyMs = desc->latency();
2225 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2226
2227 if (shouldWait && isActive && (waitMs < latencyMs)) {
2228 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002229 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002230
2231 // Require mute check if another output is on a shared device
2232 // and currently active to have proper drain and avoid pops.
2233 // Note restoring AudioTracks onto this output needs to invoke
2234 // a volume ramp if there is no mute.
2235 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002236 }
2237 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002238
2239 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002240 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002241
Eric Laurente552edb2014-03-10 17:42:56 -07002242 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002243 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002244 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002245 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002246 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002247 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002248 outputDesc->useHwGain() /*force*/)) {
2249 // request AudioService to reinitialize the volume curves asynchronously
2250 ALOGE("checkAndSetVolume failed, requesting volume range init");
2251 mpClientInterface->onVolumeRangeInitRequest();
2252 };
Eric Laurente552edb2014-03-10 17:42:56 -07002253
2254 // update the outputs if starting an output with a stream that can affect notification
2255 // routing
2256 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002257
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002258 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002259 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002260 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2261 }
Eric Laurentdc462862016-07-19 12:29:53 -07002262
2263 if (waitMs > muteWaitMs) {
2264 *delayMs = waitMs - muteWaitMs;
2265 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002266
2267 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2268 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2269 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2270 // change occurs after the MixerThread starts and causes a stream volume
2271 // glitch.
2272 //
2273 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002274 }
Eric Laurentdc462862016-07-19 12:29:53 -07002275
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002276 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002277 mEngine->getForceUse(
2278 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002279 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002280 }
2281
Eric Laurent97ac8712018-07-27 18:59:02 -07002282 // Automatically enable the remote submix input when output is started on a re routing mix
2283 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002284 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2285 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002286 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2287 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2288 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002289 "remote-submix",
2290 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002291 }
2292
Eric Laurent96d1dda2022-03-14 17:14:19 +01002293 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2294
Eric Laurente552edb2014-03-10 17:42:56 -07002295 return NO_ERROR;
2296}
2297
Eric Laurent96d1dda2022-03-14 17:14:19 +01002298void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2299 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2300 bool isUnicastActive = isLeUnicastActive();
2301
2302 if (wasUnicastActive != isUnicastActive) {
2303 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2304 for (size_t i = 0; i < mOutputs.size(); i++) {
2305 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2306 if (desc != ignoredOutput && desc->isActive()
2307 && ((isUnicastActive &&
2308 !desc->devices().
2309 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2310 || (wasUnicastActive &&
2311 !desc->devices().getDevicesFromTypes(
2312 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2313 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2314 bool force = desc->devices() != newDevices;
2315 setOutputDevices(desc, newDevices, force, delayMs);
2316 // re-apply device specific volume if not done by setOutputDevice()
2317 if (!force) {
2318 applyStreamVolumes(desc, newDevices.types(), delayMs);
2319 }
2320 }
2321 }
2322 }
2323}
2324
Eric Laurent8fc147b2018-07-22 19:13:55 -07002325status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002326{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002327 ALOGV("%s portId %d", __FUNCTION__, portId);
2328
2329 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2330 if (outputDesc == 0) {
2331 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002332 return BAD_VALUE;
2333 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002334 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002335
Eric Laurent97ac8712018-07-27 18:59:02 -07002336 ALOGV("stopOutput() output %d, stream %d, session %d",
2337 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002338
Eric Laurent97ac8712018-07-27 18:59:02 -07002339 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002340
Eric Laurent733ce942017-12-07 12:18:25 -08002341 if (status == NO_ERROR ) {
2342 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002343 } else {
2344 return status;
2345 }
2346
2347 if (outputDesc->devices().size() == 1) {
2348 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2349 outputDesc->devices()[0]->getId(), client->strategy());
2350 if (info != nullptr && info->getUid() == client->uid()) {
2351 info->decreaseActiveClient();
2352 if (info->getActiveClientCount() == 0) {
2353 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2354 }
2355 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002356 }
2357 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002358}
2359
Eric Laurent97ac8712018-07-27 18:59:02 -07002360status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2361 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002362{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002363 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002364 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002365 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002366 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002367
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002368 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2369
François Gaffie1c878552018-11-22 16:53:21 +01002370 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2371 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002372 // Automatically disable the remote submix input when output is stopped on a
2373 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002374 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002375 if (isSingleDeviceType(
2376 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002377 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002378 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002379 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2380 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002381 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002382 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002383 }
2384 }
2385 bool forceDeviceUpdate = false;
2386 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002387 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002388 forceDeviceUpdate = true;
2389 }
2390
Eric Laurente552edb2014-03-10 17:42:56 -07002391 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002392 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002393
Eric Laurente552edb2014-03-10 17:42:56 -07002394 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002395 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002396 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002397 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002398
2399 // If the routing does not change, if an output is routed on a device using HwGain
2400 // (aka setAudioPortConfig) and there are still active clients following different
2401 // volume group(s), force reapply volume
2402 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2403 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2404
Eric Laurente552edb2014-03-10 17:42:56 -07002405 // delay the device switch by twice the latency because stopOutput() is executed when
2406 // the track stop() command is received and at that time the audio track buffer can
2407 // still contain data that needs to be drained. The latency only covers the audio HAL
2408 // and kernel buffers. Also the latency does not always include additional delay in the
2409 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002410 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2411 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002412
2413 // force restoring the device selection on other active outputs if it differs from the
2414 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002415 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002416 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002417 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002418 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002419 desc->isActive() &&
2420 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002421 (newDevices != desc->devices())) {
2422 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2423 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002424
François Gaffie11d30102018-11-02 16:09:09 +01002425 setOutputDevices(desc, newDevices2, force, delayMs);
2426
Eric Laurent57de36c2016-09-28 16:59:11 -07002427 // re-apply device specific volume if not done by setOutputDevice()
2428 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002429 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002430 }
Eric Laurente552edb2014-03-10 17:42:56 -07002431 }
2432 }
2433 // update the outputs if stopping one with a stream that can affect notification routing
2434 handleNotificationRoutingForStream(stream);
2435 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002436
2437 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2438 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002439 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002440 }
2441
François Gaffiec005e562018-11-06 15:04:49 +01002442 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002443 selectOutputForMusicEffects();
2444 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002445
2446 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2447
Eric Laurente552edb2014-03-10 17:42:56 -07002448 return NO_ERROR;
2449 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002450 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002451 return INVALID_OPERATION;
2452 }
2453}
2454
jiabinbce0c1d2020-10-05 11:20:18 -07002455bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002456{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002457 ALOGV("%s portId %d", __FUNCTION__, portId);
2458
2459 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2460 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002461 // If an output descriptor is closed due to a device routing change,
2462 // then there are race conditions with releaseOutput from tracks
2463 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2464 // destroyed shortly thereafter.
2465 //
2466 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002467 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002468 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002469 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002470
2471 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002472
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302473 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2474 if (outputDesc->isClientActive(client)) {
2475 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2476 stopOutput(portId);
2477 }
2478
Eric Laurent8fc147b2018-07-22 19:13:55 -07002479 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2480 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002481 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002482 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002483 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002484 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002485 if (--outputDesc->mDirectOpenCount == 0) {
2486 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002487 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002488 }
2489 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302490
Andy Hung39efb7a2018-09-26 15:39:28 -07002491 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002492 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2493 // The output is pending reopened to query dynamic profiles and
2494 // there is no active clients
2495 closeOutput(outputDesc->mIoHandle);
2496 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2497 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2498 if (newOutputDesc == nullptr) {
2499 ALOGE("%s failed to open output", __func__);
2500 }
2501 return true;
2502 }
2503 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002504}
2505
Eric Laurentcaf7f482014-11-25 17:50:47 -08002506status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2507 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002508 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002509 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002510 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002511 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002512 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002513 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002514 input_type_t *inputType,
2515 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002516{
François Gaffiec005e562018-11-06 15:04:49 +01002517 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002518 "flags %#x attributes=%s requested device ID %d",
2519 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2520 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002521
Eric Laurentad2e7b92017-09-14 20:06:42 -07002522 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002523 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002524 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002525 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002526 sp<AudioInputDescriptor> inputDesc;
2527 sp<RecordClientDescriptor> clientDesc;
2528 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002529 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002530 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002531
2532 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2533 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2534 return INVALID_OPERATION;
2535 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002536
Francois Gaffie716e1432019-01-14 16:58:59 +01002537 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2538 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002539 }
2540
Paul McLean466dc8e2015-04-17 13:15:36 -06002541 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002542 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002543 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002544
Eric Laurentad2e7b92017-09-14 20:06:42 -07002545 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2546 // possible
2547 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2548 *input != AUDIO_IO_HANDLE_NONE) {
2549 ssize_t index = mInputs.indexOfKey(*input);
2550 if (index < 0) {
2551 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2552 status = BAD_VALUE;
2553 goto error;
2554 }
2555 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002556 RecordClientVector clients = inputDesc->getClientsForSession(session);
2557 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002558 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2559 status = BAD_VALUE;
2560 goto error;
2561 }
2562 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2563 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002564 // corresponds to a new client and is only permitted from the same UID.
2565 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002566 if (clients.size() > 1) {
2567 for (const auto& client : clients) {
2568 // The client map is ordered by key values (portId) and portIds are allocated
2569 // incrementaly. So the first client in this list is the one opened by audio flinger
2570 // when the mmap stream is created and should be ignored as it does not correspond
2571 // to an actual client
2572 if (client == *clients.cbegin()) {
2573 continue;
2574 }
2575 if (uid != client->uid() && !client->isSilenced()) {
2576 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2577 uid, client->portId(), client->uid());
2578 status = INVALID_OPERATION;
2579 goto error;
2580 }
Eric Laurent331679c2018-04-16 17:03:16 -07002581 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002582 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002583 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002584 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002585
Eric Laurentfecbceb2021-02-09 14:46:43 +01002586 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002587 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002588 }
2589
2590 *input = AUDIO_IO_HANDLE_NONE;
2591 *inputType = API_INPUT_INVALID;
2592
Francois Gaffie716e1432019-01-14 16:58:59 +01002593 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002594 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002595 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002596 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002597 ALOGW("%s could not find input mix for attr %s",
2598 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002599 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002600 }
jiabinc1de2df2019-05-07 14:26:40 -07002601 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2602 String8(attr->tags + strlen("addr=")),
2603 AUDIO_FORMAT_DEFAULT);
2604 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002605 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002606 __func__, attributes.source, attributes.tags);
2607 status = BAD_VALUE;
2608 goto error;
2609 }
2610
Kevin Rocard25f9b052019-02-27 15:08:54 -08002611 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2612 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2613 } else {
2614 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2615 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002616 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002617 if (explicitRoutingDevice != nullptr) {
2618 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002619 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002620 // Prevent from storing invalid requested device id in clients
2621 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002622 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002623 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2624 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002625 }
François Gaffie11d30102018-11-02 16:09:09 +01002626 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002627 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002628 status = BAD_VALUE;
2629 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002630 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002631 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2632 *inputType = API_INPUT_MIX_CAPTURE;
2633 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002634 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2635 // there is an external policy, but this input is attached to a mix of recorders,
2636 // meaning it receives audio injected into the framework, so the recorder doesn't
2637 // know about it and is therefore considered "legacy"
2638 *inputType = API_INPUT_LEGACY;
2639 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002640 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002641 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002642 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002643 } else {
2644 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002645 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002646
Eric Laurent599c7582015-12-07 18:05:55 -08002647 }
2648
François Gaffiec005e562018-11-06 15:04:49 +01002649 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002650 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002651 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002652 AudioProfileVector profiles;
2653 status_t ret = getProfilesForDevices(
2654 DeviceVector(device), profiles, flags, true /*isInput*/);
2655 if (ret == NO_ERROR && !profiles.empty()) {
2656 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2657 : *profiles[0]->getChannels().begin();
2658 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2659 : *profiles[0]->getSampleRates().begin();
2660 config->format = profiles[0]->getFormat();
2661 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002662 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002663 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002664
Eric Laurent8f42ea12018-08-08 09:08:25 -07002665exit:
2666
François Gaffiec005e562018-11-06 15:04:49 +01002667 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2668 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002669
Francois Gaffie716e1432019-01-14 16:58:59 +01002670 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002671 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002672 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002673
Mikhail Naganov2996f672019-04-18 12:29:59 -07002674 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002675 requestedDeviceId, attributes.source, flags,
2676 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002677 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002678 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002679
2680 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2681 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002682
Eric Laurent599c7582015-12-07 18:05:55 -08002683 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002684
2685error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002686 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002687}
2688
2689
François Gaffie11d30102018-11-02 16:09:09 +01002690audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002691 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002692 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002693 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002694 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002695 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002696{
2697 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002698 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002699 bool isSoundTrigger = false;
2700
François Gaffiec005e562018-11-06 15:04:49 +01002701 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002702 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2703 if (index >= 0) {
2704 input = mSoundTriggerSessions.valueFor(session);
2705 isSoundTrigger = true;
2706 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2707 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2708 } else {
2709 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002710 }
François Gaffiec005e562018-11-06 15:04:49 +01002711 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002712 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002713 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002714 }
2715
Carter Hsua3abb402021-10-26 11:11:20 +08002716 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2717 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2718 }
2719
Eric Laurentfe231122017-11-17 17:48:06 -08002720 // sampling rate and flags may be updated by getInputProfile
2721 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2722 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002723 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002724 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002725 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002726 // find a compatible input profile (not necessarily identical in parameters)
2727 sp<IOProfile> profile = getInputProfile(
2728 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2729 if (profile == nullptr) {
2730 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002731 }
jiabin2fd710d2022-05-02 23:20:22 +00002732
Glenn Kasten05ddca52016-02-11 08:17:12 -08002733 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002734 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002735 if (samplingRate == 0) {
2736 samplingRate = profileSamplingRate;
2737 }
Eric Laurente552edb2014-03-10 17:42:56 -07002738
Eric Laurent322b4d22015-04-03 15:57:54 -07002739 if (profile->getModuleHandle() == 0) {
2740 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002741 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002742 }
2743
Eric Laurentec376dc2021-04-08 20:41:22 +02002744 // Reuse an already opened input if a client with the same session ID already exists
2745 // on that input
2746 for (size_t i = 0; i < mInputs.size(); i++) {
2747 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2748 if (desc->mProfile != profile) {
2749 continue;
2750 }
2751 RecordClientVector clients = desc->clientsList();
2752 for (const auto &client : clients) {
2753 if (session == client->session()) {
2754 return desc->mIoHandle;
2755 }
2756 }
2757 }
2758
Eric Laurent3974e3b2017-12-07 17:58:43 -08002759 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002760 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002761 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002762 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002763 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002764 continue;
2765 }
2766 // if sound trigger, reuse input if used by other sound trigger on same session
2767 // else
2768 // reuse input if active client app is not in IDLE state
2769 //
2770 RecordClientVector clients = desc->clientsList();
2771 bool doClose = false;
2772 for (const auto& client : clients) {
2773 if (isSoundTrigger != client->isSoundTrigger()) {
2774 continue;
2775 }
2776 if (client->isSoundTrigger()) {
2777 if (session == client->session()) {
2778 return desc->mIoHandle;
2779 }
2780 continue;
2781 }
2782 if (client->active() && client->appState() != APP_STATE_IDLE) {
2783 return desc->mIoHandle;
2784 }
2785 doClose = true;
2786 }
2787 if (doClose) {
2788 closeInput(desc->mIoHandle);
2789 } else {
2790 i++;
2791 }
2792 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002793 }
2794
Eric Laurentfe231122017-11-17 17:48:06 -08002795 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002796
Eric Laurentfe231122017-11-17 17:48:06 -08002797 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2798 lConfig.sample_rate = profileSamplingRate;
2799 lConfig.channel_mask = profileChannelMask;
2800 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002801
François Gaffie11d30102018-11-02 16:09:09 +01002802 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002803
2804 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002805 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002806 (profileSamplingRate != lConfig.sample_rate) ||
2807 !audio_formats_match(profileFormat, lConfig.format) ||
2808 (profileChannelMask != lConfig.channel_mask)) {
2809 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002810 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002811 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002812 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002813 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002814 }
Eric Laurent599c7582015-12-07 18:05:55 -08002815 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002816 }
2817
Eric Laurentc722f302014-12-10 11:21:49 -08002818 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002819
Eric Laurent599c7582015-12-07 18:05:55 -08002820 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002821 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002822
Eric Laurent599c7582015-12-07 18:05:55 -08002823 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002824}
2825
Eric Laurent4eb58f12018-12-07 16:41:02 -08002826status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002827{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002828 ALOGV("%s portId %d", __FUNCTION__, portId);
2829
2830 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2831 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002832 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002833 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002835 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002836 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002837 if (client->active()) {
2838 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2839 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002840 }
2841
Eric Laurent8f42ea12018-08-08 09:08:25 -07002842 audio_session_t session = client->session();
2843
Eric Laurent4eb58f12018-12-07 16:41:02 -08002844 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002845
Eric Laurent4eb58f12018-12-07 16:41:02 -08002846 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002847
Eric Laurent4eb58f12018-12-07 16:41:02 -08002848 status_t status = inputDesc->start();
2849 if (status != NO_ERROR) {
2850 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002851 }
Eric Laurente552edb2014-03-10 17:42:56 -07002852
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002853 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002854 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002855 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002856
Eric Laurent8f42ea12018-08-08 09:08:25 -07002857 // indicate active capture to sound trigger service if starting capture from a mic on
2858 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002859 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002860 if (device != nullptr) {
2861 status = setInputDevice(input, device, true /* force */);
2862 } else {
2863 ALOGW("%s no new input device can be found for descriptor %d",
2864 __FUNCTION__, inputDesc->getId());
2865 status = BAD_VALUE;
2866 }
Eric Laurente552edb2014-03-10 17:42:56 -07002867
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002868 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002869 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002870 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002871 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002872 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2873 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002874 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002875 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002876
François Gaffie11d30102018-11-02 16:09:09 +01002877 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2878 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002879 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002880 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002881 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002882
Eric Laurent8f42ea12018-08-08 09:08:25 -07002883 // automatically enable the remote submix output when input is started if not
2884 // used by a policy mix of type MIX_TYPE_RECORDERS
2885 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002886 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002887 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002888 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002889 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002890 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2891 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002892 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002893 if (address != "") {
2894 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2895 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002896 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002897 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002898 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002899 } else if (status != NO_ERROR) {
2900 // Restore client activity state.
2901 inputDesc->setClientActive(client, false);
2902 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002903 }
2904
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002905 ALOGV("%s input %d source = %d status = %d exit",
2906 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002907
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002908 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002909}
2910
Eric Laurent8fc147b2018-07-22 19:13:55 -07002911status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002912{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002913 ALOGV("%s portId %d", __FUNCTION__, portId);
2914
2915 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2916 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002917 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002918 return BAD_VALUE;
2919 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002920 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002921 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002922 if (!client->active()) {
2923 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002924 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002925 }
Carter Hsue6139d52021-07-08 10:30:20 +08002926 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002927 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002928
Eric Laurent8f42ea12018-08-08 09:08:25 -07002929 inputDesc->stop();
2930 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002931 auto current_source = inputDesc->source();
2932 setInputDevice(input, getNewInputDevice(inputDesc),
2933 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002934 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002935 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002936 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002937 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002938 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2939 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002940 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002941 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002942
2943 // automatically disable the remote submix output when input is stopped if not
2944 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002945 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002946 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002947 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002948 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002949 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2950 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002951 }
2952 if (address != "") {
2953 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2954 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002955 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002956 }
2957 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002958 resetInputDevice(input);
2959
2960 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2961 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002962 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2963 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002964 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002965 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002966 }
2967 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002968 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002969 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002970}
2971
Eric Laurent8fc147b2018-07-22 19:13:55 -07002972void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002973{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002974 ALOGV("%s portId %d", __FUNCTION__, portId);
2975
2976 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2977 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002978 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002979 return;
2980 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002981 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002982 audio_io_handle_t input = inputDesc->mIoHandle;
2983
Eric Laurent8f42ea12018-08-08 09:08:25 -07002984 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002985
Andy Hung39efb7a2018-09-26 15:39:28 -07002986 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002987
Andy Hung39efb7a2018-09-26 15:39:28 -07002988 if (inputDesc->getClientCount() > 0) {
2989 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002990 return;
2991 }
2992
Eric Laurent05b90f82014-08-27 15:32:29 -07002993 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002994 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002995 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002996}
2997
Eric Laurent8f42ea12018-08-08 09:08:25 -07002998void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002999{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003000 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003001
3002 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003003 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003004 }
3005}
3006
Eric Laurent8f42ea12018-08-08 09:08:25 -07003007void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3008{
3009 stopInput(portId);
3010 releaseInput(portId);
3011}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003012
Eric Laurent0dd51852019-04-19 18:18:58 -07003013void AudioPolicyManager::checkCloseInputs() {
3014 // After connecting or disconnecting an input device, close input if:
3015 // - it has no client (was just opened to check profile) OR
3016 // - none of its supported devices are connected anymore OR
3017 // - one of its clients cannot be routed to one of its supported
3018 // devices anymore. Otherwise update device selection
3019 std::vector<audio_io_handle_t> inputsToClose;
3020 for (size_t i = 0; i < mInputs.size(); i++) {
3021 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3022 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003023 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003024 inputsToClose.push_back(mInputs.keyAt(i));
3025 } else {
3026 bool close = false;
3027 for (const auto& client : input->clientsList()) {
3028 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003029 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3030 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003031 if (!input->supportedDevices().contains(device)) {
3032 close = true;
3033 break;
3034 }
3035 }
3036 if (close) {
3037 inputsToClose.push_back(mInputs.keyAt(i));
3038 } else {
3039 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3040 }
3041 }
3042 }
3043
3044 for (const audio_io_handle_t handle : inputsToClose) {
3045 ALOGV("%s closing input %d", __func__, handle);
3046 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003047 }
Eric Laurentd4692962014-05-05 18:13:44 -07003048}
3049
François Gaffie251c7f02018-11-07 10:41:08 +01003050void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003051{
3052 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003053 if (indexMin < 0 || indexMax < 0) {
3054 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3055 return;
3056 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003057 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003058
3059 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003060 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3061 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003062 continue;
3063 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003064 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003065 }
Eric Laurente552edb2014-03-10 17:42:56 -07003066}
3067
Eric Laurente0720872014-03-11 09:30:41 -07003068status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003069 int index,
3070 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003071{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003072 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003073 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3074 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3075 return NO_ERROR;
3076 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003077 ALOGV("%s: stream %s attributes=%s", __func__,
3078 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003079 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003080}
3081
Eric Laurente0720872014-03-11 09:30:41 -07003082status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003083 int *index,
3084 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003085{
François Gaffiec005e562018-11-06 15:04:49 +01003086 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3087 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003088 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003089 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003090 deviceTypes = mEngine->getOutputDevicesForStream(
3091 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003092 }
jiabin9a3361e2019-10-01 09:38:30 -07003093 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003094}
3095
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003096status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003097 int index,
3098 audio_devices_t device)
3099{
3100 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003101 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3102 if (group == VOLUME_GROUP_NONE) {
3103 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003104 return BAD_VALUE;
3105 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003106 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003107 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003108 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003109 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003110 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3111 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3112 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3113 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003114 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3115
3116 status = setVolumeCurveIndex(index, device, curves);
3117 if (status != NO_ERROR) {
3118 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3119 return status;
3120 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003121
jiabin9a3361e2019-10-01 09:38:30 -07003122 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003123 auto curCurvAttrs = curves.getAttributes();
3124 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3125 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003126 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003127 } else if (!curves.getStreamTypes().empty()) {
3128 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003129 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003130 } else {
3131 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3132 return BAD_VALUE;
3133 }
jiabin9a3361e2019-10-01 09:38:30 -07003134 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3135 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003136
François Gaffiecfe17322018-11-07 13:41:29 +01003137 // update volume on all outputs and streams matching the following:
3138 // - The requested stream (or a stream matching for volume control) is active on the output
3139 // - The device (or devices) selected by the engine for this stream includes
3140 // the requested device
3141 // - For non default requested device, currently selected device on the output is either the
3142 // requested device or one of the devices selected by the engine for this stream
3143 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3144 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003145 for (size_t i = 0; i < mOutputs.size(); i++) {
3146 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003147 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003148
jiabin9a3361e2019-10-01 09:38:30 -07003149 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3150 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003151 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003152
3153 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003154 continue;
3155 }
3156 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3157 curDevices.find(device) == curDevices.end()) {
3158 continue;
3159 }
3160 bool applyVolume = false;
3161 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3162 curSrcDevices.insert(device);
3163 applyVolume = (curSrcDevices.find(
3164 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3165 } else {
3166 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3167 }
3168 if (!applyVolume) {
3169 continue; // next output
3170 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003171 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3172 // If a higher priority strategy is active, and the output is routed to a device with a
3173 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003174 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003175 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003176 // If the volume source is active with higher priority source, ensure at least Sw Muted
3177 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003178 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3179 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3180 false /*preferredDevice*/);
3181 if (activeClients.empty()) {
3182 continue;
3183 }
3184 bool isPreempted = false;
3185 bool isHigherPriority = productStrategy < strategy;
3186 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003187 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003188 ALOGV("%s: Strategy=%d (\nrequester:\n"
3189 " group %d, volumeGroup=%d attributes=%s)\n"
3190 " higher priority source active:\n"
3191 " volumeGroup=%d attributes=%s) \n"
3192 " on output %zu, bailing out", __func__, productStrategy,
3193 group, group, toString(attributes).c_str(),
3194 client->volumeSource(), toString(client->attributes()).c_str(), i);
3195 applyVolume = false;
3196 isPreempted = true;
3197 break;
3198 }
3199 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003200 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003201 applyVolume = true;
3202 }
3203 }
3204 if (isPreempted || applyVolume) {
3205 break;
3206 }
3207 }
3208 if (!applyVolume) {
3209 continue; // next output
3210 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003211 }
François Gaffieed91f582020-01-31 10:35:37 +01003212 //FIXME: workaround for truncated touch sounds
3213 // delayed volume change for system stream to be removed when the problem is
3214 // handled by system UI
3215 status_t volStatus = checkAndSetVolume(
3216 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003217 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003218 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3219 if (volStatus != NO_ERROR) {
3220 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003221 }
3222 }
François Gaffiecfe17322018-11-07 13:41:29 +01003223 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3224 return status;
3225}
3226
François Gaffieaaac0fd2018-11-22 17:56:39 +01003227status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003228 audio_devices_t device,
3229 IVolumeCurves &volumeCurves)
3230{
3231 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3232 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003233 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3234 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003235 (index > volumeCurves.getVolumeIndexMax())) {
3236 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3237 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3238 return BAD_VALUE;
3239 }
3240 if (!audio_is_output_device(device)) {
3241 return BAD_VALUE;
3242 }
3243
3244 // Force max volume if stream cannot be muted
3245 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3246
François Gaffieaaac0fd2018-11-22 17:56:39 +01003247 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003248 volumeCurves.addCurrentVolumeIndex(device, index);
3249 return NO_ERROR;
3250}
3251
3252status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3253 int &index,
3254 audio_devices_t device)
3255{
3256 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3257 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003258 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003259 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003260 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003261 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003262 }
jiabin9a3361e2019-10-01 09:38:30 -07003263 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003264}
3265
3266status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3267 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003268 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003269{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003270 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003271 return BAD_VALUE;
3272 }
jiabin9a3361e2019-10-01 09:38:30 -07003273 index = curves.getVolumeIndex(deviceTypes);
3274 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003275 return NO_ERROR;
3276}
3277
3278status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3279 int &index)
3280{
3281 index = getVolumeCurves(attr).getVolumeIndexMin();
3282 return NO_ERROR;
3283}
3284
3285status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3286 int &index)
3287{
3288 index = getVolumeCurves(attr).getVolumeIndexMax();
3289 return NO_ERROR;
3290}
3291
Eric Laurent36829f92017-04-07 19:04:42 -07003292audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003293{
3294 // select one output among several suitable for global effects.
3295 // The priority is as follows:
3296 // 1: An offloaded output. If the effect ends up not being offloadable,
3297 // AudioFlinger will invalidate the track and the offloaded output
3298 // will be closed causing the effect to be moved to a PCM output.
3299 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003300 // 3: The primary output
3301 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003302
François Gaffiec005e562018-11-06 15:04:49 +01003303 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3304 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003305 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003306
Eric Laurent36829f92017-04-07 19:04:42 -07003307 if (outputs.size() == 0) {
3308 return AUDIO_IO_HANDLE_NONE;
3309 }
Eric Laurente552edb2014-03-10 17:42:56 -07003310
Eric Laurent36829f92017-04-07 19:04:42 -07003311 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3312 bool activeOnly = true;
3313
3314 while (output == AUDIO_IO_HANDLE_NONE) {
3315 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3316 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3317 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3318
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003319 for (audio_io_handle_t output : outputs) {
3320 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003321 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003322 continue;
3323 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003324 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3325 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003326 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003327 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003328 }
3329 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003330 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003331 }
3332 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003333 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003334 }
3335 }
3336 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3337 output = outputOffloaded;
3338 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3339 output = outputDeepBuffer;
3340 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3341 output = outputPrimary;
3342 } else {
3343 output = outputs[0];
3344 }
3345 activeOnly = false;
3346 }
3347
3348 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003349 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003350 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3351 mMusicEffectOutput = output;
3352 }
3353
3354 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003355 return output;
3356}
3357
Eric Laurent36829f92017-04-07 19:04:42 -07003358audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3359{
3360 return selectOutputForMusicEffects();
3361}
3362
Eric Laurente0720872014-03-11 09:30:41 -07003363status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003364 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003365 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003366 int session,
3367 int id)
3368{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003369 if (session != AUDIO_SESSION_DEVICE) {
3370 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003371 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003372 index = mInputs.indexOfKey(io);
3373 if (index < 0) {
3374 ALOGW("registerEffect() unknown io %d", io);
3375 return INVALID_OPERATION;
3376 }
Eric Laurente552edb2014-03-10 17:42:56 -07003377 }
3378 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003379 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3380 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3381 || strategy == PRODUCT_STRATEGY_NONE));
3382 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003383}
3384
Eric Laurentc241b0d2018-11-28 09:08:49 -08003385status_t AudioPolicyManager::unregisterEffect(int id)
3386{
3387 if (mEffects.getEffect(id) == nullptr) {
3388 return INVALID_OPERATION;
3389 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003390 if (mEffects.isEffectEnabled(id)) {
3391 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3392 setEffectEnabled(id, false);
3393 }
3394 return mEffects.unregisterEffect(id);
3395}
3396
3397status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3398{
3399 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3400 if (effect == nullptr) {
3401 return INVALID_OPERATION;
3402 }
3403
3404 status_t status = mEffects.setEffectEnabled(id, enabled);
3405 if (status == NO_ERROR) {
3406 mInputs.trackEffectEnabled(effect, enabled);
3407 }
3408 return status;
3409}
3410
Eric Laurent6c796322019-04-09 14:13:17 -07003411
3412status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3413{
3414 mEffects.moveEffects(ids, io);
3415 return NO_ERROR;
3416}
3417
Eric Laurentc75307b2015-03-17 15:29:32 -07003418bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3419{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003420 auto vs = toVolumeSource(stream, false);
3421 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003422}
3423
3424bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3425{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003426 auto vs = toVolumeSource(stream, false);
3427 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003428}
3429
Eric Laurente0720872014-03-11 09:30:41 -07003430bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003431{
3432 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003433 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003434 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003435 return true;
3436 }
3437 }
3438 return false;
3439}
3440
Eric Laurent275e8e92014-11-30 15:14:47 -08003441// Register a list of custom mixes with their attributes and format.
3442// When a mix is registered, corresponding input and output profiles are
3443// added to the remote submix hw module. The profile contains only the
3444// parameters (sampling rate, format...) specified by the mix.
3445// The corresponding input remote submix device is also connected.
3446//
3447// When a remote submix device is connected, the address is checked to select the
3448// appropriate profile and the corresponding input or output stream is opened.
3449//
3450// When capture starts, getInputForAttr() will:
3451// - 1 look for a mix matching the address passed in attribtutes tags if any
3452// - 2 if none found, getDeviceForInputSource() will:
3453// - 2.1 look for a mix matching the attributes source
3454// - 2.2 if none found, default to device selection by policy rules
3455// At this time, the corresponding output remote submix device is also connected
3456// and active playback use cases can be transferred to this mix if needed when reconnecting
3457// after AudioTracks are invalidated
3458//
3459// When playback starts, getOutputForAttr() will:
3460// - 1 look for a mix matching the address passed in attribtutes tags if any
3461// - 2 if none found, look for a mix matching the attributes usage
3462// - 3 if none found, default to device and output selection by policy rules.
3463
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003464status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003465{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003466 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3467 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003468 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003469 sp<HwModule> rSubmixModule;
3470 // examine each mix's route type
3471 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003472 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003473 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3474 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3475 ALOGE("Unsupported Policy Mix %zu of %zu: "
3476 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3477 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003478 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003479 break;
3480 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003481 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3482 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003483 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003484 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3485 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003486 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003487 rSubmixModule = mHwModules.getModuleFromName(
3488 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3489 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003490 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003491 i);
3492 res = INVALID_OPERATION;
3493 break;
3494 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003495 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003496
Eric Laurent97ac8712018-07-27 18:59:02 -07003497 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003498 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003499 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003500 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003501 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3502 } else {
3503 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3504 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003505 }
François Gaffie036e1e92015-03-19 10:16:24 +01003506
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003507 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003508 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003509 res = INVALID_OPERATION;
3510 break;
3511 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003512 audio_config_t outputConfig = mix.mFormat;
3513 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003514 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3515 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003516 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3517 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003518 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003519 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003520 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003521 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003522
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003523 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003524 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3525 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3526 ALOGE("Failed to set remote submix device available, type %u, address %s",
3527 mix.mDeviceType, address.string());
3528 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003529 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003530 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3531 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003532 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003533 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003534 i, mixes.size(), type, address.string());
3535
3536 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3537 mix.mDeviceType, mix.mDeviceAddress,
3538 String8(), AUDIO_FORMAT_DEFAULT);
3539 if (device == nullptr) {
3540 res = INVALID_OPERATION;
3541 break;
3542 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003543
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003544 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003545 // First try to find an already opened output supporting the device
3546 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003547 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003548
Eric Laurentc529cf62020-04-17 18:19:10 -07003549 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003550 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003551 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3552 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003553 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003554 } else {
3555 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003556 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003557 }
3558 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003559 // If no output found, try to find a direct output profile supporting the device
3560 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3561 sp<HwModule> module = mHwModules[i];
3562 for (size_t j = 0;
3563 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3564 j++) {
3565 sp<IOProfile> profile = module->getOutputProfiles()[j];
3566 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3567 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3568 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3569 address.string());
3570 res = INVALID_OPERATION;
3571 } else {
3572 foundOutput = true;
3573 }
3574 }
3575 }
3576 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003577 if (res != NO_ERROR) {
3578 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003579 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003580 res = INVALID_OPERATION;
3581 break;
3582 } else if (!foundOutput) {
3583 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003584 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003585 res = INVALID_OPERATION;
3586 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003587 } else {
3588 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003589 }
Eric Laurentc722f302014-12-10 11:21:49 -08003590 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003591 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003592 if (res != NO_ERROR) {
3593 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003594 } else if (checkOutputs) {
3595 checkForDeviceAndOutputChanges();
3596 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003597 }
3598 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003599}
3600
3601status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3602{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003603 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003604 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003605 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003606 sp<HwModule> rSubmixModule;
3607 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003608 for (const auto& mix : mixes) {
3609 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003610
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003611 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003612 rSubmixModule = mHwModules.getModuleFromName(
3613 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3614 if (rSubmixModule == 0) {
3615 res = INVALID_OPERATION;
3616 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003617 }
3618 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003619
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003620 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003621
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003622 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003623 res = INVALID_OPERATION;
3624 continue;
3625 }
3626
Kevin Rocard04ed0462019-05-02 17:53:24 -07003627 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3628 if (getDeviceConnectionState(device, address.string()) ==
3629 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3630 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3631 address.string(), "remote-submix",
3632 AUDIO_FORMAT_DEFAULT);
3633 if (res != OK) {
3634 ALOGE("Error making RemoteSubmix device unavailable for mix "
3635 "with type %d, address %s", device, address.string());
3636 }
3637 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003638 }
jiabin5740f082019-08-19 15:08:30 -07003639 rSubmixModule->removeOutputProfile(address.c_str());
3640 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003641
Kevin Rocard153f92d2018-12-18 18:33:28 -08003642 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003643 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003644 res = INVALID_OPERATION;
3645 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003646 } else {
3647 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003648 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003649 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003650 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003651 if (res == NO_ERROR && checkOutputs) {
3652 checkForDeviceAndOutputChanges();
3653 updateCallAndOutputRouting();
3654 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003655 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003656}
3657
Mikhail Naganov100f0122018-11-29 11:22:16 -08003658void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3659{
3660 size_t i = 0;
3661 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3662 for (const auto& fmt : mManualSurroundFormats) {
3663 if (i++ != 0) dst->append(", ");
3664 std::string sfmt;
3665 FormatConverter::toString(fmt, sfmt);
3666 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3667 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3668 }
3669}
3670
Eric Laurentc529cf62020-04-17 18:19:10 -07003671// Returns true if all devices types match the predicate and are supported by one HW module
3672bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003673 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003674 std::function<bool(audio_devices_t)> predicate,
3675 const char *context) {
3676 for (size_t i = 0; i < devices.size(); i++) {
3677 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003678 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003679 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003680 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003681 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003682 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003683 return false;
3684 }
3685 }
3686 return true;
3687}
3688
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003689status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003690 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003691 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003692 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3693 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003694 }
3695 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003696 if (res != NO_ERROR) {
3697 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3698 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003699 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003700
3701 checkForDeviceAndOutputChanges();
3702 updateCallAndOutputRouting();
3703
3704 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003705}
3706
3707status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3708 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003709 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3710 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003711 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003712 __FUNCTION__, uid);
3713 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003714 }
3715
Eric Laurentc529cf62020-04-17 18:19:10 -07003716 checkForDeviceAndOutputChanges();
3717 updateCallAndOutputRouting();
3718
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003719 return res;
3720}
3721
Eric Laurent2517af32020-11-25 15:31:27 +01003722
jiabin0a488932020-08-07 17:32:40 -07003723status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3724 device_role_t role,
3725 const AudioDeviceTypeAddrVector &devices) {
3726 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3727 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003728
Eric Laurentc529cf62020-04-17 18:19:10 -07003729 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003730 return BAD_VALUE;
3731 }
jiabin0a488932020-08-07 17:32:40 -07003732 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003733 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003734 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3735 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003736 return status;
3737 }
3738
3739 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003740
3741 bool forceVolumeReeval = false;
3742 // FIXME: workaround for truncated touch sounds
3743 // to be removed when the problem is handled by system UI
3744 uint32_t delayMs = 0;
3745 if (strategy == mCommunnicationStrategy) {
3746 forceVolumeReeval = true;
3747 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3748 updateInputRouting();
3749 }
3750 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003751
3752 return NO_ERROR;
3753}
3754
3755void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3756{
3757 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003758 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003759 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003760 // Only apply special touch sound delay once
3761 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003762 }
3763 for (size_t i = 0; i < mOutputs.size(); i++) {
3764 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3765 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003766 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3767 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003768 // As done in setDeviceConnectionState, we could also fix default device issue by
3769 // preventing the force re-routing in case of default dev that distinguishes on address.
3770 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003771 bool forceRouting = !newDevices.isEmpty();
3772 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3773 true /*requiresMuteCheck*/,
3774 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003775 // Only apply special touch sound delay once
3776 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003777 }
3778 if (forceVolumeReeval && !newDevices.isEmpty()) {
3779 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3780 }
3781 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003782 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003783}
3784
Eric Laurent2517af32020-11-25 15:31:27 +01003785void AudioPolicyManager::updateInputRouting() {
3786 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303787 // Skip for hotword recording as the input device switch
3788 // is handled within sound trigger HAL
3789 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3790 continue;
3791 }
Eric Laurent2517af32020-11-25 15:31:27 +01003792 auto newDevice = getNewInputDevice(activeDesc);
3793 // Force new input selection if the new device can not be reached via current input
3794 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3795 setInputDevice(activeDesc->mIoHandle, newDevice);
3796 } else {
3797 closeInput(activeDesc->mIoHandle);
3798 }
3799 }
3800}
3801
jiabin0a488932020-08-07 17:32:40 -07003802status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3803 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003804{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003805 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003806
jiabin0a488932020-08-07 17:32:40 -07003807 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003808 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003809 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3810 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003811 return status;
3812 }
3813
3814 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003815
3816 bool forceVolumeReeval = false;
3817 // FIXME: workaround for truncated touch sounds
3818 // to be removed when the problem is handled by system UI
3819 uint32_t delayMs = 0;
3820 if (strategy == mCommunnicationStrategy) {
3821 forceVolumeReeval = true;
3822 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3823 updateInputRouting();
3824 }
3825 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003826
3827 return NO_ERROR;
3828}
3829
jiabin0a488932020-08-07 17:32:40 -07003830status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3831 device_role_t role,
3832 AudioDeviceTypeAddrVector &devices) {
3833 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003834}
3835
Jiabin Huang3b98d322020-09-03 17:54:16 +00003836status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3837 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3838 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3839 dumpAudioDeviceTypeAddrVector(devices).c_str());
3840
Mikhail Naganov55773032020-10-01 15:08:13 -07003841 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003842 return BAD_VALUE;
3843 }
3844 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3845 ALOGW_IF(status != NO_ERROR,
3846 "Engine could not set preferred devices %s for audio source %d role %d",
3847 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3848
3849 return status;
3850}
3851
3852status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3853 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3854 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3855 dumpAudioDeviceTypeAddrVector(devices).c_str());
3856
Mikhail Naganov55773032020-10-01 15:08:13 -07003857 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003858 return BAD_VALUE;
3859 }
3860 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3861 ALOGW_IF(status != NO_ERROR,
3862 "Engine could not add preferred devices %s for audio source %d role %d",
3863 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3864
Eric Laurent2517af32020-11-25 15:31:27 +01003865 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003866 return status;
3867}
3868
3869status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3870 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3871{
3872 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3873 dumpAudioDeviceTypeAddrVector(devices).c_str());
3874
Mikhail Naganov55773032020-10-01 15:08:13 -07003875 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003876 return BAD_VALUE;
3877 }
3878
3879 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3880 audioSource, role, devices);
3881 ALOGW_IF(status != NO_ERROR,
3882 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3883
Eric Laurent2517af32020-11-25 15:31:27 +01003884 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003885 return status;
3886}
3887
3888status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3889 device_role_t role) {
3890 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3891
3892 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3893 ALOGW_IF(status != NO_ERROR,
3894 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3895
Eric Laurent2517af32020-11-25 15:31:27 +01003896 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003897 return status;
3898}
3899
3900status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3901 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3902 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3903}
3904
Oscar Azucena90e77632019-11-27 17:12:28 -08003905status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003906 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003907 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003908 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3909 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003910 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003911 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3912 if (status != NO_ERROR) {
3913 ALOGE("%s() could not set device affinity for userId %d",
3914 __FUNCTION__, userId);
3915 return status;
3916 }
3917
3918 // reevaluate outputs for all devices
3919 checkForDeviceAndOutputChanges();
3920 updateCallAndOutputRouting();
3921
3922 return NO_ERROR;
3923}
3924
3925status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003926 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003927 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3928 if (status != NO_ERROR) {
3929 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3930 __FUNCTION__, userId);
3931 return status;
3932 }
3933
3934 // reevaluate outputs for all devices
3935 checkForDeviceAndOutputChanges();
3936 updateCallAndOutputRouting();
3937
3938 return NO_ERROR;
3939}
3940
Andy Hungc29d82b2018-10-05 12:23:17 -07003941void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003942{
Andy Hungc29d82b2018-10-05 12:23:17 -07003943 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003944 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003945 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003946 std::string stateLiteral;
3947 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003948 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003949 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3950 "communications", "media", "record", "dock", "system",
3951 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3952 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3953 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003954 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3955 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3956 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3957 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3958 dst->append(" (MANUAL: ");
3959 dumpManualSurroundFormats(dst);
3960 dst->append(")");
3961 }
3962 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003963 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003964 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3965 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003966 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003967 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003968
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003969 dst->append("\n");
3970 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3971 dst->append("\n");
3972 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003973 mHwModulesAll.dump(dst);
3974 mOutputs.dump(dst);
3975 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003976 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003977 mAudioPatches.dump(dst);
3978 mPolicyMixes.dump(dst);
3979 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003980
Kevin Rocardb99cc752019-03-21 20:52:24 -07003981 dst->appendFormat(" AllowedCapturePolicies:\n");
3982 for (auto& policy : mAllowedCapturePolicies) {
3983 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3984 }
3985
jiabina84c3d32022-12-02 18:59:55 +00003986 dst->appendFormat(" Preferred mixer audio configuration:\n");
3987 for (const auto it : mPreferredMixerAttrInfos) {
3988 dst->appendFormat(" - device port id: %d\n", it.first);
3989 for (const auto preferredMixerInfoIt : it.second) {
3990 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
3991 preferredMixerInfoIt.second->dump(dst);
3992 }
3993 }
3994
François Gaffiec005e562018-11-06 15:04:49 +01003995 dst->appendFormat("\nPolicy Engine dump:\n");
3996 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003997}
3998
3999status_t AudioPolicyManager::dump(int fd)
4000{
4001 String8 result;
4002 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07004003 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004004 return NO_ERROR;
4005}
4006
Kevin Rocardb99cc752019-03-21 20:52:24 -07004007status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4008{
4009 mAllowedCapturePolicies[uid] = capturePolicy;
4010 return NO_ERROR;
4011}
4012
Eric Laurente552edb2014-03-10 17:42:56 -07004013// This function checks for the parameters which can be offloaded.
4014// This can be enhanced depending on the capability of the DSP and policy
4015// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004016audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004017{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004018 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004019 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004020 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004021 offloadInfo.format,
4022 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4023 offloadInfo.has_video);
4024
jiabin2b9d5a12021-12-10 01:06:29 +00004025 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004026 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004027 }
4028
4029 // See if there is a profile to support this.
4030 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004031 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004032 offloadInfo.sample_rate,
4033 offloadInfo.format,
4034 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004035 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4036 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004037 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4038 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4039 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004040 if (profile == nullptr) {
4041 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4042 }
4043 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4044 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4045 }
4046 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004047}
4048
Michael Chana94fbb22018-04-24 14:31:19 +10004049bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4050 const audio_attributes_t& attributes) {
4051 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004052 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004053 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4054 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004055 config.sample_rate,
4056 config.format,
4057 config.channel_mask,
4058 output_flags,
4059 true /* directOnly */);
4060 ALOGV("%s() profile %sfound with name: %s, "
4061 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4062 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004063 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004064 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004065
4066 // also try the MSD module if compatible profile not found
4067 if (profile == nullptr) {
4068 profile = getMsdProfileForOutput(outputDevices,
4069 config.sample_rate,
4070 config.format,
4071 config.channel_mask,
4072 output_flags,
4073 true /* directOnly */);
4074 ALOGV("%s() MSD profile %sfound with name: %s, "
4075 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4076 __FUNCTION__, profile != 0 ? "" : "NOT ",
4077 (profile != 0 ? profile->getTagName().c_str() : "null"),
4078 config.sample_rate, config.format, config.channel_mask, output_flags);
4079 }
4080 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004081}
4082
jiabin2b9d5a12021-12-10 01:06:29 +00004083bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4084 bool durationIgnored) {
4085 if (mMasterMono) {
4086 return false; // no offloading if mono is set.
4087 }
4088
4089 // Check if offload has been disabled
4090 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4091 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4092 return false;
4093 }
4094
4095 // Check if stream type is music, then only allow offload as of now.
4096 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4097 {
4098 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4099 return false;
4100 }
4101
4102 //TODO: enable audio offloading with video when ready
4103 const bool allowOffloadWithVideo =
4104 property_get_bool("audio.offload.video", false /* default_value */);
4105 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4106 ALOGV("%s: has_video == true, returning false", __func__);
4107 return false;
4108 }
4109
4110 //If duration is less than minimum value defined in property, return false
4111 const int min_duration_secs = property_get_int32(
4112 "audio.offload.min.duration.secs", -1 /* default_value */);
4113 if (!durationIgnored) {
4114 if (min_duration_secs >= 0) {
4115 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4116 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4117 __func__, min_duration_secs);
4118 return false;
4119 }
4120 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4121 ALOGV("%s: Offload denied by duration < default min(=%u)",
4122 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4123 return false;
4124 }
4125 }
4126
4127 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4128 // creating an offloaded track and tearing it down immediately after start when audioflinger
4129 // detects there is an active non offloadable effect.
4130 // FIXME: We should check the audio session here but we do not have it in this context.
4131 // This may prevent offloading in rare situations where effects are left active by apps
4132 // in the background.
4133 if (mEffects.isNonOffloadableEffectEnabled()) {
4134 return false;
4135 }
4136
4137 return true;
4138}
4139
4140audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4141 const audio_config_t *config) {
4142 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4143 offloadInfo.format = config->format;
4144 offloadInfo.sample_rate = config->sample_rate;
4145 offloadInfo.channel_mask = config->channel_mask;
4146 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4147 offloadInfo.has_video = false;
4148 offloadInfo.is_streaming = false;
4149 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4150
4151 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4152 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4153 audio_flags_to_audio_output_flags(attr->flags, &flags);
4154 // only retain flags that will drive compressed offload or passthrough
4155 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4156 if (offloadPossible) {
4157 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4158 }
4159 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4160
Dorin Drimusfae3c642022-03-17 18:36:30 +01004161 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004162 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004163 DeviceVector outputDevices = engineOutputDevices;
4164 // the MSD module checks for different conditions and output devices
4165 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4166 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4167 continue;
4168 }
4169 outputDevices = getMsdAudioOutDevices();
4170 }
jiabin2b9d5a12021-12-10 01:06:29 +00004171 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004172 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004173 config->sample_rate, nullptr /*updatedSamplingRate*/,
4174 config->format, nullptr /*updatedFormat*/,
4175 config->channel_mask, nullptr /*updatedChannelMask*/,
4176 flags)) {
4177 continue;
4178 }
4179 // reject profiles not corresponding to a device currently available
4180 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4181 continue;
4182 }
4183 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4184 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004185 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004186 != AUDIO_DIRECT_NOT_SUPPORTED) {
4187 // Already reports offload gapless supported. No need to report offload support.
4188 continue;
4189 }
4190 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4191 != AUDIO_OUTPUT_FLAG_NONE) {
4192 // If offload gapless is reported, no need to report offload support.
4193 directMode = (audio_direct_mode_t) ((directMode &
4194 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4195 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4196 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004197 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004198 }
4199 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004200 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004201 }
4202 }
4203 }
4204 return directMode;
4205}
4206
Dorin Drimusf2196d82022-01-03 12:11:18 +01004207status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4208 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004209 if (mEffects.isNonOffloadableEffectEnabled()) {
4210 return OK;
4211 }
jiabinf1c73972022-04-14 16:28:52 -07004212 DeviceVector devices;
4213 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004214 if (status != OK) {
4215 return status;
4216 }
4217 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4218 if (devices.empty()) {
4219 return OK; // no output devices for the attributes
4220 }
jiabinf1c73972022-04-14 16:28:52 -07004221 return getProfilesForDevices(devices, audioProfilesVector,
4222 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004223}
4224
jiabina84c3d32022-12-02 18:59:55 +00004225status_t AudioPolicyManager::getSupportedMixerAttributes(
4226 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4227 ALOGV("%s, portId=%d", __func__, portId);
4228 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4229 if (deviceDescriptor == nullptr) {
4230 ALOGE("%s the requested device is currently unavailable", __func__);
4231 return BAD_VALUE;
4232 }
4233 for (const auto& hwModule : mHwModules) {
4234 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4235 if (curProfile->supportsDevice(deviceDescriptor)) {
4236 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4237 }
4238 }
4239 }
4240 return NO_ERROR;
4241}
4242
4243status_t AudioPolicyManager::setPreferredMixerAttributes(
4244 const audio_attributes_t *attr,
4245 audio_port_handle_t portId,
4246 uid_t uid,
4247 const audio_mixer_attributes_t *mixerAttributes) {
4248 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4249 "mixerBehavior=%d}, uid=%d, portId=%u",
4250 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4251 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4252 mixerAttributes->mixer_behavior, uid, portId);
4253 if (attr->usage != AUDIO_USAGE_MEDIA) {
4254 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4255 return BAD_VALUE;
4256 }
4257 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4258 if (deviceDescriptor == nullptr) {
4259 ALOGE("%s the requested device is currently unavailable", __func__);
4260 return BAD_VALUE;
4261 }
4262 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4263 ALOGE("%s(%d), type=%d, is not a usb output device",
4264 __func__, portId, deviceDescriptor->type());
4265 return BAD_VALUE;
4266 }
4267
4268 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4269 audio_flags_to_audio_output_flags(attr->flags, &flags);
4270 flags = (audio_output_flags_t) (flags |
4271 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4272 sp<IOProfile> profile = nullptr;
4273 DeviceVector devices(deviceDescriptor);
4274 for (const auto& hwModule : mHwModules) {
4275 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4276 if (curProfile->hasDynamicAudioProfile()
4277 && curProfile->isCompatibleProfile(devices,
4278 mixerAttributes->config.sample_rate,
4279 nullptr /*updatedSamplingRate*/,
4280 mixerAttributes->config.format,
4281 nullptr /*updatedFormat*/,
4282 mixerAttributes->config.channel_mask,
4283 nullptr /*updatedChannelMask*/,
4284 flags,
4285 false /*exactMatchRequiredForInputFlags*/)) {
4286 profile = curProfile;
4287 break;
4288 }
4289 }
4290 }
4291 if (profile == nullptr) {
4292 ALOGE("%s, there is no compatible profile found", __func__);
4293 return BAD_VALUE;
4294 }
4295
4296 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4297 sp<PreferredMixerAttributesInfo>::make(
4298 uid, portId, profile, flags, *mixerAttributes);
4299 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4300 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4301
4302 // If 1) there is any client from the preferred mixer configuration owner that is currently
4303 // active and matches the strategy and 2) current output is on the preferred device and the
4304 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4305 // configuration.
4306 std::vector<audio_io_handle_t> outputsToReopen;
4307 for (size_t i = 0; i < mOutputs.size(); i++) {
4308 const auto output = mOutputs.valueAt(i);
4309 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)
4310 && !output->isConfigurationMatched(mixerAttributes->config, flags)) {
4311 for (const auto& client : output->getActiveClients()) {
4312 if (client->uid() == uid && client->strategy() == strategy) {
4313 client->setIsInvalid();
4314 outputsToReopen.push_back(output->mIoHandle);
4315 }
4316 }
4317 }
4318 }
4319 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4320 config.sample_rate = mixerAttributes->config.sample_rate;
4321 config.channel_mask = mixerAttributes->config.channel_mask;
4322 config.format = mixerAttributes->config.format;
4323 for (const auto output : outputsToReopen) {
4324 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4325 }
4326
4327 return NO_ERROR;
4328}
4329
4330sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
4331 audio_port_handle_t devicePortId, product_strategy_t strategy) {
4332 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4333 if (it == mPreferredMixerAttrInfos.end()) {
4334 return nullptr;
4335 }
4336 auto mixerAttrInfoIt = it->second.find(strategy);
4337 if (mixerAttrInfoIt == it->second.end()) {
4338 return nullptr;
4339 }
4340 return mixerAttrInfoIt->second;
4341}
4342
4343status_t AudioPolicyManager::getPreferredMixerAttributes(
4344 const audio_attributes_t *attr,
4345 audio_port_handle_t portId,
4346 audio_mixer_attributes_t* mixerAttributes) {
4347 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4348 portId, mEngine->getProductStrategyForAttributes(*attr));
4349 if (info == nullptr) {
4350 return NAME_NOT_FOUND;
4351 }
4352 *mixerAttributes = info->getMixerAttributes();
4353 return NO_ERROR;
4354}
4355
4356status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4357 audio_port_handle_t portId,
4358 uid_t uid) {
4359 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4360 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4361 if (preferredMixerAttrInfo == nullptr) {
4362 return NAME_NOT_FOUND;
4363 }
4364 if (preferredMixerAttrInfo->getUid() != uid) {
4365 ALOGE("%s, requested uid=%d, owned uid=%d",
4366 __func__, uid, preferredMixerAttrInfo->getUid());
4367 return PERMISSION_DENIED;
4368 }
4369 mPreferredMixerAttrInfos[portId].erase(strategy);
4370 if (mPreferredMixerAttrInfos[portId].empty()) {
4371 mPreferredMixerAttrInfos.erase(portId);
4372 }
4373
4374 // Reconfig existing output
4375 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4376 for (size_t i = 0; i < mOutputs.size(); i++) {
4377 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4378 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4379 }
4380 }
4381 for (const auto output : potentialOutputsToReopen) {
4382 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4383 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4384 preferredMixerAttrInfo->getFlags())) {
4385 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4386 }
4387 }
4388 return NO_ERROR;
4389}
4390
Eric Laurent6a94d692014-05-20 11:18:06 -07004391status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4392 audio_port_type_t type,
4393 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004394 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004395 unsigned int *generation)
4396{
jiabin19cdba52020-11-24 11:28:58 -08004397 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4398 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004399 return BAD_VALUE;
4400 }
4401 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004402 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004403 *num_ports = 0;
4404 }
4405
4406 size_t portsWritten = 0;
4407 size_t portsMax = *num_ports;
4408 *num_ports = 0;
4409 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004410 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4411 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004412 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004413 for (const auto& dev : mAvailableOutputDevices) {
4414 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004415 continue;
4416 }
4417 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004418 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004419 }
4420 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004421 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004422 }
4423 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004424 for (const auto& dev : mAvailableInputDevices) {
4425 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004426 continue;
4427 }
4428 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004429 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004430 }
4431 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004432 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004433 }
4434 }
4435 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4436 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4437 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4438 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4439 }
4440 *num_ports += mInputs.size();
4441 }
4442 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004443 size_t numOutputs = 0;
4444 for (size_t i = 0; i < mOutputs.size(); i++) {
4445 if (!mOutputs[i]->isDuplicated()) {
4446 numOutputs++;
4447 if (portsWritten < portsMax) {
4448 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4449 }
4450 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004451 }
Eric Laurent84c70242014-06-23 08:46:27 -07004452 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004453 }
4454 }
jiabina84c3d32022-12-02 18:59:55 +00004455
Eric Laurent6a94d692014-05-20 11:18:06 -07004456 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004457 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004458 return NO_ERROR;
4459}
4460
jiabin19cdba52020-11-24 11:28:58 -08004461status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004462{
Eric Laurent99fcae42018-05-17 16:59:18 -07004463 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4464 return BAD_VALUE;
4465 }
4466 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4467 if (dev != 0) {
4468 dev->toAudioPort(port);
4469 return NO_ERROR;
4470 }
4471 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4472 if (dev != 0) {
4473 dev->toAudioPort(port);
4474 return NO_ERROR;
4475 }
4476 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4477 if (out != 0) {
4478 out->toAudioPort(port);
4479 return NO_ERROR;
4480 }
4481 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4482 if (in != 0) {
4483 in->toAudioPort(port);
4484 return NO_ERROR;
4485 }
4486 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004487}
4488
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004489status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4490 audio_patch_handle_t *handle,
4491 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004492{
François Gaffieafd4cea2019-11-18 15:50:22 +01004493 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004494 if (handle == NULL || patch == NULL) {
4495 return BAD_VALUE;
4496 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004497 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004498 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004499 return BAD_VALUE;
4500 }
4501 // only one source per audio patch supported for now
4502 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004503 return INVALID_OPERATION;
4504 }
Eric Laurent874c42872014-08-08 15:13:39 -07004505 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004506 return INVALID_OPERATION;
4507 }
Eric Laurent874c42872014-08-08 15:13:39 -07004508 for (size_t i = 0; i < patch->num_sinks; i++) {
4509 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4510 return INVALID_OPERATION;
4511 }
4512 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004513
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004514 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4515 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4516 if (srcDevice == nullptr || sinkDevice == nullptr) {
4517 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4518 return BAD_VALUE;
4519 }
4520 ALOGV("%s between source %s and sink %s", __func__,
4521 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4522 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4523 // Default attributes, default volume priority, not to infer with non raw audio patches.
4524 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4525 const struct audio_port_config *source = &patch->sources[0];
4526 sp<SourceClientDescriptor> sourceDesc =
4527 new InternalSourceClientDescriptor(
4528 portId, uid, attributes, *source, srcDevice, sinkDevice,
4529 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4530
4531 status_t status =
4532 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4533
4534 if (status != NO_ERROR) {
4535 return INVALID_OPERATION;
4536 }
4537 mAudioSources.add(portId, sourceDesc);
4538 return NO_ERROR;
4539}
4540
4541status_t AudioPolicyManager::connectAudioSourceToSink(
4542 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4543 const struct audio_patch *patch,
4544 audio_patch_handle_t &handle,
4545 uid_t uid, uint32_t delayMs)
4546{
4547 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4548 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4549 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4550 return INVALID_OPERATION;
4551 }
4552 sourceDesc->connect(handle, sinkDevice);
4553 if (isMsdPatch(handle)) {
4554 return NO_ERROR;
4555 }
4556 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4557 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4558 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4559 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4560 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4561 goto FailurePatchAdded;
4562 }
4563 status = swOutput->start();
4564 if (status != NO_ERROR) {
4565 goto FailureSourceAdded;
4566 }
4567 swOutput->addClient(sourceDesc);
4568 status = startSource(swOutput, sourceDesc, &delayMs);
4569 if (status != NO_ERROR) {
4570 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4571 goto FailureSourceActive;
4572 }
4573 if (delayMs != 0) {
4574 usleep(delayMs * 1000);
4575 }
4576 return NO_ERROR;
4577
4578FailureSourceActive:
4579 swOutput->stop();
4580 releaseOutput(sourceDesc->portId());
4581FailureSourceAdded:
4582 sourceDesc->setSwOutput(nullptr);
4583FailurePatchAdded:
4584 releaseAudioPatchInternal(handle);
4585 return INVALID_OPERATION;
4586}
4587
4588status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4589 audio_patch_handle_t *handle,
4590 uid_t uid, uint32_t delayMs,
4591 const sp<SourceClientDescriptor>& sourceDesc)
4592{
4593 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004594 sp<AudioPatch> patchDesc;
4595 ssize_t index = mAudioPatches.indexOfKey(*handle);
4596
François Gaffieafd4cea2019-11-18 15:50:22 +01004597 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4598 patch->sources[0].role,
4599 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004600#if LOG_NDEBUG == 0
4601 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004602 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4603 patch->sinks[i].role,
4604 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004605 }
4606#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004607
4608 if (index >= 0) {
4609 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004610 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4611 __func__, mUidCached, patchDesc->getUid(), uid);
4612 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004613 return INVALID_OPERATION;
4614 }
4615 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004616 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004617 }
4618
4619 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004620 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004621 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004622 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004623 return BAD_VALUE;
4624 }
Eric Laurent84c70242014-06-23 08:46:27 -07004625 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4626 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004627 if (patchDesc != 0) {
4628 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004629 ALOGV("%s source id differs for patch current id %d new id %d",
4630 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004631 return BAD_VALUE;
4632 }
4633 }
Eric Laurent874c42872014-08-08 15:13:39 -07004634 DeviceVector devices;
4635 for (size_t i = 0; i < patch->num_sinks; i++) {
4636 // Only support mix to devices connection
4637 // TODO add support for mix to mix connection
4638 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004639 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004640 return INVALID_OPERATION;
4641 }
4642 sp<DeviceDescriptor> devDesc =
4643 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4644 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004645 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004646 return BAD_VALUE;
4647 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004648
François Gaffie11d30102018-11-02 16:09:09 +01004649 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004650 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004651 NULL, // updatedSamplingRate
4652 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004653 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004654 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004655 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004656 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004657 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004658 return INVALID_OPERATION;
4659 }
4660 devices.add(devDesc);
4661 }
4662 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004663 return INVALID_OPERATION;
4664 }
Eric Laurent874c42872014-08-08 15:13:39 -07004665
Eric Laurent6a94d692014-05-20 11:18:06 -07004666 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004667 ALOGV("%s setting device %s on output %d",
4668 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004669 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004670 index = mAudioPatches.indexOfKey(*handle);
4671 if (index >= 0) {
4672 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004673 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004674 }
4675 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004676 patchDesc->setUid(uid);
4677 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004678 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004679 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004680 return INVALID_OPERATION;
4681 }
4682 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4683 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4684 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004685 // only one sink supported when connecting an input device to a mix
4686 if (patch->num_sinks > 1) {
4687 return INVALID_OPERATION;
4688 }
François Gaffie53615e22015-03-19 09:24:12 +01004689 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004690 if (inputDesc == NULL) {
4691 return BAD_VALUE;
4692 }
4693 if (patchDesc != 0) {
4694 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4695 return BAD_VALUE;
4696 }
4697 }
François Gaffie11d30102018-11-02 16:09:09 +01004698 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004699 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004700 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004701 return BAD_VALUE;
4702 }
4703
François Gaffie11d30102018-11-02 16:09:09 +01004704 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004705 patch->sinks[0].sample_rate,
4706 NULL, /*updatedSampleRate*/
4707 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004708 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004709 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004710 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004711 // FIXME for the parameter type,
4712 // and the NONE
4713 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004714 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004715 return INVALID_OPERATION;
4716 }
4717 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004718 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004719 device->toString().c_str(), inputDesc->mIoHandle);
4720 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004721 index = mAudioPatches.indexOfKey(*handle);
4722 if (index >= 0) {
4723 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004724 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004725 }
4726 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004727 patchDesc->setUid(uid);
4728 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004729 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004730 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004731 return INVALID_OPERATION;
4732 }
4733 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4734 // device to device connection
4735 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004736 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004737 return BAD_VALUE;
4738 }
4739 }
François Gaffie11d30102018-11-02 16:09:09 +01004740 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004741 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004742 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004743 return BAD_VALUE;
4744 }
Eric Laurent874c42872014-08-08 15:13:39 -07004745
Eric Laurent6a94d692014-05-20 11:18:06 -07004746 //update source and sink with our own data as the data passed in the patch may
4747 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004748 PatchBuilder patchBuilder;
4749 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004750
4751 // if first sink is to MSD, establish single MSD patch
4752 if (getMsdAudioOutDevices().contains(
4753 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4754 ALOGV("%s patching to MSD", __FUNCTION__);
4755 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4756 goto installPatch;
4757 }
4758
François Gaffieafd4cea2019-11-18 15:50:22 +01004759 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4760 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004761
Eric Laurent874c42872014-08-08 15:13:39 -07004762 for (size_t i = 0; i < patch->num_sinks; i++) {
4763 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004764 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004765 return INVALID_OPERATION;
4766 }
François Gaffie11d30102018-11-02 16:09:09 +01004767 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004768 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004769 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004770 return BAD_VALUE;
4771 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004772 audio_port_config sinkPortConfig = {};
4773 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4774 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004775
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004776 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4777 // volume management purpose (tracking activity)
4778 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4779 // in config XML to reach the sink so that is can be declared as available.
4780 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004781 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004782 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004783 // take care of dynamic routing for SwOutput selection,
4784 audio_attributes_t attributes = sourceDesc->attributes();
4785 audio_stream_type_t stream = sourceDesc->stream();
4786 audio_attributes_t resultAttr;
4787 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4788 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004789 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4790 config.channel_mask =
4791 (audio_channel_mask_get_representation(sourceMask)
4792 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4793 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004794 config.format = sourceDesc->config().format;
4795 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4796 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4797 bool isRequestedDeviceForExclusiveUse = false;
4798 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004799 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00004800 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004801 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4802 &stream, sourceDesc->uid(), &config, &flags,
4803 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00004804 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004805 if (output == AUDIO_IO_HANDLE_NONE) {
4806 ALOGV("%s no output for device %s",
4807 __FUNCTION__, sinkDevice->toString().c_str());
4808 return INVALID_OPERATION;
4809 }
4810 outputDesc = mOutputs.valueFor(output);
4811 if (outputDesc->isDuplicated()) {
4812 ALOGE("%s output is duplicated", __func__);
4813 return INVALID_OPERATION;
4814 }
François Gaffie7e39df22022-04-26 12:48:49 +02004815 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4816 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004817 } else {
4818 // Same for "raw patches" aka created from createAudioPatch API
4819 SortedVector<audio_io_handle_t> outputs =
4820 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4821 // if the sink device is reachable via an opened output stream, request to
4822 // go via this output stream by adding a second source to the patch
4823 // description
4824 output = selectOutput(outputs);
4825 if (output == AUDIO_IO_HANDLE_NONE) {
4826 ALOGE("%s no output available for internal patch sink", __func__);
4827 return INVALID_OPERATION;
4828 }
4829 outputDesc = mOutputs.valueFor(output);
4830 if (outputDesc->isDuplicated()) {
4831 ALOGV("%s output for device %s is duplicated",
4832 __func__, sinkDevice->toString().c_str());
4833 return INVALID_OPERATION;
4834 }
François Gaffie7e39df22022-04-26 12:48:49 +02004835 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004836 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004837 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004838 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004839 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004840 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004841 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4842 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004843 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4844 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004845 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004846 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004847 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004848 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004849 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004850 return INVALID_OPERATION;
4851 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004852 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004853 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004854 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004855 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004856 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004857 srcMixPortConfig.ext.mix.usecase.stream =
4858 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004859 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4860 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004861 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004862 }
Eric Laurent83b88082014-06-20 18:31:16 -07004863 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004864 }
4865 // TODO: check from routing capabilities in config file and other conflicting patches
4866
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004867installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004868 status_t status = installPatch(
4869 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004870 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004871 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004872 return INVALID_OPERATION;
4873 }
4874 } else {
4875 return BAD_VALUE;
4876 }
4877 } else {
4878 return BAD_VALUE;
4879 }
4880 return NO_ERROR;
4881}
4882
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004883status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004884{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004885 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004886 ssize_t index = mAudioPatches.indexOfKey(handle);
4887
4888 if (index < 0) {
4889 return BAD_VALUE;
4890 }
4891 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004892 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4893 __func__, mUidCached, patchDesc->getUid(), uid);
4894 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004895 return INVALID_OPERATION;
4896 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004897 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4898 for (size_t i = 0; i < mAudioSources.size(); i++) {
4899 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4900 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4901 portId = sourceDesc->portId();
4902 break;
4903 }
4904 }
4905 return portId != AUDIO_PORT_HANDLE_NONE ?
4906 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004907}
Eric Laurent6a94d692014-05-20 11:18:06 -07004908
François Gaffieafd4cea2019-11-18 15:50:22 +01004909status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004910 uint32_t delayMs,
4911 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004912{
4913 ALOGV("%s patch %d", __func__, handle);
4914 if (mAudioPatches.indexOfKey(handle) < 0) {
4915 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4916 return BAD_VALUE;
4917 }
4918 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004919 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004920 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004921 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004922 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004923 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004924 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004925 return BAD_VALUE;
4926 }
4927
François Gaffie11d30102018-11-02 16:09:09 +01004928 setOutputDevices(outputDesc,
4929 getNewOutputDevices(outputDesc, true /*fromCache*/),
4930 true,
4931 0,
4932 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004933 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4934 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004935 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004936 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004937 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004938 return BAD_VALUE;
4939 }
4940 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004941 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004942 true,
4943 NULL);
4944 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004945 status_t status =
4946 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4947 ALOGV("%s patch panel returned %d patchHandle %d",
4948 __func__, status, patchDesc->getAfHandle());
4949 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004951 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004952 // SW or HW Bridge
4953 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4954 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004955 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004956 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4957 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4958 outputDesc = sourceDesc->swOutput().promote();
4959 }
4960 if (outputDesc == nullptr) {
4961 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4962 // releaseOutput has already called closeOutput in case of direct output
4963 return NO_ERROR;
4964 }
François Gaffie7e39df22022-04-26 12:48:49 +02004965 patchHandle = outputDesc->getPatchHandle();
4966 // When a Sw bridge is released, the mixer used by this bridge will release its
4967 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4968 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4969 // updating hal patch handle (prevent leaks).
4970 // While using a HwBridge, force reconsidering device only if not reusing an existing
4971 // output and no more activity on output (will force to close).
4972 bool force = sourceDesc->useSwBridge() ||
4973 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4974 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4975 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4976 // Reconsider device only for cases:
4977 // 1 / Active Output
4978 // 2 / Inactive Output previously hosting HwBridge
4979 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4980 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4981 sourceDesc->canCloseOutput();
4982 setOutputDevices(outputDesc,
4983 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4984 outputDesc->devices(),
4985 force,
4986 0,
4987 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 } else {
4989 return BAD_VALUE;
4990 }
4991 } else {
4992 return BAD_VALUE;
4993 }
4994 return NO_ERROR;
4995}
4996
4997status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4998 struct audio_patch *patches,
4999 unsigned int *generation)
5000{
François Gaffie53615e22015-03-19 09:24:12 +01005001 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 return BAD_VALUE;
5003 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005004 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005005 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005006}
5007
Eric Laurente1715a42014-05-20 11:30:42 -07005008status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005009{
Eric Laurente1715a42014-05-20 11:30:42 -07005010 ALOGV("setAudioPortConfig()");
5011
5012 if (config == NULL) {
5013 return BAD_VALUE;
5014 }
5015 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5016 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005017 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5018 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005019 }
5020
Eric Laurenta121f902014-06-03 13:32:54 -07005021 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005022 if (config->type == AUDIO_PORT_TYPE_MIX) {
5023 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005024 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005025 if (outputDesc == NULL) {
5026 return BAD_VALUE;
5027 }
Eric Laurent84c70242014-06-23 08:46:27 -07005028 ALOG_ASSERT(!outputDesc->isDuplicated(),
5029 "setAudioPortConfig() called on duplicated output %d",
5030 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005031 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005032 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005033 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005034 if (inputDesc == NULL) {
5035 return BAD_VALUE;
5036 }
Eric Laurenta121f902014-06-03 13:32:54 -07005037 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005038 } else {
5039 return BAD_VALUE;
5040 }
5041 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5042 sp<DeviceDescriptor> deviceDesc;
5043 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5044 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5045 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5046 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5047 } else {
5048 return BAD_VALUE;
5049 }
5050 if (deviceDesc == NULL) {
5051 return BAD_VALUE;
5052 }
Eric Laurenta121f902014-06-03 13:32:54 -07005053 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005054 } else {
5055 return BAD_VALUE;
5056 }
5057
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005058 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005059 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5060 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005061 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005062 audioPortConfig->toAudioPortConfig(&newConfig, config);
5063 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005064 }
Eric Laurenta121f902014-06-03 13:32:54 -07005065 if (status != NO_ERROR) {
5066 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005067 }
Eric Laurente1715a42014-05-20 11:30:42 -07005068
5069 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005070}
5071
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005072void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5073{
Eric Laurentd60560a2015-04-10 11:31:20 -07005074 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005075 clearAudioPatches(uid);
5076 clearSessionRoutes(uid);
5077}
5078
Eric Laurent6a94d692014-05-20 11:18:06 -07005079void AudioPolicyManager::clearAudioPatches(uid_t uid)
5080{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005081 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005082 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005083 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005084 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005085 }
5086 }
5087}
5088
François Gaffiec005e562018-11-06 15:04:49 +01005089void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005090{
François Gaffiec005e562018-11-06 15:04:49 +01005091 // Take the first attributes following the product strategy as it is used to retrieve the routed
5092 // device. All attributes wihin a strategy follows the same "routing strategy"
5093 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5094 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005095 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005096 for (size_t j = 0; j < mOutputs.size(); j++) {
5097 if (mOutputs.keyAt(j) == ouptutToSkip) {
5098 continue;
5099 }
5100 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005101 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005102 continue;
5103 }
5104 // If the default device for this strategy is on another output mix,
5105 // invalidate all tracks in this strategy to force re connection.
5106 // Otherwise select new device on the output mix.
5107 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01005108 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
5109 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005110 }
5111 } else {
François Gaffie11d30102018-11-02 16:09:09 +01005112 setOutputDevices(
5113 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005114 }
5115 }
5116}
5117
5118void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5119{
5120 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005121 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005122 for (size_t i = 0; i < mOutputs.size(); i++) {
5123 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005124 for (const auto& client : outputDesc->getClientIterable()) {
5125 if (client->hasPreferredDevice() && client->uid() == uid) {
5126 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005127 auto clientStrategy = client->strategy();
5128 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5129 end(affectedStrategies)) {
5130 continue;
5131 }
5132 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005133 }
5134 }
5135 }
5136 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005137 for (const auto& strategy : affectedStrategies) {
5138 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005139 }
5140
5141 // remove input routes associated with this uid
5142 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005143 for (size_t i = 0; i < mInputs.size(); i++) {
5144 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005145 for (const auto& client : inputDesc->getClientIterable()) {
5146 if (client->hasPreferredDevice() && client->uid() == uid) {
5147 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5148 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005149 }
5150 }
5151 }
5152 // reroute inputs if necessary
5153 SortedVector<audio_io_handle_t> inputsToClose;
5154 for (size_t i = 0; i < mInputs.size(); i++) {
5155 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005156 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005157 inputsToClose.add(inputDesc->mIoHandle);
5158 }
5159 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005160 for (const auto& input : inputsToClose) {
5161 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005162 }
5163}
5164
Eric Laurentd60560a2015-04-10 11:31:20 -07005165void AudioPolicyManager::clearAudioSources(uid_t uid)
5166{
5167 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005168 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5169 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005170 stopAudioSource(mAudioSources.keyAt(i));
5171 }
5172 }
5173}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005174
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005175status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5176 audio_io_handle_t *ioHandle,
5177 audio_devices_t *device)
5178{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005179 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5180 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005181 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01005182 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005183
François Gaffiedf372692015-03-19 10:43:27 +01005184 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005185}
5186
Eric Laurentd60560a2015-04-10 11:31:20 -07005187status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005188 const audio_attributes_t *attributes,
5189 audio_port_handle_t *portId,
5190 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005191{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005192 ALOGV("%s", __FUNCTION__);
5193 *portId = AUDIO_PORT_HANDLE_NONE;
5194
5195 if (source == NULL || attributes == NULL || portId == NULL) {
5196 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5197 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005198 return BAD_VALUE;
5199 }
5200
Eric Laurentd60560a2015-04-10 11:31:20 -07005201 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5202 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005203 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5204 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005205 return INVALID_OPERATION;
5206 }
5207
François Gaffie11d30102018-11-02 16:09:09 +01005208 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005209 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005210 String8(source->ext.device.address),
5211 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005212 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005213 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005214 return BAD_VALUE;
5215 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005216
jiabin4ef93452019-09-10 14:29:54 -07005217 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005218
François Gaffieaaac0fd2018-11-22 17:56:39 +01005219 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005220 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005221 mEngine->getStreamTypeForAttributes(*attributes),
5222 mEngine->getProductStrategyForAttributes(*attributes),
5223 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005224
5225 status_t status = connectAudioSource(sourceDesc);
5226 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005227 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005228 }
5229 return status;
5230}
5231
Francois Gaffie601801d2021-06-22 13:27:39 +02005232sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5233 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5234{
5235 ALOGV("%s", __FUNCTION__);
5236 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5237
5238 status_t status = startAudioSource(source, attributes, &portId, uid);
5239 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5240 return mAudioSources.valueFor(portId);
5241}
5242
5243
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005244status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005245{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005246 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005247
5248 // make sure we only have one patch per source.
5249 disconnectAudioSource(sourceDesc);
5250
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005251 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005252 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5253 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5254 sourceDesc->srcDevice()->type(),
5255 String8(sourceDesc->srcDevice()->address().c_str()),
5256 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005257 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005258 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005259 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005260 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005261 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5262 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5263 return INVALID_OPERATION;
5264 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005265 PatchBuilder patchBuilder;
5266 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5267 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005268
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005269 return connectAudioSourceToSink(
5270 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005271}
5272
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005273status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005274{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005275 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5276 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005277 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005278 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005279 return BAD_VALUE;
5280 }
5281 status_t status = disconnectAudioSource(sourceDesc);
5282
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005283 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005284 return status;
5285}
5286
Andy Hung2ddee192015-12-18 17:34:44 -08005287status_t AudioPolicyManager::setMasterMono(bool mono)
5288{
5289 if (mMasterMono == mono) {
5290 return NO_ERROR;
5291 }
5292 mMasterMono = mono;
5293 // if enabling mono we close all offloaded devices, which will invalidate the
5294 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5295 // for recreating the new AudioTrack as non-offloaded PCM.
5296 //
5297 // If disabling mono, we leave all tracks as is: we don't know which clients
5298 // and tracks are able to be recreated as offloaded. The next "song" should
5299 // play back offloaded.
5300 if (mMasterMono) {
5301 Vector<audio_io_handle_t> offloaded;
5302 for (size_t i = 0; i < mOutputs.size(); ++i) {
5303 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5304 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5305 offloaded.push(desc->mIoHandle);
5306 }
5307 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005308 for (const auto& handle : offloaded) {
5309 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005310 }
5311 }
5312 // update master mono for all remaining outputs
5313 for (size_t i = 0; i < mOutputs.size(); ++i) {
5314 updateMono(mOutputs.keyAt(i));
5315 }
5316 return NO_ERROR;
5317}
5318
5319status_t AudioPolicyManager::getMasterMono(bool *mono)
5320{
5321 *mono = mMasterMono;
5322 return NO_ERROR;
5323}
5324
Eric Laurentac9cef52017-06-09 15:46:26 -07005325float AudioPolicyManager::getStreamVolumeDB(
5326 audio_stream_type_t stream, int index, audio_devices_t device)
5327{
jiabin9a3361e2019-10-01 09:38:30 -07005328 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005329}
5330
jiabin81772902018-04-02 17:52:27 -07005331status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5332 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005333 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005334{
Kriti Dang6537def2021-03-02 13:46:59 +01005335 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5336 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005337 return BAD_VALUE;
5338 }
Kriti Dang6537def2021-03-02 13:46:59 +01005339 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5340 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005341
5342 size_t formatsWritten = 0;
5343 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005344
Kriti Dang6537def2021-03-02 13:46:59 +01005345 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005346 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5347 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005348 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005349 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005350 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005351 bool formatEnabled = true;
5352 switch (forceUse) {
5353 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005354 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005355 break;
5356 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5357 formatEnabled = false;
5358 break;
5359 default: // AUTO or ALWAYS => true
5360 break;
jiabin81772902018-04-02 17:52:27 -07005361 }
5362 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5363 }
jiabin81772902018-04-02 17:52:27 -07005364 }
5365 return NO_ERROR;
5366}
5367
Kriti Dang6537def2021-03-02 13:46:59 +01005368status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5369 audio_format_t *surroundFormats) {
5370 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5371 return BAD_VALUE;
5372 }
5373 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5374 __func__, *numSurroundFormats, surroundFormats);
5375
5376 size_t formatsWritten = 0;
5377 size_t formatsMax = *numSurroundFormats;
5378 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5379
5380 // Return formats from all device profiles that have already been resolved by
5381 // checkOutputsForDevice().
5382 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5383 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5384 audio_devices_t deviceType = device->type();
5385 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5386 // returns formats reported by HDMI devices.
5387 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5388 continue;
5389 }
5390 // Formats reported by sink devices
5391 std::unordered_set<audio_format_t> formatset;
5392 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5393 formatset.insert(it->second.begin(), it->second.end());
5394 }
5395
5396 // Formats hard-coded in the in policy configuration file (if any).
5397 FormatVector encodedFormats = device->encodedFormats();
5398 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5399 // Filter the formats which are supported by the vendor hardware.
5400 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5401 if (mConfig.getSurroundFormats().count(*it) != 0) {
5402 formats.insert(*it);
5403 } else {
5404 for (const auto& pair : mConfig.getSurroundFormats()) {
5405 if (pair.second.count(*it) != 0) {
5406 formats.insert(pair.first);
5407 break;
5408 }
5409 }
5410 }
5411 }
5412 }
5413 *numSurroundFormats = formats.size();
5414 for (const auto& format: formats) {
5415 if (formatsWritten < formatsMax) {
5416 surroundFormats[formatsWritten++] = format;
5417 }
5418 }
5419 return NO_ERROR;
5420}
5421
jiabin81772902018-04-02 17:52:27 -07005422status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5423{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005424 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005425 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5426 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005427 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005428 return BAD_VALUE;
5429 }
5430
Mikhail Naganov100f0122018-11-29 11:22:16 -08005431 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5432 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005433 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005434 return INVALID_OPERATION;
5435 }
5436
Mikhail Naganov100f0122018-11-29 11:22:16 -08005437 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005438 return NO_ERROR;
5439 }
5440
Mikhail Naganov100f0122018-11-29 11:22:16 -08005441 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005442 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005443 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005444 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005445 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005446 }
5447 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005448 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005449 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005450 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005451 }
5452 }
5453
5454 sp<SwAudioOutputDescriptor> outputDesc;
5455 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005456 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5457 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005458 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5459 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005460 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005461 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005462 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5463 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5464 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005465 name.c_str(),
5466 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005467 if (status != NO_ERROR) {
5468 continue;
5469 }
5470 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5471 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5472 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005473 name.c_str(),
5474 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005475 profileUpdated |= (status == NO_ERROR);
5476 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005477 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005478 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005479 AUDIO_DEVICE_IN_HDMI);
5480 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5481 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005482 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005483 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005484 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5485 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5486 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005487 name.c_str(),
5488 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005489 if (status != NO_ERROR) {
5490 continue;
5491 }
5492 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5493 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5494 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005495 name.c_str(),
5496 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005497 profileUpdated |= (status == NO_ERROR);
5498 }
5499
jiabin81772902018-04-02 17:52:27 -07005500 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005501 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005502 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005503 }
5504
5505 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5506}
5507
Eric Laurent5ada82e2019-08-29 17:53:54 -07005508void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005509{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005510 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005511 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005512 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005513 }
5514}
5515
jiabin6012f912018-11-02 17:06:30 -07005516bool AudioPolicyManager::isHapticPlaybackSupported()
5517{
5518 for (const auto& hwModule : mHwModules) {
5519 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5520 for (const auto &outProfile : outputProfiles) {
5521 struct audio_port audioPort;
5522 outProfile->toAudioPort(&audioPort);
5523 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5524 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5525 return true;
5526 }
5527 }
5528 }
5529 }
5530 return false;
5531}
5532
Carter Hsu325a8eb2022-01-19 19:56:51 +08005533bool AudioPolicyManager::isUltrasoundSupported()
5534{
5535 bool hasUltrasoundOutput = false;
5536 bool hasUltrasoundInput = false;
5537 for (const auto& hwModule : mHwModules) {
5538 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5539 if (!hasUltrasoundOutput) {
5540 for (const auto &outProfile : outputProfiles) {
5541 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5542 hasUltrasoundOutput = true;
5543 break;
5544 }
5545 }
5546 }
5547
5548 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5549 if (!hasUltrasoundInput) {
5550 for (const auto &inputProfile : inputProfiles) {
5551 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5552 hasUltrasoundInput = true;
5553 break;
5554 }
5555 }
5556 }
5557
5558 if (hasUltrasoundOutput && hasUltrasoundInput)
5559 return true;
5560 }
5561 return false;
5562}
5563
Eric Laurent8340e672019-11-06 11:01:08 -08005564bool AudioPolicyManager::isCallScreenModeSupported()
5565{
5566 return getConfig().isCallScreenModeSupported();
5567}
5568
5569
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005570status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005571{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005572 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005573 if (!sourceDesc->isConnected()) {
5574 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5575 return NO_ERROR;
5576 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005577 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5578 if (swOutput != 0) {
5579 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005580 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005581 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005582 }
jiabinbce0c1d2020-10-05 11:20:18 -07005583 if (releaseOutput(sourceDesc->portId())) {
5584 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5585 // no need to release audio patch here but just return NO_ERROR.
5586 return NO_ERROR;
5587 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005588 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005589 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005590 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005591 // close Hwoutput and remove from mHwOutputs
5592 } else {
5593 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5594 }
5595 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005596 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005597 sourceDesc->disconnect();
5598 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005599}
5600
François Gaffiec005e562018-11-06 15:04:49 +01005601sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5602 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005603{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005604 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005605 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005606 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005607 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005608 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5609 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005610 source = sourceDesc;
5611 break;
5612 }
5613 }
5614 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005615}
5616
Eric Laurentb4f42a92022-01-17 17:37:31 +01005617bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005618 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005619 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005620{
5621 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5622 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005623 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005624 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005625 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5626 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5627 return false;
5628 }
5629 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5630 return false;
5631 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005632 }
5633
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005634 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005635 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005636 if (profile == nullptr) {
5637 return false;
5638 }
5639
5640 // The caller can have the audio config criteria ignored by either passing a null ptr or
5641 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005642 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005643 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005644
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005645 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005646 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005647 return false;
5648 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005649 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005650 return true;
5651}
5652
5653void AudioPolicyManager::checkVirtualizerClientRoutes() {
5654 std::set<audio_stream_type_t> streamsToInvalidate;
5655 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005656 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5657 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005658 audio_attributes_t attr = client->attributes();
5659 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5660 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5661 audio_config_base_t clientConfig = client->config();
5662 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005663 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005664 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005665 streamsToInvalidate.insert(client->stream());
5666 }
5667 }
5668 }
5669
5670 for (audio_stream_type_t stream : streamsToInvalidate) {
5671 mpClientInterface->invalidateStream(stream);
5672 }
5673}
5674
Eric Laurente191d1b2022-04-15 11:59:25 +02005675
5676bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5677 const sp<SwAudioOutputDescriptor>& outputDesc) {
5678 if (outputDesc->isDuplicated()) {
5679 return false;
5680 }
5681 DeviceVector devices = outputDesc->supportedDevices();
5682 for (size_t i = 0; i < mOutputs.size(); i++) {
5683 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5684 if (desc == outputDesc || desc->isDuplicated()) {
5685 continue;
5686 }
5687 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5688 if (!sharedDevices.isEmpty()
5689 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5690 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5691 return false;
5692 }
5693 }
5694 return true;
5695}
5696
5697
Eric Laurentfa0f6742021-08-17 18:39:44 +02005698status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005699 const audio_attributes_t *attr,
5700 audio_io_handle_t *output) {
5701 *output = AUDIO_IO_HANDLE_NONE;
5702
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005703 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5704 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5705 audio_config_t *configPtr = nullptr;
5706 audio_config_t config;
5707 if (mixerConfig != nullptr) {
5708 config = audio_config_initializer(mixerConfig);
5709 configPtr = &config;
5710 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005711 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005712 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005713 return BAD_VALUE;
5714 }
5715
5716 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005717 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005718 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005719 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005720 return BAD_VALUE;
5721 }
5722
Eric Laurente191d1b2022-04-15 11:59:25 +02005723 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005724 for (size_t i = 0; i < mOutputs.size(); i++) {
5725 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005726 if (!desc->isDuplicated()
5727 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5728 spatializerOutputs.push_back(desc);
5729 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005730 }
5731 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005732 mSpatializerOutput.clear();
5733 bool outputsChanged = false;
5734 for (const auto& desc : spatializerOutputs) {
5735 if (desc->mProfile == profile
5736 && (configPtr == nullptr
5737 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5738 mSpatializerOutput = desc;
5739 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5740 } else {
5741 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5742 " and devices %s", __func__, desc->mIoHandle,
5743 configPtr != nullptr ? configPtr->channel_mask : 0,
5744 devices.toString().c_str());
5745 closeOutput(desc->mIoHandle);
5746 outputsChanged = true;
5747 }
Eric Laurent39095982021-08-24 18:29:27 +02005748 }
5749
Eric Laurente191d1b2022-04-15 11:59:25 +02005750 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005751 sp<SwAudioOutputDescriptor> desc =
5752 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005753 if (desc != nullptr) {
5754 mSpatializerOutput = desc;
5755 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005756 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005757 }
5758
5759 checkVirtualizerClientRoutes();
5760
Eric Laurente191d1b2022-04-15 11:59:25 +02005761 if (outputsChanged) {
5762 mPreviousOutputs = mOutputs;
5763 mpClientInterface->onAudioPortListUpdate();
5764 }
5765
5766 if (mSpatializerOutput == nullptr) {
5767 ALOGV("%s could not open spatializer output with requested config", __func__);
5768 return BAD_VALUE;
5769 }
Eric Laurent39095982021-08-24 18:29:27 +02005770 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005771 ALOGV("%s returning new spatializer output %d", __func__, *output);
5772 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005773}
5774
Eric Laurentfa0f6742021-08-17 18:39:44 +02005775status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5776 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005777 return INVALID_OPERATION;
5778 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005779 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005780 return BAD_VALUE;
5781 }
Eric Laurent39095982021-08-24 18:29:27 +02005782
Eric Laurente191d1b2022-04-15 11:59:25 +02005783 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5784 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5785 closeOutput(mSpatializerOutput->mIoHandle);
5786 //from now on mSpatializerOutput is null
5787 checkVirtualizerClientRoutes();
5788 }
Eric Laurent39095982021-08-24 18:29:27 +02005789
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005790 return NO_ERROR;
5791}
5792
Eric Laurente552edb2014-03-10 17:42:56 -07005793// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005794// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005795// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005796uint32_t AudioPolicyManager::nextAudioPortGeneration()
5797{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005798 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005799}
5800
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005801static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005802 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5803 !audioPolicyXmlConfigFile.empty()) {
5804 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5805 if (ret == NO_ERROR) {
5806 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005807 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005808 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005809 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005810 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005811}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005812
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005813AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5814 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005815 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005816 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005817 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005818 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005819 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005820 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005821 mAudioPortGeneration(1),
5822 mBeaconMuteRefCount(0),
5823 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005824 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005825 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005826 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005827 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005828{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005829}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005830
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005831AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5832 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5833{
5834 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005835}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005836
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005837void AudioPolicyManager::loadConfig() {
5838 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005839 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005840 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005841 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005842}
5843
5844status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005845 {
5846 auto engLib = EngineLibrary::load(
5847 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5848 if (!engLib) {
5849 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5850 return NO_INIT;
5851 }
5852 mEngine = engLib->createEngine();
5853 if (mEngine == nullptr) {
5854 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5855 return NO_INIT;
5856 }
François Gaffie2110e042015-03-24 08:41:51 +01005857 }
5858 mEngine->setObserver(this);
5859 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005860 if (status != NO_ERROR) {
5861 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5862 return status;
5863 }
François Gaffie2110e042015-03-24 08:41:51 +01005864
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005865 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005866 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5867 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5868
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005869 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005870 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005871 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005872
Eric Laurent3a4311c2014-03-17 12:00:47 -07005873 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005874 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5875 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5876 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005877 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005878 }
jiabin9ff780e2018-03-19 18:19:52 -07005879 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005880 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005881 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005882 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005883 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005884 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005885 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005886 }
5887 }
5888 }
Eric Laurente552edb2014-03-10 17:42:56 -07005889
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005890 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005891
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005892 // Silence ALOGV statements
5893 property_set("log.tag." LOG_TAG, "D");
5894
Eric Laurente552edb2014-03-10 17:42:56 -07005895 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005896 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005897}
5898
Eric Laurente0720872014-03-11 09:30:41 -07005899AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005900{
Eric Laurente552edb2014-03-10 17:42:56 -07005901 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005902 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005903 }
5904 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005905 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005906 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005907 mAvailableOutputDevices.clear();
5908 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005909 mOutputs.clear();
5910 mInputs.clear();
5911 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005912 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005913 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005914}
5915
Eric Laurente0720872014-03-11 09:30:41 -07005916status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005917{
Eric Laurent87ffa392015-05-22 10:32:38 -07005918 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005919}
5920
Eric Laurente552edb2014-03-10 17:42:56 -07005921// ---
5922
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005923void AudioPolicyManager::onNewAudioModulesAvailable()
5924{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005925 DeviceVector newDevices;
5926 onNewAudioModulesAvailableInt(&newDevices);
5927 if (!newDevices.empty()) {
5928 nextAudioPortGeneration();
5929 mpClientInterface->onAudioPortListUpdate();
5930 }
5931}
5932
5933void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5934{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005935 for (const auto& hwModule : mHwModulesAll) {
5936 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5937 continue;
5938 }
5939 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5940 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5941 ALOGW("could not open HW module %s", hwModule->getName());
5942 continue;
5943 }
5944 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005945 // open all output streams needed to access attached devices.
5946 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005947 // This also validates mAvailableOutputDevices list
5948 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5949 if (!outProfile->canOpenNewIo()) {
5950 ALOGE("Invalid Output profile max open count %u for profile %s",
5951 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5952 continue;
5953 }
5954 if (!outProfile->hasSupportedDevices()) {
5955 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5956 continue;
5957 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005958 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5959 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005960 mTtsOutputAvailable = true;
5961 }
5962
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005963 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5964 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5965 sp<DeviceDescriptor> supportedDevice = 0;
5966 if (supportedDevices.contains(mDefaultOutputDevice)) {
5967 supportedDevice = mDefaultOutputDevice;
5968 } else {
5969 // choose first device present in profile's SupportedDevices also part of
5970 // mAvailableOutputDevices.
5971 if (availProfileDevices.isEmpty()) {
5972 continue;
5973 }
5974 supportedDevice = availProfileDevices.itemAt(0);
5975 }
5976 if (!mOutputDevicesAll.contains(supportedDevice)) {
5977 continue;
5978 }
5979 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5980 mpClientInterface);
5981 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005982 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5983 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005984 AUDIO_STREAM_DEFAULT,
5985 AUDIO_OUTPUT_FLAG_NONE, &output);
5986 if (status != NO_ERROR) {
5987 ALOGW("Cannot open output stream for devices %s on hw module %s",
5988 supportedDevice->toString().c_str(), hwModule->getName());
5989 continue;
5990 }
5991 for (const auto &device : availProfileDevices) {
5992 // give a valid ID to an attached device once confirmed it is reachable
5993 if (!device->isAttached()) {
5994 device->attach(hwModule);
5995 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005996 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005997 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005998 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5999 }
6000 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006001 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006002 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6003 mPrimaryOutput = outputDesc;
6004 }
Eric Laurent39095982021-08-24 18:29:27 +02006005 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006006 outputDesc->close();
6007 } else {
6008 addOutput(output, outputDesc);
6009 setOutputDevices(outputDesc,
6010 DeviceVector(supportedDevice),
6011 true,
6012 0,
6013 NULL);
6014 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006015 }
6016 // open input streams needed to access attached devices to validate
6017 // mAvailableInputDevices list
6018 for (const auto& inProfile : hwModule->getInputProfiles()) {
6019 if (!inProfile->canOpenNewIo()) {
6020 ALOGE("Invalid Input profile max open count %u for profile %s",
6021 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6022 continue;
6023 }
6024 if (!inProfile->hasSupportedDevices()) {
6025 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6026 continue;
6027 }
6028 // chose first device present in profile's SupportedDevices also part of
6029 // available input devices
6030 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
6031 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
6032 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006033 ALOGV("%s: Input device list is empty! for profile %s",
6034 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006035 continue;
6036 }
6037 sp<AudioInputDescriptor> inputDesc =
6038 new AudioInputDescriptor(inProfile, mpClientInterface);
6039
6040 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6041 status_t status = inputDesc->open(nullptr,
6042 availProfileDevices.itemAt(0),
6043 AUDIO_SOURCE_MIC,
6044 AUDIO_INPUT_FLAG_NONE,
6045 &input);
6046 if (status != NO_ERROR) {
6047 ALOGW("Cannot open input stream for device %s on hw module %s",
6048 availProfileDevices.toString().c_str(),
6049 hwModule->getName());
6050 continue;
6051 }
6052 for (const auto &device : availProfileDevices) {
6053 // give a valid ID to an attached device once confirmed it is reachable
6054 if (!device->isAttached()) {
6055 device->attach(hwModule);
6056 device->importAudioPortAndPickAudioProfile(inProfile, true);
6057 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006058 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006059 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6060 }
6061 }
6062 inputDesc->close();
6063 }
6064 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006065
6066 // Check if spatializer outputs can be closed until used.
6067 // mOutputs vector never contains duplicated outputs at this point.
6068 std::vector<audio_io_handle_t> outputsClosed;
6069 for (size_t i = 0; i < mOutputs.size(); i++) {
6070 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6071 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6072 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6073 outputsClosed.push_back(desc->mIoHandle);
6074 desc->close();
6075 }
6076 }
6077 for (auto output : outputsClosed) {
6078 removeOutput(output);
6079 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006080}
6081
Eric Laurent98e38192018-02-15 18:31:53 -08006082void AudioPolicyManager::addOutput(audio_io_handle_t output,
6083 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006084{
Eric Laurent1c333e22014-05-20 10:48:17 -07006085 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006086 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006087 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006088 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006089 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006090}
6091
François Gaffie53615e22015-03-19 09:24:12 +01006092void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6093{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006094 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6095 ALOGV("%s: removing primary output", __func__);
6096 mPrimaryOutput = nullptr;
6097 }
François Gaffie53615e22015-03-19 09:24:12 +01006098 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006099 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006100}
6101
Eric Laurent98e38192018-02-15 18:31:53 -08006102void AudioPolicyManager::addInput(audio_io_handle_t input,
6103 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006104{
Eric Laurent1c333e22014-05-20 10:48:17 -07006105 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006106 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006107}
Eric Laurente552edb2014-03-10 17:42:56 -07006108
François Gaffie11d30102018-11-02 16:09:09 +01006109status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006110 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006111 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006112{
François Gaffie11d30102018-11-02 16:09:09 +01006113 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006114 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006115 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006116
François Gaffie11d30102018-11-02 16:09:09 +01006117 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006118 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006119 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006120 }
Eric Laurente552edb2014-03-10 17:42:56 -07006121
Eric Laurent3b73df72014-03-11 09:06:29 -07006122 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006123 // first call getAudioPort to get the supported attributes from the HAL
6124 struct audio_port_v7 port = {};
6125 device->toAudioPort(&port);
6126 status_t status = mpClientInterface->getAudioPort(&port);
6127 if (status == NO_ERROR) {
6128 device->importAudioPort(port);
6129 }
6130
6131 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006132 for (size_t i = 0; i < mOutputs.size(); i++) {
6133 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006134 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006135 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006136 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6137 mOutputs.keyAt(i), device->toString().c_str());
6138 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006139 }
6140 }
6141 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006142 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006143 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006144 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6145 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006146 if (profile->supportsDevice(device)) {
6147 profiles.add(profile);
6148 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6149 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006150 }
6151 }
6152 }
6153
Eric Laurent7b279bb2015-12-14 10:18:23 -08006154 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006155
Eric Laurente552edb2014-03-10 17:42:56 -07006156 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006157 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006158 return BAD_VALUE;
6159 }
6160
6161 // open outputs for matching profiles if needed. Direct outputs are also opened to
6162 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6163 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006164 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006165
6166 // nothing to do if one output is already opened for this profile
6167 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006168 for (j = 0; j < outputs.size(); j++) {
6169 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006170 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006171 // matching profile: save the sample rates, format and channel masks supported
6172 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006173 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006174 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006175 }
Eric Laurente552edb2014-03-10 17:42:56 -07006176 break;
6177 }
6178 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006179 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006180 continue;
6181 }
6182
Eric Laurent3974e3b2017-12-07 17:58:43 -08006183 if (!profile->canOpenNewIo()) {
6184 ALOGW("Max Output number %u already opened for this profile %s",
6185 profile->maxOpenCount, profile->getTagName().c_str());
6186 continue;
6187 }
6188
Eric Laurent83efe1c2017-07-09 16:51:08 -07006189 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07006190 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006191 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6192 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006193 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006194 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006195 profiles.removeAt(profile_index);
6196 profile_index--;
6197 } else {
6198 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006199 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006200 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006201 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6202 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006203 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006204 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006205
François Gaffie11d30102018-11-02 16:09:09 +01006206 if (device_distinguishes_on_address(deviceType)) {
6207 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6208 device->toString().c_str());
6209 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
6210 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006211 }
Eric Laurente552edb2014-03-10 17:42:56 -07006212 ALOGV("checkOutputsForDevice(): adding output %d", output);
6213 }
6214 }
6215
6216 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006217 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006218 return BAD_VALUE;
6219 }
Eric Laurentd4692962014-05-05 18:13:44 -07006220 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006221 // check if one opened output is not needed any more after disconnecting one device
6222 for (size_t i = 0; i < mOutputs.size(); i++) {
6223 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006224 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006225 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006226 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006227 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006228 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006229 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006230 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6231 mOutputs.keyAt(i));
6232 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006233 }
Eric Laurente552edb2014-03-10 17:42:56 -07006234 }
6235 }
Eric Laurentd4692962014-05-05 18:13:44 -07006236 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006237 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006238 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6239 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006240 if (!profile->supportsDevice(device)) {
6241 continue;
6242 }
6243 ALOGV("checkOutputsForDevice(): "
6244 "clearing direct output profile %zu on module %s",
6245 j, hwModule->getName());
6246 profile->clearAudioProfiles();
6247 if (!profile->hasDynamicAudioProfile()) {
6248 continue;
6249 }
6250 // When a device is disconnected, if there is an IOProfile that contains dynamic
6251 // profiles and supports the disconnected device, call getAudioPort to repopulate
6252 // the capabilities of the devices that is supported by the IOProfile.
6253 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6254 if (supportedDevice == device ||
6255 !mAvailableOutputDevices.contains(supportedDevice)) {
6256 continue;
6257 }
6258 struct audio_port_v7 port;
6259 supportedDevice->toAudioPort(&port);
6260 status_t status = mpClientInterface->getAudioPort(&port);
6261 if (status == NO_ERROR) {
6262 supportedDevice->importAudioPort(port);
6263 }
Eric Laurente552edb2014-03-10 17:42:56 -07006264 }
6265 }
6266 }
6267 }
6268 return NO_ERROR;
6269}
6270
François Gaffie11d30102018-11-02 16:09:09 +01006271status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006272 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006273{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006274 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006275
François Gaffie11d30102018-11-02 16:09:09 +01006276 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006277 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006278 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006279 }
6280
Eric Laurentd4692962014-05-05 18:13:44 -07006281 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006282 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006283 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006284 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006285 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006286 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006287 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006288 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006289
François Gaffie11d30102018-11-02 16:09:09 +01006290 if (profile->supportsDevice(device)) {
6291 profiles.add(profile);
6292 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6293 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006294 }
6295 }
6296 }
6297
Eric Laurent0dd51852019-04-19 18:18:58 -07006298 if (profiles.isEmpty()) {
6299 ALOGW("%s: No input profile available for device %s",
6300 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006301 return BAD_VALUE;
6302 }
6303
6304 // open inputs for matching profiles if needed. Direct inputs are also opened to
6305 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6306 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6307
Eric Laurent1c333e22014-05-20 10:48:17 -07006308 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006309
Eric Laurentd4692962014-05-05 18:13:44 -07006310 // nothing to do if one input is already opened for this profile
6311 size_t input_index;
6312 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6313 desc = mInputs.valueAt(input_index);
6314 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006315 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006316 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006317 }
Eric Laurentd4692962014-05-05 18:13:44 -07006318 break;
6319 }
6320 }
6321 if (input_index != mInputs.size()) {
6322 continue;
6323 }
6324
Eric Laurent3974e3b2017-12-07 17:58:43 -08006325 if (!profile->canOpenNewIo()) {
6326 ALOGW("Max Input number %u already opened for this profile %s",
6327 profile->maxOpenCount, profile->getTagName().c_str());
6328 continue;
6329 }
6330
Eric Laurentfe231122017-11-17 17:48:06 -08006331 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006332 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006333 status_t status = desc->open(nullptr,
6334 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006335 AUDIO_SOURCE_MIC,
6336 AUDIO_INPUT_FLAG_NONE,
6337 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006338
Eric Laurentcf2c0212014-07-25 16:20:43 -07006339 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006340 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006341 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006342 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006343 mpClientInterface->setParameters(input, String8(param));
6344 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006345 }
François Gaffie11d30102018-11-02 16:09:09 +01006346 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006347 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006348 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006349 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006350 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006351 }
6352
Eric Laurent0dd51852019-04-19 18:18:58 -07006353 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006354 addInput(input, desc);
6355 }
6356 } // endif input != 0
6357
Eric Laurentcf2c0212014-07-25 16:20:43 -07006358 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006359 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006360 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006361 profiles.removeAt(profile_index);
6362 profile_index--;
6363 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006364 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006365 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006366 }
Eric Laurentd4692962014-05-05 18:13:44 -07006367 ALOGV("checkInputsForDevice(): adding input %d", input);
6368 }
6369 } // end scan profiles
6370
6371 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006372 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006373 return BAD_VALUE;
6374 }
6375 } else {
6376 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006377 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006378 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006379 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006380 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006381 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006382 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006383 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006384 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6385 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006386 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006387 }
6388 }
6389 }
6390 } // end disconnect
6391
6392 return NO_ERROR;
6393}
6394
6395
Eric Laurente0720872014-03-11 09:30:41 -07006396void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006397{
6398 ALOGV("closeOutput(%d)", output);
6399
François Gaffie1c878552018-11-22 16:53:21 +01006400 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6401 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006402 ALOGW("closeOutput() unknown output %d", output);
6403 return;
6404 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006405 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006406 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006407
Eric Laurente552edb2014-03-10 17:42:56 -07006408 // look for duplicated outputs connected to the output being removed.
6409 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006410 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6411 if (dupOutput->isDuplicated() &&
6412 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6413 sp<SwAudioOutputDescriptor> remainingOutput =
6414 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006415 // As all active tracks on duplicated output will be deleted,
6416 // and as they were also referenced on the other output, the reference
6417 // count for their stream type must be adjusted accordingly on
6418 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006419 const bool wasActive = remainingOutput->isActive();
6420 // Note: no-op on the closing output where all clients has already been set inactive
6421 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006422 // stop() will be a no op if the output is still active but is needed in case all
6423 // active streams refcounts where cleared above
6424 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006425 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006426 }
Eric Laurente552edb2014-03-10 17:42:56 -07006427 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6428 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6429
6430 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006431 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006432 }
6433 }
6434
Eric Laurent05b90f82014-08-27 15:32:29 -07006435 nextAudioPortGeneration();
6436
François Gaffie1c878552018-11-22 16:53:21 +01006437 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006438 if (index >= 0) {
6439 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006440 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6441 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006442 mAudioPatches.removeItemsAt(index);
6443 mpClientInterface->onAudioPatchListUpdate();
6444 }
6445
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006446 if (closingOutputWasActive) {
6447 closingOutput->stop();
6448 }
François Gaffie1c878552018-11-22 16:53:21 +01006449 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006450
François Gaffie53615e22015-03-19 09:24:12 +01006451 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006452 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006453 if (closingOutput == mSpatializerOutput) {
6454 mSpatializerOutput.clear();
6455 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006456
6457 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6458 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006459 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006460 bool directOutputOpen = false;
6461 for (size_t i = 0; i < mOutputs.size(); i++) {
6462 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6463 directOutputOpen = true;
6464 break;
6465 }
6466 }
6467 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006468 ALOGV("no direct outputs open, reset MSD patches");
6469 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6470 // how output devices for patching are resolved. Avoid by caching and reusing the
6471 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6472 // devices to patch to. This may be complicated by the fact that devices may become
6473 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006474 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006475 }
6476 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006477}
6478
6479void AudioPolicyManager::closeInput(audio_io_handle_t input)
6480{
6481 ALOGV("closeInput(%d)", input);
6482
6483 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6484 if (inputDesc == NULL) {
6485 ALOGW("closeInput() unknown input %d", input);
6486 return;
6487 }
6488
Eric Laurent6a94d692014-05-20 11:18:06 -07006489 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006490
François Gaffie11d30102018-11-02 16:09:09 +01006491 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006492 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006493 if (index >= 0) {
6494 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006495 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6496 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006497 mAudioPatches.removeItemsAt(index);
6498 mpClientInterface->onAudioPatchListUpdate();
6499 }
6500
Eric Laurentfe231122017-11-17 17:48:06 -08006501 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006502 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006503
François Gaffie11d30102018-11-02 16:09:09 +01006504 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6505 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006506 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006507 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006508 }
Eric Laurente552edb2014-03-10 17:42:56 -07006509}
6510
François Gaffie11d30102018-11-02 16:09:09 +01006511SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6512 const DeviceVector &devices,
6513 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006514{
6515 SortedVector<audio_io_handle_t> outputs;
6516
François Gaffie11d30102018-11-02 16:09:09 +01006517 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006518 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006519 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006520 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006521 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006522 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006523 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006524 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006525 outputs.add(openOutputs.keyAt(i));
6526 }
6527 }
6528 return outputs;
6529}
6530
Mikhail Naganov37977152018-07-11 15:54:44 -07006531void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6532{
6533 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6534 // output is suspended before any tracks are moved to it
6535 checkA2dpSuspend();
6536 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006537 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006538 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006539 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006540 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006541 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6542 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6543 // configuration changes will ultimately be rerouted correctly. We can still avoid
6544 // unnecessary rerouting by caching and reusing the arguments to
6545 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6546 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006547 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006548 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006549 // an event that changed routing likely occurred, inform upper layers
6550 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006551}
6552
François Gaffiec005e562018-11-06 15:04:49 +01006553bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6554 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006555{
François Gaffiec005e562018-11-06 15:04:49 +01006556 return mEngine->getProductStrategyForAttributes(lAttr) ==
6557 mEngine->getProductStrategyForAttributes(rAttr);
6558}
6559
Francois Gaffieff1eb522020-05-06 18:37:04 +02006560void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6561{
6562 for (size_t i = 0; i < mAudioSources.size(); i++) {
6563 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6564 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006565 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006566 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006567 connectAudioSource(sourceDesc);
6568 }
6569 }
6570}
6571
6572void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6573{
6574 for (size_t i = 0; i < mAudioSources.size(); i++) {
6575 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6576 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6577 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6578 disconnectAudioSource(sourceDesc);
6579 }
6580 }
6581}
6582
François Gaffiec005e562018-11-06 15:04:49 +01006583void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6584{
6585 auto psId = mEngine->getProductStrategyForAttributes(attr);
6586
6587 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6588 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006589
François Gaffie11d30102018-11-02 16:09:09 +01006590 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6591 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006592
Eric Laurentc209fe42020-06-05 18:11:23 -07006593 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006594 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006595 // take into account dynamic audio policies related changes: if a client is now associated
6596 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006597 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006598 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6599 if (desc->isDuplicated()) {
6600 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006601 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006602 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6603 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6604 continue;
6605 }
6606 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006607 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006608 client->uid(), client->session(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006609 if (status != OK) {
6610 continue;
6611 }
yucliuf4de36d2020-09-14 14:57:56 -07006612 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006613 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006614 maxLatency = desc->latency();
6615 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006616 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006617 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006618 }
6619 }
6620
Eric Laurent56ed8842022-11-15 16:04:41 +01006621 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006622 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6623 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006624 for (audio_io_handle_t srcOut : srcOutputs) {
6625 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006626 if (desc == nullptr) continue;
6627
6628 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006629 maxLatency = desc->latency();
6630 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006631
Eric Laurent56ed8842022-11-15 16:04:41 +01006632 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006633 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006634 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006635 // a client on a non direct outputs has necessarily a linear PCM format
6636 // so we can call selectOutput() safely
6637 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6638 client->flags(),
6639 client->config().format,
6640 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006641 client->config().sample_rate,
6642 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006643 if (newOutput != srcOut) {
6644 invalidate = true;
6645 break;
6646 }
6647 } else {
6648 sp<IOProfile> profile = getProfileForOutput(newDevices,
6649 client->config().sample_rate,
6650 client->config().format,
6651 client->config().channel_mask,
6652 client->flags(),
6653 true /* directOnly */);
6654 if (profile != desc->mProfile) {
6655 invalidate = true;
6656 break;
6657 }
6658 }
6659 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006660 // mute strategy while moving tracks from one output to another
6661 if (invalidate) {
6662 invalidatedOutputs.push_back(desc);
6663 if (desc->isStrategyActive(psId)) {
6664 setStrategyMute(psId, true, desc);
6665 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6666 newDevices.types());
6667 }
Eric Laurente552edb2014-03-10 17:42:56 -07006668 }
François Gaffiec005e562018-11-06 15:04:49 +01006669 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006670 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006671 connectAudioSource(source);
6672 }
Eric Laurente552edb2014-03-10 17:42:56 -07006673 }
6674
Eric Laurent56ed8842022-11-15 16:04:41 +01006675 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6676 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6677 std::to_string(srcOutputs[0]).c_str(),
6678 std::to_string(dstOutputs[0]).c_str());
6679
François Gaffiec005e562018-11-06 15:04:49 +01006680 // Move effects associated to this stream from previous output to new output
6681 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006682 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006683 }
François Gaffiec005e562018-11-06 15:04:49 +01006684 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006685 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006686 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6687 mpClientInterface->invalidateStream(stream);
6688 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006689 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006690 desc->setTracksInvalidatedStatusByStrategy(psId);
6691 }
Eric Laurente552edb2014-03-10 17:42:56 -07006692 }
6693 }
6694}
6695
Eric Laurente0720872014-03-11 09:30:41 -07006696void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006697{
François Gaffiec005e562018-11-06 15:04:49 +01006698 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6699 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6700 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006701 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006702 }
Eric Laurente552edb2014-03-10 17:42:56 -07006703}
6704
Kevin Rocard153f92d2018-12-18 18:33:28 -08006705void AudioPolicyManager::checkSecondaryOutputs() {
6706 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006707 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006708 for (size_t i = 0; i < mOutputs.size(); i++) {
6709 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6710 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006711 sp<AudioPolicyMix> primaryMix;
6712 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006713 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006714 client->uid(), client->session(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006715 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6716 for (auto &secondaryMix : secondaryMixes) {
6717 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6718 if (outputDesc != nullptr &&
6719 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6720 secondaryDescs.push_back(outputDesc);
6721 }
6722 }
6723
jiabin10a03f12021-05-07 23:46:28 +00006724 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006725 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006726 } else if (!std::equal(
6727 client->getSecondaryOutputs().begin(),
6728 client->getSecondaryOutputs().end(),
6729 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006730 if (!audio_is_linear_pcm(client->config().format)) {
6731 // If the format is not PCM, the tracks should be invalidated to get correct
6732 // behavior when the secondary output is changed.
6733 streamsToInvalidate.insert(client->stream());
6734 } else {
6735 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6736 std::vector<audio_io_handle_t> secondaryOutputIds;
6737 for (const auto &secondaryDesc: secondaryDescs) {
6738 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6739 weakSecondaryDescs.push_back(secondaryDesc);
6740 }
6741 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6742 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006743 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006744 }
6745 }
6746 }
jiabin10a03f12021-05-07 23:46:28 +00006747 if (!trackSecondaryOutputs.empty()) {
6748 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6749 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006750 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006751 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006752 mpClientInterface->invalidateStream(stream);
6753 }
6754}
6755
Eric Laurent2517af32020-11-25 15:31:27 +01006756bool AudioPolicyManager::isScoRequestedForComm() const {
6757 AudioDeviceTypeAddrVector devices;
6758 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6759 for (const auto &device : devices) {
6760 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6761 return true;
6762 }
6763 }
6764 return false;
6765}
6766
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006767bool AudioPolicyManager::isHearingAidUsedForComm() const {
6768 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6769 true /*fromCache*/);
6770 for (const auto &device : devices) {
6771 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6772 return true;
6773 }
6774 }
6775 return false;
6776}
6777
6778
Eric Laurente0720872014-03-11 09:30:41 -07006779void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006780{
François Gaffie53615e22015-03-19 09:24:12 +01006781 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006782 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006783 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006784 return;
6785 }
6786
Eric Laurent3a4311c2014-03-17 12:00:47 -07006787 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006788 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6789 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006790 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006791
6792 // if suspended, restore A2DP output if:
6793 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006794 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006795 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006796 //
Eric Laurentf732e072016-08-03 19:30:28 -07006797 // if not suspended, suspend A2DP output if:
6798 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006799 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006800 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006801 //
6802 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006803 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006804 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006805 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006806 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006807
6808 mpClientInterface->restoreOutput(a2dpOutput);
6809 mA2dpSuspended = false;
6810 }
6811 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006812 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006813 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006814 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006815 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006816
6817 mpClientInterface->suspendOutput(a2dpOutput);
6818 mA2dpSuspended = true;
6819 }
6820 }
6821}
6822
François Gaffie11d30102018-11-02 16:09:09 +01006823DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6824 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006825{
François Gaffie11d30102018-11-02 16:09:09 +01006826 DeviceVector devices;
6827
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006828 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006829 if (index >= 0) {
6830 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006831 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006832 ALOGV("%s device %s forced by patch %d", __func__,
6833 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6834 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006835 }
6836 }
6837
Dean Wheatley514b4312020-06-17 21:45:00 +10006838 // Do not retrieve engine device for outputs through MSD
6839 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6840 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6841 return outputDesc->devices();
6842 }
6843
Eric Laurent97ac8712018-07-27 18:59:02 -07006844 // Honor explicit routing requests only if no client using default routing is active on this
6845 // input: a specific app can not force routing for other apps by setting a preferred device.
6846 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006847 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006848 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006849 if (device != nullptr) {
6850 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006851 }
6852
François Gaffiea807ef92018-11-05 10:44:33 +01006853 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6854 // of setForceUse / Default Bus device here
6855 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6856 if (device != nullptr) {
6857 return DeviceVector(device);
6858 }
6859
François Gaffiec005e562018-11-06 15:04:49 +01006860 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6861 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6862 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306863 auto hasStreamActive = [&](auto stream) {
6864 return hasStream(streams, stream) && isStreamActive(stream, 0);
6865 };
Eric Laurent484e9272018-06-07 17:29:23 -07006866
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306867 auto doGetOutputDevicesForVoice = [&]() {
6868 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006869 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306870 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006871 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6872 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306873 };
6874
6875 // With low-latency playing on speaker, music on WFD, when the first low-latency
6876 // output is stopped, getNewOutputDevices checks for a product strategy
6877 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006878 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306879 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6880 // stream is associated to the output descriptor.
6881 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6882 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6883 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6884 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006885 // Retrieval of devices for voice DL is done on primary output profile, cannot
6886 // check the route (would force modifying configuration file for this profile)
6887 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6888 break;
6889 }
Eric Laurente552edb2014-03-10 17:42:56 -07006890 }
François Gaffiec005e562018-11-06 15:04:49 +01006891 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006892 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006893}
6894
François Gaffie11d30102018-11-02 16:09:09 +01006895sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6896 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006897{
François Gaffie11d30102018-11-02 16:09:09 +01006898 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006899
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006900 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006901 if (index >= 0) {
6902 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006903 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006904 ALOGV("getNewInputDevice() device %s forced by patch %d",
6905 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6906 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006907 }
6908 }
6909
Eric Laurent97ac8712018-07-27 18:59:02 -07006910 // Honor explicit routing requests only if no client using default routing is active on this
6911 // input: a specific app can not force routing for other apps by setting a preferred device.
6912 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006913 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6914 if (device != nullptr) {
6915 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006916 }
6917
Eric Laurentdc95a252018-04-12 12:46:56 -07006918 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006919 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006920 audio_attributes_t attributes;
6921 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006922 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006923 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6924 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006925 attributes = topClient->attributes();
6926 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006927 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006928 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006929 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6930 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006931 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006932 }
6933
Francois Gaffie716e1432019-01-14 16:58:59 +01006934 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6935 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006936 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006937 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006938 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006939 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006940
Eric Laurente552edb2014-03-10 17:42:56 -07006941 return device;
6942}
6943
Eric Laurent794fde22016-03-11 09:50:45 -08006944bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6945 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006946 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006947}
6948
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006949status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006950 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006951 if (devices == nullptr) {
6952 return BAD_VALUE;
6953 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006954
Andy Hung6d23c0f2022-02-16 09:37:15 -08006955 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07006956 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
6957 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08006958 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006959 for (const auto& device : curDevices) {
6960 devices->push_back(device->getDeviceTypeAddr());
6961 }
6962 return NO_ERROR;
6963}
6964
Eric Laurente0720872014-03-11 09:30:41 -07006965void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006966 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006967 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006968 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006969 updateDevicesAndOutputs();
6970 break;
6971 default:
6972 break;
6973 }
6974}
6975
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006976uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006977
6978 // skip beacon mute management if a dedicated TTS output is available
6979 if (mTtsOutputAvailable) {
6980 return 0;
6981 }
6982
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006983 switch(event) {
6984 case STARTING_OUTPUT:
6985 mBeaconMuteRefCount++;
6986 break;
6987 case STOPPING_OUTPUT:
6988 if (mBeaconMuteRefCount > 0) {
6989 mBeaconMuteRefCount--;
6990 }
6991 break;
6992 case STARTING_BEACON:
6993 mBeaconPlayingRefCount++;
6994 break;
6995 case STOPPING_BEACON:
6996 if (mBeaconPlayingRefCount > 0) {
6997 mBeaconPlayingRefCount--;
6998 }
6999 break;
7000 }
7001
7002 if (mBeaconMuteRefCount > 0) {
7003 // any playback causes beacon to be muted
7004 return setBeaconMute(true);
7005 } else {
7006 // no other playback: unmute when beacon starts playing, mute when it stops
7007 return setBeaconMute(mBeaconPlayingRefCount == 0);
7008 }
7009}
7010
7011uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7012 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7013 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7014 // keep track of muted state to avoid repeating mute/unmute operations
7015 if (mBeaconMuted != mute) {
7016 // mute/unmute AUDIO_STREAM_TTS on all outputs
7017 ALOGV("\t muting %d", mute);
7018 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007019 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7020 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7021 ALOGV("\t no tts volume source available");
7022 return 0;
7023 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007024 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007025 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007026 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007027 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007028 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007029 maxLatency = latency;
7030 }
7031 }
7032 mBeaconMuted = mute;
7033 return maxLatency;
7034 }
7035 return 0;
7036}
7037
Eric Laurente0720872014-03-11 09:30:41 -07007038void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007039{
François Gaffiec005e562018-11-06 15:04:49 +01007040 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007041 mPreviousOutputs = mOutputs;
7042}
7043
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007044uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007045 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007046 uint32_t delayMs)
7047{
7048 // mute/unmute strategies using an incompatible device combination
7049 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7050 // if unmuting, unmute only after the specified delay
7051 if (outputDesc->isDuplicated()) {
7052 return 0;
7053 }
7054
7055 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007056 DeviceVector devices = outputDesc->devices();
7057 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007058
François Gaffiec005e562018-11-06 15:04:49 +01007059 auto productStrategies = mEngine->getOrderedProductStrategies();
7060 for (const auto &productStrategy : productStrategies) {
7061 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7062 DeviceVector curDevices =
7063 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7064 curDevices = curDevices.filter(outputDesc->supportedDevices());
7065 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007066 bool doMute = false;
7067
François Gaffiec005e562018-11-06 15:04:49 +01007068 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007069 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007070 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7071 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007072 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007073 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007074 }
Eric Laurent99401132014-05-07 19:48:15 -07007075 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007076 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007077 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007078 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007079 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007080 continue;
7081 }
François Gaffiec005e562018-11-06 15:04:49 +01007082 ALOGVV("%s() %s (curDevice %s)", __func__,
7083 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7084 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7085 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007086 if (mute) {
7087 // FIXME: should not need to double latency if volume could be applied
7088 // immediately by the audioflinger mixer. We must account for the delay
7089 // between now and the next time the audioflinger thread for this output
7090 // will process a buffer (which corresponds to one buffer size,
7091 // usually 1/2 or 1/4 of the latency).
7092 if (muteWaitMs < desc->latency() * 2) {
7093 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007094 }
7095 }
7096 }
7097 }
7098 }
7099 }
7100
Eric Laurent99401132014-05-07 19:48:15 -07007101 // temporary mute output if device selection changes to avoid volume bursts due to
7102 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007103 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007104 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007105
Eric Laurentdc462862016-07-19 12:29:53 -07007106 if (muteWaitMs < tempMuteWaitMs) {
7107 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007108 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007109
7110 // If recommended duration is defined, replace temporary mute duration to avoid
7111 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7112 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7113 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7114 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7115 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7116
François Gaffieaaac0fd2018-11-22 17:56:39 +01007117 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7118 // make sure that we do not start the temporary mute period too early in case of
7119 // delayed device change
7120 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7121 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007122 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007123 }
7124 }
7125
Eric Laurente552edb2014-03-10 17:42:56 -07007126 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7127 if (muteWaitMs > delayMs) {
7128 muteWaitMs -= delayMs;
7129 usleep(muteWaitMs * 1000);
7130 return muteWaitMs;
7131 }
7132 return 0;
7133}
7134
François Gaffie11d30102018-11-02 16:09:09 +01007135uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7136 const DeviceVector &devices,
7137 bool force,
7138 int delayMs,
7139 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02007140 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07007141{
François Gaffie11d30102018-11-02 16:09:09 +01007142 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007143 uint32_t muteWaitMs;
7144
7145 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01007146 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
7147 nullptr /* patchHandle */, requiresMuteCheck);
7148 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
7149 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07007150 return muteWaitMs;
7151 }
Eric Laurente552edb2014-03-10 17:42:56 -07007152
7153 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007154 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007155 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007156 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007157
François Gaffie11d30102018-11-02 16:09:09 +01007158 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
7159
7160 if (!filteredDevices.isEmpty()) {
7161 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007162 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007163
7164 // if the outputs are not materially active, there is no need to mute.
7165 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007166 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007167 } else {
7168 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
7169 muteWaitMs = 0;
7170 }
Eric Laurente552edb2014-03-10 17:42:56 -07007171
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007172 bool outputRouted = outputDesc->isRouted();
7173
Eric Laurent79ea9582020-06-11 18:49:24 -07007174 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7175 // output profile or if new device is not supported AND previous device(s) is(are) still
7176 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007177 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07007178 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
7179 // restore previous device after evaluating strategy mute state
7180 outputDesc->setDevices(prevDevices);
7181 return muteWaitMs;
7182 }
7183
Eric Laurente552edb2014-03-10 17:42:56 -07007184 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007185 // the requested device is AUDIO_DEVICE_NONE
7186 // OR the requested device is the same as current device
7187 // AND force is not specified
7188 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007189 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007190 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007191 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7192 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007193 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7194 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7195 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7196 }
Eric Laurente552edb2014-03-10 17:42:56 -07007197 return muteWaitMs;
7198 }
7199
François Gaffie11d30102018-11-02 16:09:09 +01007200 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007201
Eric Laurente552edb2014-03-10 17:42:56 -07007202 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007203 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007204 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007205 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007206 PatchBuilder patchBuilder;
7207 patchBuilder.addSource(outputDesc);
7208 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7209 for (const auto &filteredDevice : filteredDevices) {
7210 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007211 }
7212
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007213 // Add half reported latency to delayMs when muteWaitMs is null in order
7214 // to avoid disordered sequence of muting volume and changing devices.
7215 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7216 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007217 }
Eric Laurente552edb2014-03-10 17:42:56 -07007218
7219 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007220 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007221
7222 return muteWaitMs;
7223}
7224
Eric Laurentc75307b2015-03-17 15:29:32 -07007225status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007226 int delayMs,
7227 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007228{
Eric Laurent6a94d692014-05-20 11:18:06 -07007229 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007230 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7231 return INVALID_OPERATION;
7232 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007233 if (patchHandle) {
7234 index = mAudioPatches.indexOfKey(*patchHandle);
7235 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007236 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007237 }
7238 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007239 return INVALID_OPERATION;
7240 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007241 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007242 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007243 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007244 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007245 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007246 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007247 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007248 return status;
7249}
7250
7251status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007252 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007253 bool force,
7254 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007255{
7256 status_t status = NO_ERROR;
7257
Eric Laurent1f2f2232014-06-02 12:01:23 -07007258 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007259 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7260 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007261
François Gaffie11d30102018-11-02 16:09:09 +01007262 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007263 PatchBuilder patchBuilder;
7264 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007265 // AUDIO_SOURCE_HOTWORD is for internal use only:
7266 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007267 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7268 auto result = usecase;
7269 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7270 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7271 }
7272 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007273 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007274 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007275 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007276 }
7277 }
7278 return status;
7279}
7280
Eric Laurent6a94d692014-05-20 11:18:06 -07007281status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7282 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007283{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007284 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007285 ssize_t index;
7286 if (patchHandle) {
7287 index = mAudioPatches.indexOfKey(*patchHandle);
7288 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007289 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007290 }
7291 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007292 return INVALID_OPERATION;
7293 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007294 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007295 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007296 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007297 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007298 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007299 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007300 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007301 return status;
7302}
7303
François Gaffie11d30102018-11-02 16:09:09 +01007304sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007305 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007306 audio_format_t& format,
7307 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007308 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007309{
7310 // Choose an input profile based on the requested capture parameters: select the first available
7311 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007312 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007313 //
7314 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7315 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007316
jiabin2fd710d2022-05-02 23:20:22 +00007317 const audio_input_flags_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ;
7318 const audio_input_flags_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007319
jiabin2fd710d2022-05-02 23:20:22 +00007320 for (;;) {
7321 sp<IOProfile> firstInexact = nullptr;
7322 uint32_t updatedSamplingRate = 0;
7323 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7324 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7325 for (const auto& hwModule : mHwModules) {
7326 for (const auto& profile : hwModule->getInputProfiles()) {
7327 // profile->log();
7328 //updatedFormat = format;
7329 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7330 &samplingRate /*updatedSamplingRate*/,
7331 format,
7332 &format, /*updatedFormat*/
7333 channelMask,
7334 &channelMask /*updatedChannelMask*/,
7335 // FIXME ugly cast
7336 (audio_output_flags_t) flags,
7337 true /*exactMatchRequiredForInputFlags*/)) {
7338 return profile;
7339 }
7340 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7341 samplingRate,
7342 &updatedSamplingRate,
7343 format,
7344 &updatedFormat,
7345 channelMask,
7346 &updatedChannelMask,
7347 // FIXME ugly cast
7348 (audio_output_flags_t) flags,
7349 false /*exactMatchRequiredForInputFlags*/)) {
7350 firstInexact = profile;
7351 }
7352 }
7353 }
7354
7355 if (firstInexact != nullptr) {
7356 samplingRate = updatedSamplingRate;
7357 format = updatedFormat;
7358 channelMask = updatedChannelMask;
7359 return firstInexact;
7360 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7361 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7362 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7363 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7364 flags = AUDIO_INPUT_FLAG_NONE;
7365 } else { // fail
7366 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7367 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7368 samplingRate, format, channelMask, oriFlags);
7369 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007370 }
7371 }
jiabin2fd710d2022-05-02 23:20:22 +00007372
7373 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007374}
7375
François Gaffieaaac0fd2018-11-22 17:56:39 +01007376float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7377 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007378 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007379 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007380{
jiabin9a3361e2019-10-01 09:38:30 -07007381 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007382
7383 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7384 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7385 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7386 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007387 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7388 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7389 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7390 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7391 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007392
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007393 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007394 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7395 mOutputs.isActive(ringVolumeSrc, 0)) {
7396 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007397 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007398 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007399 }
7400
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007401 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007402 if ((volumeSource != callVolumeSrc && (isInCall() ||
7403 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007404 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007405 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7406 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007407 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7408 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7409 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007410 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007411 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007412 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007413 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007414 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007415 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007416 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7417 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7418 // programmatically muted.
7419 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7420 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7421 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007422 bool exemptFromCapping =
7423 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7424 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007425 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7426 volumeSource, volumeDb);
7427 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007428 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7429 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7430 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007431 }
7432 }
Eric Laurente552edb2014-03-10 17:42:56 -07007433 // if a headset is connected, apply the following rules to ring tones and notifications
7434 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007435 // - always attenuate notifications volume by 6dB
7436 // - attenuate ring tones volume by 6dB unless music is not playing and
7437 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007438 // - if music is playing, always limit the volume to current music volume,
7439 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007440 if (!Intersection(deviceTypes,
7441 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7442 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007443 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7444 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007445 ((volumeSource == alarmVolumeSrc ||
7446 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007447 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7448 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7449 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007450 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7451 curves.canBeMuted()) {
7452
Eric Laurente552edb2014-03-10 17:42:56 -07007453 // when the phone is ringing we must consider that music could have been paused just before
7454 // by the music application and behave as if music was active if the last music track was
7455 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007456 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007457 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007458 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007459 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007460 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7461 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007462 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007463 float musicVolDb = computeVolume(musicCurves,
7464 musicVolumeSrc,
7465 musicCurves.getVolumeIndex(musicDevice),
7466 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007467 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7468 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7469 if (volumeDb > minVolDb) {
7470 volumeDb = minVolDb;
7471 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007472 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007473 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7474 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7475 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007476 // on A2DP, also ensure notification volume is not too low compared to media when
7477 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007478 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007479 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007480 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7481 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007482 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7483 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007484 }
7485 }
jiabin9a3361e2019-10-01 09:38:30 -07007486 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007487 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007488 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007489 }
7490 }
7491
François Gaffie43c73442018-11-08 08:21:55 +01007492 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007493}
7494
Eric Laurent3839bc02018-07-10 18:33:34 -07007495int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007496 VolumeSource fromVolumeSource,
7497 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007498{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007499 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007500 return srcIndex;
7501 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007502 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7503 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007504 float minSrc = (float)srcCurves.getVolumeIndexMin();
7505 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7506 float minDst = (float)dstCurves.getVolumeIndexMin();
7507 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007508
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007509 // preserve mute request or correct range
7510 if (srcIndex < minSrc) {
7511 if (srcIndex == 0) {
7512 return 0;
7513 }
7514 srcIndex = minSrc;
7515 } else if (srcIndex > maxSrc) {
7516 srcIndex = maxSrc;
7517 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007518 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7519}
7520
François Gaffieaaac0fd2018-11-22 17:56:39 +01007521status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7522 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007523 int index,
7524 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007525 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007526 int delayMs,
7527 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007528{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007529 // do not change actual attributes volume if the attributes is muted
7530 if (outputDesc->isMuted(volumeSource)) {
7531 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7532 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007533 return NO_ERROR;
7534 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007535 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7536 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7537 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7538 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007539
Eric Laurent2517af32020-11-25 15:31:27 +01007540 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007541 bool isHAUsed = isHearingAidUsedForComm();
7542
Eric Laurente552edb2014-03-10 17:42:56 -07007543 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007544 // if sco and call follow same curves, bypass forceUseForComm
7545 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007546 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007547 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007548 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007549 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007550 // Do not return an error here as AudioService will always set both voice call
7551 // and bluetooth SCO volumes due to stream aliasing.
7552 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007553 }
jiabin9a3361e2019-10-01 09:38:30 -07007554 if (deviceTypes.empty()) {
7555 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007556 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007557
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007558 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7559 ALOGE("invalid volume index range");
7560 return BAD_VALUE;
7561 }
7562
jiabin9a3361e2019-10-01 09:38:30 -07007563 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7564 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007565 // Force VoIP volume to max for bluetooth SCO device except if muted
7566 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007567 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007568 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007569 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007570 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007571 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007572 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007573
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007574 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007575 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007576 // 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 +01007577 if (isVoiceVolSrc) {
7578 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007579 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007580 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007581 }
Eric Laurent18fba842016-03-31 14:41:26 -07007582 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007583 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7584 mLastVoiceVolume = voiceVolume;
7585 }
7586 }
Eric Laurente552edb2014-03-10 17:42:56 -07007587 return NO_ERROR;
7588}
7589
Eric Laurentc75307b2015-03-17 15:29:32 -07007590void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007591 const DeviceTypeSet& deviceTypes,
7592 int delayMs,
7593 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007594{
jiabincd510522020-01-22 09:40:55 -08007595 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007596 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7597 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7598 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007599 curves.getVolumeIndex(deviceTypes),
7600 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007601 }
7602}
7603
François Gaffiec005e562018-11-06 15:04:49 +01007604void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7605 bool on,
7606 const sp<AudioOutputDescriptor>& outputDesc,
7607 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007608 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007609{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007610 std::vector<VolumeSource> sourcesToMute;
7611 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7612 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7613 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007614 VolumeSource source = toVolumeSource(attributes, false);
7615 if ((source != VOLUME_SOURCE_NONE) &&
7616 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7617 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007618 sourcesToMute.push_back(source);
7619 }
Eric Laurente552edb2014-03-10 17:42:56 -07007620 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007621 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007622 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007623 }
7624
Eric Laurente552edb2014-03-10 17:42:56 -07007625}
7626
François Gaffieaaac0fd2018-11-22 17:56:39 +01007627void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7628 bool on,
7629 const sp<AudioOutputDescriptor>& outputDesc,
7630 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007631 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007632{
jiabin9a3361e2019-10-01 09:38:30 -07007633 if (deviceTypes.empty()) {
7634 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007635 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007636 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007637 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007638 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007639 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007640 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007641 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7642 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007643 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007644 }
7645 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007646 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7647 // ignored
7648 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007649 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007650 if (!outputDesc->isMuted(volumeSource)) {
7651 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007652 return;
7653 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007654 if (outputDesc->decMuteCount(volumeSource) == 0) {
7655 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007656 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007657 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007658 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007659 delayMs);
7660 }
7661 }
7662}
7663
François Gaffie53615e22015-03-19 09:24:12 +01007664bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7665{
François Gaffiec005e562018-11-06 15:04:49 +01007666 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007667 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7668 return true;
7669 }
7670
7671 // has known usage?
7672 switch (paa->usage) {
7673 case AUDIO_USAGE_UNKNOWN:
7674 case AUDIO_USAGE_MEDIA:
7675 case AUDIO_USAGE_VOICE_COMMUNICATION:
7676 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7677 case AUDIO_USAGE_ALARM:
7678 case AUDIO_USAGE_NOTIFICATION:
7679 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7680 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7681 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7682 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7683 case AUDIO_USAGE_NOTIFICATION_EVENT:
7684 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7685 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7686 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7687 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007688 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007689 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007690 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007691 case AUDIO_USAGE_EMERGENCY:
7692 case AUDIO_USAGE_SAFETY:
7693 case AUDIO_USAGE_VEHICLE_STATUS:
7694 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007695 break;
7696 default:
7697 return false;
7698 }
7699 return true;
7700}
7701
François Gaffie2110e042015-03-24 08:41:51 +01007702audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7703{
7704 return mEngine->getForceUse(usage);
7705}
7706
Eric Laurent96d1dda2022-03-14 17:14:19 +01007707bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007708 return isStateInCall(mEngine->getPhoneState());
7709}
7710
Eric Laurent96d1dda2022-03-14 17:14:19 +01007711bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007712 return is_state_in_call(state);
7713}
7714
Eric Laurentf9cccec2022-11-16 19:12:00 +01007715bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08007716 audio_mode_t mode = mEngine->getPhoneState();
7717 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007718 || (mode == AUDIO_MODE_CALL_SCREEN)
7719 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007720}
7721
Eric Laurentf9cccec2022-11-16 19:12:00 +01007722bool AudioPolicyManager::isInCallOrScreening() const {
7723 audio_mode_t mode = mEngine->getPhoneState();
7724 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
7725}
7726
Eric Laurentd60560a2015-04-10 11:31:20 -07007727void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7728{
7729 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007730 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007731 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007732 sourceDesc->sinkDevice()->equals(deviceDesc))
7733 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007734 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007735 }
7736 }
7737
7738 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7739 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7740 bool release = false;
7741 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7742 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7743 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7744 source->ext.device.type == deviceDesc->type()) {
7745 release = true;
7746 }
7747 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007748 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007749 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7750 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7751 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007752 sink->ext.device.type == deviceDesc->type() &&
7753 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7754 || strncmp(sink->ext.device.address, address,
7755 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007756 release = true;
7757 }
7758 }
7759 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007760 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7761 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007762 }
7763 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007764
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007765 mInputs.clearSessionRoutesForDevice(deviceDesc);
7766
Francois Gaffie716e1432019-01-14 16:58:59 +01007767 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007768}
7769
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007770void AudioPolicyManager::modifySurroundFormats(
7771 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007772 std::unordered_set<audio_format_t> enforcedSurround(
7773 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007774 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7775 for (const auto& pair : mConfig.getSurroundFormats()) {
7776 allSurround.insert(pair.first);
7777 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7778 }
Phil Burk09bc4612016-02-24 15:58:15 -08007779
7780 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7781 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007782 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007783 // This is the resulting set of formats depending on the surround mode:
7784 // 'all surround' = allSurround
7785 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7786 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7787 // 'manual surround' = mManualSurroundFormats
7788 // AUTO: formats v 'enforced surround'
7789 // ALWAYS: formats v 'all surround' v 'enforced surround'
7790 // NEVER: formats ^ 'non-surround'
7791 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007792
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007793 std::unordered_set<audio_format_t> formatSet;
7794 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7795 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007796 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007797 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007798 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007799 formatSet.insert(*formatIter);
7800 }
7801 }
7802 } else {
7803 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7804 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007805 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007806
jiabin81772902018-04-02 17:52:27 -07007807 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007808 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007809 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7810 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7811 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007812 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007813 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7814 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7815 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007816 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007817 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007818 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007819 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007820 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007821 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007822}
7823
jiabin06e4bab2019-07-29 10:13:34 -07007824void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7825 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007826 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7827 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7828
7829 // If NEVER, then remove support for channelMasks > stereo.
7830 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007831 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7832 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007833 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007834 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007835 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007836 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007837 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007838 }
7839 }
jiabin81772902018-04-02 17:52:27 -07007840 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7841 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7842 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007843 bool supports5dot1 = false;
7844 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007845 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007846 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7847 supports5dot1 = true;
7848 break;
7849 }
7850 }
7851 // If not then add 5.1 support.
7852 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007853 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007854 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007855 }
Phil Burk09bc4612016-02-24 15:58:15 -08007856 }
7857}
7858
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007859void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007860 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007861 AudioProfileVector &profiles)
7862{
7863 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007864 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007865
François Gaffie112b0af2015-11-19 16:13:25 +01007866 // Format MUST be checked first to update the list of AudioProfile
7867 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007868 reply = mpClientInterface->getParameters(
7869 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007870 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007871 AudioParameter repliedParameters(reply);
7872 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007873 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007874 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7875 return;
7876 }
Phil Burk09bc4612016-02-24 15:58:15 -08007877 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007878 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007879 if (device == AUDIO_DEVICE_OUT_HDMI
7880 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007881 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007882 }
jiabin3e277cc2019-09-10 14:27:34 -07007883 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007884 }
François Gaffie112b0af2015-11-19 16:13:25 +01007885
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007886 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007887 ChannelMaskSet channelMasks;
7888 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007889 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007890 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007891
7892 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007893 reply = mpClientInterface->getParameters(
7894 ioHandle,
7895 requestedParameters.toString() + ";" +
7896 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007897 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007898 AudioParameter repliedParameters(reply);
7899 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007900 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007901 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007902 }
7903 }
7904 if (profiles.hasDynamicChannelsFor(format)) {
7905 reply = mpClientInterface->getParameters(ioHandle,
7906 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007907 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007908 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007909 AudioParameter repliedParameters(reply);
7910 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007911 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007912 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007913 if (device == AUDIO_DEVICE_OUT_HDMI
7914 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007915 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007916 }
François Gaffie112b0af2015-11-19 16:13:25 +01007917 }
7918 }
jiabin3e277cc2019-09-10 14:27:34 -07007919 addDynamicAudioProfileAndSort(
7920 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007921 }
7922}
Eric Laurentd60560a2015-04-10 11:31:20 -07007923
Mikhail Naganovdc769682018-05-04 15:34:08 -07007924status_t AudioPolicyManager::installPatch(const char *caller,
7925 audio_patch_handle_t *patchHandle,
7926 AudioIODescriptorInterface *ioDescriptor,
7927 const struct audio_patch *patch,
7928 int delayMs)
7929{
7930 ssize_t index = mAudioPatches.indexOfKey(
7931 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7932 *patchHandle : ioDescriptor->getPatchHandle());
7933 sp<AudioPatch> patchDesc;
7934 status_t status = installPatch(
7935 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7936 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007937 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007938 }
7939 return status;
7940}
7941
7942status_t AudioPolicyManager::installPatch(const char *caller,
7943 ssize_t index,
7944 audio_patch_handle_t *patchHandle,
7945 const struct audio_patch *patch,
7946 int delayMs,
7947 uid_t uid,
7948 sp<AudioPatch> *patchDescPtr)
7949{
7950 sp<AudioPatch> patchDesc;
7951 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7952 if (index >= 0) {
7953 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007954 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007955 }
7956
7957 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7958 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7959 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7960 if (status == NO_ERROR) {
7961 if (index < 0) {
7962 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007963 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007964 } else {
7965 patchDesc->mPatch = *patch;
7966 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007967 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007968 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007969 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007970 }
7971 nextAudioPortGeneration();
7972 mpClientInterface->onAudioPatchListUpdate();
7973 }
7974 if (patchDescPtr) *patchDescPtr = patchDesc;
7975 return status;
7976}
7977
jiabinbce0c1d2020-10-05 11:20:18 -07007978bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7979{
7980 const TrackClientVector activeClients = output->getActiveClients();
7981 if (activeClients.empty()) {
7982 return true;
7983 }
7984 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7985 if (index < 0) {
7986 ALOGE("%s, no audio patch found while there are active clients on output %d",
7987 __func__, output->getId());
7988 return false;
7989 }
7990 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7991 DeviceVector routedDevices;
7992 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7993 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7994 patchDesc->mPatch.sinks[i].id);
7995 if (device == nullptr) {
7996 ALOGE("%s, no audio device found with id(%d)",
7997 __func__, patchDesc->mPatch.sinks[i].id);
7998 return false;
7999 }
8000 routedDevices.add(device);
8001 }
8002 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008003 if (client->isInvalid()) {
8004 // No need to take care about invalidated clients.
8005 continue;
8006 }
jiabinbce0c1d2020-10-05 11:20:18 -07008007 sp<DeviceDescriptor> preferredDevice =
8008 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8009 if (mEngine->getOutputDevicesForAttributes(
8010 client->attributes(), preferredDevice, false) == routedDevices) {
8011 return false;
8012 }
8013 }
8014 return true;
8015}
8016
8017sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008018 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008019 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8020 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008021{
8022 for (const auto& device : devices) {
8023 // TODO: This should be checking if the profile supports the device combo.
8024 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008025 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8026 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008027 return nullptr;
8028 }
8029 }
8030 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8031 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008032 status_t status = desc->open(halConfig, mixerConfig, devices,
8033 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008034 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008035 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008036 return nullptr;
8037 }
8038
8039 // Here is where the out_set_parameters() for card & device gets called
8040 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8041 const audio_devices_t deviceType = device->type();
8042 const String8 &address = String8(device->address().c_str());
8043 if (!address.isEmpty()) {
8044 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8045 mpClientInterface->setParameters(output, String8(param));
8046 free(param);
8047 }
8048 updateAudioProfiles(device, output, profile->getAudioProfiles());
8049 if (!profile->hasValidAudioProfile()) {
8050 ALOGW("%s() missing param", __func__);
8051 desc->close();
8052 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008053 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8054 // Reopen the output with the best audio profile picked by APM when the profile supports
8055 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008056 desc->close();
8057 output = AUDIO_IO_HANDLE_NONE;
8058 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8059 profile->pickAudioProfile(
8060 config.sample_rate, config.channel_mask, config.format);
8061 config.offload_info.sample_rate = config.sample_rate;
8062 config.offload_info.channel_mask = config.channel_mask;
8063 config.offload_info.format = config.format;
8064
jiabina84c3d32022-12-02 18:59:55 +00008065 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008066 if (status != NO_ERROR) {
8067 return nullptr;
8068 }
8069 }
8070
8071 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008072
baek.kim -61c20122022-07-27 10:05:32 +00008073 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8074 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8075
jiabinbce0c1d2020-10-05 11:20:18 -07008076 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8077 sp<AudioPolicyMix> policyMix;
8078 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8079 policyMix->setOutput(desc);
8080 desc->mPolicyMix = policyMix;
8081 } else {
8082 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
8083 address.string());
8084 }
8085
baek.kim -61c20122022-07-27 10:05:32 +00008086 } else if (hasPrimaryOutput() && speaker != nullptr
8087 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008088 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8089 // no duplicated output for:
8090 // - direct outputs
8091 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008092 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008093 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8094
8095 //TODO: configure audio effect output stage here
8096
8097 // open a duplicating output thread for the new output and the primary output
8098 sp<SwAudioOutputDescriptor> dupOutputDesc =
8099 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8100 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8101 if (status == NO_ERROR) {
8102 // add duplicated output descriptor
8103 addOutput(duplicatedOutput, dupOutputDesc);
8104 } else {
8105 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8106 mPrimaryOutput->mIoHandle, output);
8107 desc->close();
8108 removeOutput(output);
8109 nextAudioPortGeneration();
8110 return nullptr;
8111 }
8112 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008113 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8114 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8115 mPrimaryOutput = desc;
8116 }
jiabinbce0c1d2020-10-05 11:20:18 -07008117 return desc;
8118}
8119
jiabinf1c73972022-04-14 16:28:52 -07008120status_t AudioPolicyManager::getDevicesForAttributes(
8121 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8122 // Devices are determined in the following precedence:
8123 //
8124 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8125 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8126 //
8127 // If no such dynamic policy then
8128 // 2) Devices containing an active client using setPreferredDevice
8129 // with same strategy as the attributes.
8130 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8131 //
8132 // If no corresponding active client with setPreferredDevice then
8133 // 3) Devices associated with the strategy determined by the attributes
8134 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8135 //
8136 // See related getOutputForAttrInt().
8137
8138 // check dynamic policies but only for primary descriptors (secondary not used for audible
8139 // audio routing, only used for duplication for playback capture)
8140 sp<AudioPolicyMix> policyMix;
8141 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02008142 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE, policyMix,
jiabinf1c73972022-04-14 16:28:52 -07008143 nullptr /* secondaryMixes */);
8144 if (status != OK) {
8145 return status;
8146 }
8147
8148 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8149 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8150 // as they are unaffected by device/stream volume
8151 // (per SwAudioOutputDescriptor::isFixedVolume()).
8152 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8153 ) {
8154 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8155 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8156 devices.add(deviceDesc);
8157 } else {
8158 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8159 // which selects setPreferredDevice if active. This means forVolume call
8160 // will take an active setPreferredDevice, if such exists.
8161
8162 devices = mEngine->getOutputDevicesForAttributes(
8163 attr, nullptr /* preferredDevice */, false /* fromCache */);
8164 }
8165
8166 if (forVolume) {
8167 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8168 // for single volume control in AudioService (such relationship should exist if
8169 // SPEAKER_SAFE is present).
8170 //
8171 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8172 DeviceVector speakerSafeDevices =
8173 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8174 if (!speakerSafeDevices.isEmpty()) {
8175 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8176 devices.remove(speakerSafeDevices);
8177 }
8178 }
8179
8180 return NO_ERROR;
8181}
8182
8183status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8184 AudioProfileVector& audioProfiles,
8185 uint32_t flags,
8186 bool isInput) {
8187 for (const auto& hwModule : mHwModules) {
8188 // the MSD module checks for different conditions
8189 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8190 continue;
8191 }
8192 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8193 : hwModule->getOutputProfiles();
8194 for (const auto& profile : ioProfiles) {
8195 if (!profile->areAllDevicesSupported(devices) ||
8196 !profile->isCompatibleProfileForFlags(
8197 flags, false /*exactMatchRequiredForInputFlags*/)) {
8198 continue;
8199 }
8200 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8201 }
8202 }
8203
8204 if (!isInput) {
8205 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8206 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8207 if (msdModule != nullptr) {
8208 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8209 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8210 for (const auto &profile: msdModule->getOutputProfiles()) {
8211 if (!profile->asAudioPort()->isDirectOutput()) {
8212 continue;
8213 }
8214 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8215 }
8216 } else {
8217 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8218 }
8219 }
8220 }
8221
8222 return NO_ERROR;
8223}
8224
jiabina84c3d32022-12-02 18:59:55 +00008225status_t AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8226 const audio_config_t *config,
8227 audio_output_flags_t flags,
8228 const char* caller) {
8229 closeOutput(outputDesc->mIoHandle);
8230 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8231 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8232 if (preferredOutput == nullptr) {
8233 ALOGE("%s failed to reopen output device=%d, caller=%s",
8234 __func__, outputDesc->devices()[0]->getId(), caller);
8235 return BAD_VALUE;
8236 }
8237 return NO_ERROR;
8238}
8239
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008240} // namespace android