blob: 4c8aec7606eb3a7905928b4f27b6561114258048 [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
Eric Laurente552edb2014-03-10 17:42:56 -0700263 } break;
264
265 default:
François Gaffie11d30102018-11-02 16:09:09 +0100266 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700267 return BAD_VALUE;
268 }
269
Eric Laurent736a1022019-03-27 18:28:46 -0700270 // Propagate device availability to Engine
271 setEngineDeviceConnectionState(device, state);
272
Eric Laurentae970022019-01-29 14:25:04 -0800273 // No need to evaluate playback routing when connecting a remote submix
274 // output device used by a dynamic policy of type recorder as no
275 // playback use case is affected.
276 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700277 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800278 for (audio_io_handle_t output : outputs) {
279 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800280 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
281 if (policyMix != nullptr
282 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700283 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800284 doCheckForDeviceAndOutputChanges = false;
285 break;
286 }
287 }
288 }
289
290 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700291 // outputs must be closed after checkOutputForAllStrategies() is executed
292 if (!outputs.isEmpty()) {
293 for (audio_io_handle_t output : outputs) {
294 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100295 // close unused outputs after device disconnection or direct outputs that have
296 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200297 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200298 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
299 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200300 (desc->mDirectOpenCount == 0))
301 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
302 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200303 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700304 closeOutput(output);
305 }
Eric Laurente552edb2014-03-10 17:42:56 -0700306 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700307 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
308 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700310 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800311 };
312
313 if (doCheckForDeviceAndOutputChanges) {
314 checkForDeviceAndOutputChanges(checkCloseOutputs);
315 } else {
316 checkCloseOutputs();
317 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100318 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700319 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100320 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700321 const DeviceVector activeMediaDevices =
322 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700323 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700324 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530325 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
326 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100327 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 // do not force device change on duplicated output because if device is 0, it will
329 // also force a device 0 for the two outputs it is duplicated to which may override
330 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100331 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100332 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700333 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 // always force when disconnecting (a non-duplicated device)
335 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100336 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700337 }
jiabinbce0c1d2020-10-05 11:20:18 -0700338 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000339 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700340 desc->supportsDevicesForPlayback(activeMediaDevices)) {
341 // Reopen the output to query the dynamic profiles when there is not active
342 // clients or all active clients will be rerouted. Otherwise, set the flag
343 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
344 // can be reopened to query dynamic profiles when all clients are inactive.
345 if (areAllActiveTracksRerouted(desc)) {
346 outputsToReopen.push_back(mOutputs.keyAt(i));
347 } else {
348 desc->mPendingReopenToQueryProfiles = true;
349 }
350 }
351 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
352 // Clear the flag that previously set for re-querying profiles.
353 desc->mPendingReopenToQueryProfiles = false;
354 }
355 }
356 for (const auto& output : outputsToReopen) {
357 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
358 closeOutput(output);
359 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700360 }
361
Eric Laurentd60560a2015-04-10 11:31:20 -0700362 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100363 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700364 }
365
Eric Laurent96d1dda2022-03-14 17:14:19 +0100366 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
367
Eric Laurent72aa32f2014-05-30 18:51:48 -0700368 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700369 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700370 } // end if is output device
371
Eric Laurente552edb2014-03-10 17:42:56 -0700372 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700373 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100374 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700375 switch (state)
376 {
377 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700378 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700379 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100380 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700381 return INVALID_OPERATION;
382 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700383
384 if (mAvailableInputDevices.add(device) < 0) {
385 return NO_MEMORY;
386 }
387
François Gaffie44481e72016-04-20 07:49:57 +0200388 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
389 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100390 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200391
Eric Laurent0dd51852019-04-19 18:18:58 -0700392 if (checkInputsForDevice(device, state) != NO_ERROR) {
393 mAvailableInputDevices.remove(device);
394
François Gaffie11d30102018-11-02 16:09:09 +0100395 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100396
397 mHwModules.cleanUpForDevice(device);
398
Eric Laurentd4692962014-05-05 18:13:44 -0700399 return INVALID_OPERATION;
400 }
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700403
404 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700405 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700406 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100407 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700408 return INVALID_OPERATION;
409 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700410
François Gaffie11d30102018-11-02 16:09:09 +0100411 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700412
413 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100414 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700415
François Gaffie11d30102018-11-02 16:09:09 +0100416 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700417
418 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100419
420 // remove device from mReportedFormatsMap cache
421 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700422 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700423
424 default:
François Gaffie11d30102018-11-02 16:09:09 +0100425 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700426 return BAD_VALUE;
427 }
428
Eric Laurent736a1022019-03-27 18:28:46 -0700429 // Propagate device availability to Engine
430 setEngineDeviceConnectionState(device, state);
431
Eric Laurent0dd51852019-04-19 18:18:58 -0700432 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700433 // As the input device list can impact the output device selection, update
434 // getDeviceForStrategy() cache
435 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700436
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100437 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200438 // Reconnect Audio Source
439 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
440 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
441 checkAudioSourceForAttributes(attributes);
442 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700443 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100444 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700445 }
446
Eric Laurentb52c1522014-05-20 11:27:36 -0700447 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700449 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700450
François Gaffie11d30102018-11-02 16:09:09 +0100451 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700452 return BAD_VALUE;
453}
454
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100455status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
456 const char* device_name,
457 media::AudioPort* aidlPort) {
458 DeviceDescriptorBase devDescr(device, device_address);
459 devDescr.setName(device_name);
460 return devDescr.writeToParcelable(aidlPort);
461}
462
Eric Laurent736a1022019-03-27 18:28:46 -0700463void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
464 audio_policy_dev_state_t state) {
465
466 // the Engine does not have to know about remote submix devices used by dynamic audio policies
467 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
468 return;
469 }
470 mEngine->setDeviceConnectionState(device, state);
471}
472
473
Eric Laurente0720872014-03-11 09:30:41 -0700474audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100475 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700476{
Eric Laurent634b7142016-04-20 13:48:02 -0700477 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800478 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
479 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700480 (strlen(device_address) != 0)/*matchAddress*/);
481
482 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100483 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700484 device, device_address);
485 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
486 }
François Gaffie53615e22015-03-19 09:24:12 +0100487
Eric Laurent3a4311c2014-03-17 12:00:47 -0700488 DeviceVector *deviceVector;
489
Eric Laurente552edb2014-03-10 17:42:56 -0700490 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700491 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700492 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700493 deviceVector = &mAvailableInputDevices;
494 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100495 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700496 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700497 }
Eric Laurent634b7142016-04-20 13:48:02 -0700498
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800499 return (deviceVector->getDevice(
500 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700501 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800502}
503
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
505 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800506 const char *device_name,
507 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800508{
509 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700510 String8 reply;
511 AudioParameter param;
512 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800514 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
515 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800517 // connect/disconnect only 1 device at a time
518 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
519
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800520 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700521 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523 // Nothing to do: device is not connected
524 return NO_ERROR;
525 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800527
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700528 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800529 // configure codecs.
530 // Handle two specific cases by sending a set parameter to
531 // configure A2DP codecs. No need to toggle device state.
532 // Case 1: A2DP active device switches from primary to primary
533 // module
534 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200535 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700536 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800537 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
538 if (availablePrimaryOutputDevices().contains(devDesc) &&
539 (module != 0 && module->getHandle() == primaryHandle)) {
540 reply = mpClientInterface->getParameters(
541 AUDIO_IO_HANDLE_NONE,
542 String8(AudioParameter::keyReconfigA2dpSupported));
543 AudioParameter repliedParameters(reply);
544 repliedParameters.getInt(
545 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
546 if (isReconfigA2dpSupported) {
547 const String8 key(AudioParameter::keyReconfigA2dp);
548 param.add(key, String8("true"));
549 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
550 devDesc->setEncodedFormat(encodedFormat);
551 return NO_ERROR;
552 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700553 }
554 }
cnx421bd2dcc42020-07-11 14:58:44 +0800555 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
556 for (size_t i = 0; i < mOutputs.size(); i++) {
557 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
558 // mute media strategies and delay device switch by the largest
559 // This avoid sending the music tail into the earpiece or headset.
560 setStrategyMute(musicStrategy, true, desc);
561 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
562 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
563 nullptr, true /*fromCache*/).types());
564 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800565 // Toggle the device state: UNAVAILABLE -> AVAILABLE
566 // This will force reading again the device configuration
567 status = setDeviceConnectionState(device,
568 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800569 device_address, device_name,
570 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800571 if (status != NO_ERROR) {
572 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
573 status);
574 return status;
575 }
576
577 status = setDeviceConnectionState(device,
578 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800579 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800580 if (status != NO_ERROR) {
581 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
582 status);
583 return status;
584 }
585
586 return NO_ERROR;
587}
588
Pattydd807582021-11-04 21:01:03 +0800589status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
590 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800591{
Pattydd807582021-11-04 21:01:03 +0800592 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800593 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800594 std::unordered_set<audio_format_t> formatSet;
595 sp<HwModule> primaryModule =
596 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700597 if (primaryModule == nullptr) {
598 ALOGE("%s() unable to get primary module", __func__);
599 return NO_INIT;
600 }
Pattydd807582021-11-04 21:01:03 +0800601
602 DeviceTypeSet audioDeviceSet;
603
604 switch(device) {
605 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
606 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
607 break;
608 case AUDIO_DEVICE_OUT_BLE_HEADSET:
609 audioDeviceSet = getAudioDeviceOutAllBleSet();
610 break;
611 default:
612 ALOGE("%s() device type 0x%08x not supported", __func__, device);
613 return BAD_VALUE;
614 }
615
jiabin9a3361e2019-10-01 09:38:30 -0700616 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800617 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800618 for (const auto& device : declaredDevices) {
619 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800620 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800621 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800622 return status;
623}
624
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100625DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
626{
627 DeviceVector rxSinkdevices{};
628 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
629 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
630 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
631 auto rxSinkDevice = rxSinkdevices.itemAt(0);
632 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
633 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
634 // retrieve Rx Source device descriptor
635 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
636 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
637
638 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
639 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
640 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
641 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
642 return DeviceVector(rxSinkDevice);
643 }
644 }
645 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
646 // the device returned is not necessarily reachable via this output
647 // (filter later by setOutputDevices())
648 return getNewOutputDevices(mPrimaryOutput, fromCache);
649}
650
651status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
652{
653 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
654 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
655 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
656 }
657 return INVALID_OPERATION;
658}
659
660status_t AudioPolicyManager::updateCallRoutingInternal(
661 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700662{
663 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100664 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700665 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700666 if(!hasPrimaryOutput() ||
667 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100668 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700669 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100670 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100671
Francois Gaffie716e1432019-01-14 16:58:59 +0100672 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100673 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100674 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100675
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100677 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700678
Francois Gaffie601801d2021-06-22 13:27:39 +0200679 disconnectTelephonyAudioSource(mCallRxSourceClient);
680 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700681
François Gaffie9eb18552018-11-05 10:33:26 +0100682 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700683 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100684 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700685 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100686 // retrieve Rx Source and Tx Sink device descriptors
687 sp<DeviceDescriptor> rxSourceDevice =
688 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
689 String8(),
690 AUDIO_FORMAT_DEFAULT);
691 sp<DeviceDescriptor> txSinkDevice =
692 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
693 String8(),
694 AUDIO_FORMAT_DEFAULT);
695
696 // RX and TX Telephony device are declared by Primary Audio HAL
697 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
698 (telephonyRxModule->getHalVersionMajor() >= 3)) {
699 if (rxSourceDevice == 0 || txSinkDevice == 0) {
700 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100701 ALOGE("%s() no telephony Tx and/or RX device", __func__);
702 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100703 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100704 // createAudioPatchInternal now supports both HW / SW bridging
705 createRxPatch = true;
706 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100707 } else {
708 // If the RX device is on the primary HW module, then use legacy routing method for
709 // voice calls via setOutputDevice() on primary output.
710 // Otherwise, create two audio patches for TX and RX path.
711 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
712 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700713 // If the TX device is also on the primary HW module, setOutputDevice() will take care
714 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100715 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
716 (txSinkDevice != 0);
717 }
718 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
719 // Otherwise, create two audio patches for TX and RX path.
720 if (!createRxPatch) {
721 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700722 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200723 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800724 // If the TX device is on the primary HW module but RX device is
725 // on other HW module, SinkMetaData of telephony input should handle it
726 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700727 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700728 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100729 // terminate active capture if on the same HW module as the call TX source device
730 // FIXME: would be better to refine to only inputs whose profile connects to the
731 // call TX device but this information is not in the audio patch and logic here must be
732 // symmetric to the one in startInput()
733 for (const auto& activeDesc : mInputs.getActiveInputs()) {
734 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
735 closeActiveClients(activeDesc);
736 }
737 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200738 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800739 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100740 if (waitMs != nullptr) {
741 *waitMs = muteWaitMs;
742 }
743 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800744}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700745
Mikhail Naganov100f0122018-11-29 11:22:16 -0800746bool AudioPolicyManager::isDeviceOfModule(
747 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
748 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
749 if (module != 0) {
750 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
751 .indexOf(devDesc) != NAME_NOT_FOUND
752 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
753 .indexOf(devDesc) != NAME_NOT_FOUND;
754 }
755 return false;
756}
757
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200758void AudioPolicyManager::connectTelephonyRxAudioSource()
759{
Francois Gaffie601801d2021-06-22 13:27:39 +0200760 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200761 const struct audio_port_config source = {
762 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
763 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
764 };
765 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200766 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
767 ALOGE_IF(mCallRxSourceClient == nullptr,
768 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200769}
770
Francois Gaffie601801d2021-06-22 13:27:39 +0200771void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200772{
Francois Gaffie601801d2021-06-22 13:27:39 +0200773 if (clientDesc == nullptr) {
774 return;
775 }
776 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
777 "%s error stopping audio source", __func__);
778 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200779}
780
781void AudioPolicyManager::connectTelephonyTxAudioSource(
782 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
783 uint32_t delayMs)
784{
Francois Gaffie601801d2021-06-22 13:27:39 +0200785 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200786 if (srcDevice == nullptr || sinkDevice == nullptr) {
787 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
788 return;
789 }
790 PatchBuilder patchBuilder;
791 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
792 ALOGV("%s between source %s and sink %s", __func__,
793 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200794 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200795 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
796
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200797 struct audio_port_config source = {};
798 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200799 mCallTxSourceClient = new InternalSourceClientDescriptor(
800 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200801 mCommunnicationStrategy, toVolumeSource(aa));
802 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
803 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
805 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200806 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
807 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200808 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200809 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200810}
811
Eric Laurente0720872014-03-11 09:30:41 -0700812void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700813{
814 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100815 // store previous phone state for management of sonification strategy below
816 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100817 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100818
819 if (mEngine->setPhoneState(state) != NO_ERROR) {
820 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700821 return;
822 }
François Gaffie2110e042015-03-24 08:41:51 +0100823 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700824 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700825 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700826 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800827 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700828 }
829
François Gaffie2110e042015-03-24 08:41:51 +0100830 /**
831 * Switching to or from incall state or switching between telephony and VoIP lead to force
832 * routing command.
833 */
Eric Laurent74b71512019-11-06 17:21:57 -0800834 bool force = ((isStateInCall(oldState) != isStateInCall(state))
835 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700836
837 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700838 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700839
Eric Laurente552edb2014-03-10 17:42:56 -0700840 int delayMs = 0;
841 if (isStateInCall(state)) {
842 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100843 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
844 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700845 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700846 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700847 // mute media and sonification strategies and delay device switch by the largest
848 // latency of any output where either strategy is active.
849 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100850 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
851 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
852 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700853 (delayMs < (int)desc->latency()*2)) {
854 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700855 }
François Gaffiec005e562018-11-06 15:04:49 +0100856 setStrategyMute(musicStrategy, true, desc);
857 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
858 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
859 nullptr, true /*fromCache*/).types());
860 setStrategyMute(sonificationStrategy, true, desc);
861 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
862 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
863 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700864 }
865 }
866
Eric Laurent87ffa392015-05-22 10:32:38 -0700867 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700868 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100869 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700870 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100871 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
872 // force routing command to audio hardware when ending call
873 // even if no device change is needed
874 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
875 rxDevices = mPrimaryOutput->devices();
876 }
877 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200878 disconnectTelephonyAudioSource(mCallRxSourceClient);
879 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100880 }
François Gaffie11d30102018-11-02 16:09:09 +0100881 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700882 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700883 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700884
885 // reevaluate routing on all outputs in case tracks have been started during the call
886 for (size_t i = 0; i < mOutputs.size(); i++) {
887 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100888 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200889 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
890 bool forceRouting = !newDevices.isEmpty();
891 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
892 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700893 }
894 }
895
Eric Laurent96d1dda2022-03-14 17:14:19 +0100896 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
897
Eric Laurente552edb2014-03-10 17:42:56 -0700898 if (isStateInCall(state)) {
899 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700900 // force reevaluating accessibility routing when call starts
901 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700902 }
903
904 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100905 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
906 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700907}
908
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700909audio_mode_t AudioPolicyManager::getPhoneState() {
910 return mEngine->getPhoneState();
911}
912
Eric Laurente0720872014-03-11 09:30:41 -0700913void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100914 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700915{
François Gaffie2110e042015-03-24 08:41:51 +0100916 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700917 if (config == mEngine->getForceUse(usage)) {
918 return;
919 }
Eric Laurente552edb2014-03-10 17:42:56 -0700920
François Gaffie2110e042015-03-24 08:41:51 +0100921 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
922 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
923 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700924 }
François Gaffie2110e042015-03-24 08:41:51 +0100925 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
926 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
927 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700928
929 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700930 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800931
Eric Laurent22fcda22019-05-17 16:28:47 -0700932 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
933 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
934 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
935 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
936 }
937
Eric Laurentdc462862016-07-19 12:29:53 -0700938 //FIXME: workaround for truncated touch sounds
939 // to be removed when the problem is handled by system UI
940 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700941 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
942 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
943 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700944
945 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100946 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700947}
948
Eric Laurente0720872014-03-11 09:30:41 -0700949void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700950{
951 ALOGV("setSystemProperty() property %s, value %s", property, value);
952}
953
Dorin Drimusecc9f422022-03-09 17:57:40 +0100954// Find an MSD output profile compatible with the parameters passed.
955// When "directOnly" is set, restrict search to profiles for direct outputs.
956sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
957 const DeviceVector& devices,
958 uint32_t samplingRate,
959 audio_format_t format,
960 audio_channel_mask_t channelMask,
961 audio_output_flags_t flags,
962 bool directOnly)
963{
964 flags = getRelevantFlags(flags, directOnly);
965
966 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
967 if (msdModule != nullptr) {
968 // for the msd module check if there are patches to the output devices
969 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
970 HwModuleCollection modules;
971 modules.add(msdModule);
972 return searchCompatibleProfileHwModules(
973 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
974 flags, directOnly);
975 }
976 }
977 return nullptr;
978}
979
Michael Chana94fbb22018-04-24 14:31:19 +1000980// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
981// search to profiles for direct outputs.
982sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100983 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000984 uint32_t samplingRate,
985 audio_format_t format,
986 audio_channel_mask_t channelMask,
987 audio_output_flags_t flags,
988 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700989{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100990 flags = getRelevantFlags(flags, directOnly);
991
992 return searchCompatibleProfileHwModules(
993 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
994}
995
996audio_output_flags_t AudioPolicyManager::getRelevantFlags (
997 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000998 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100999 // only retain flags that will drive the direct output profile selection
1000 // if explicitly requested
1001 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001002 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001003 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1004 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001005 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001006 return flags;
1007}
Eric Laurent861a6282015-05-18 15:40:16 -07001008
Dorin Drimusecc9f422022-03-09 17:57:40 +01001009sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1010 const HwModuleCollection& hwModules,
1011 const DeviceVector& devices,
1012 uint32_t samplingRate,
1013 audio_format_t format,
1014 audio_channel_mask_t channelMask,
1015 audio_output_flags_t flags,
1016 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001017 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001018 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001019 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001020 if (!curProfile->isCompatibleProfile(devices,
1021 samplingRate, NULL /*updatedSamplingRate*/,
1022 format, NULL /*updatedFormat*/,
1023 channelMask, NULL /*updatedChannelMask*/,
1024 flags)) {
1025 continue;
1026 }
1027 // reject profiles not corresponding to a device currently available
1028 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1029 continue;
1030 }
1031 // reject profiles if connected device does not support codec
1032 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1033 continue;
1034 }
1035 if (!directOnly) {
1036 return curProfile;
1037 }
1038
1039 // when searching for direct outputs, if several profiles are compatible, give priority
1040 // to one with offload capability
1041 if (profile != 0 &&
1042 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001043 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001044 }
1045 profile = curProfile;
1046 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1047 break;
1048 }
Eric Laurente552edb2014-03-10 17:42:56 -07001049 }
1050 }
Eric Laurent861a6282015-05-18 15:40:16 -07001051 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001052}
1053
Eric Laurentfa0f6742021-08-17 18:39:44 +02001054sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001055 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001056{
1057 for (const auto& hwModule : mHwModules) {
1058 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001059 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001060 continue;
1061 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001062 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001063 // reject profiles not corresponding to a device currently available
1064 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1065 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1066 continue;
1067 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001068 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1069 != devices.size()) {
1070 continue;
1071 }
1072 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001073 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1074 return curProfile;
1075 }
1076 }
1077 return nullptr;
1078}
1079
Eric Laurentf4e63452017-11-06 19:31:46 +00001080audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001081{
François Gaffiec005e562018-11-06 15:04:49 +01001082 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001083
1084 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1085 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1086 // format, flags, etc. This may result in some discrepancy for functions that utilize
1087 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1088 // and AudioSystem::getOutputSamplingRate().
1089
François Gaffie11d30102018-11-02 16:09:09 +01001090 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001091 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001092
François Gaffie11d30102018-11-02 16:09:09 +01001093 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1094 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001095 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001096}
1097
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001098status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1099 const audio_attributes_t *srcAttr,
1100 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001101{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001102 if (srcAttr != NULL) {
1103 if (!isValidAttributes(srcAttr)) {
1104 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1105 __func__,
1106 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1107 srcAttr->tags);
1108 return BAD_VALUE;
1109 }
1110 *dstAttr = *srcAttr;
1111 } else {
1112 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1113 ALOGE("%s: invalid stream type", __func__);
1114 return BAD_VALUE;
1115 }
François Gaffiec005e562018-11-06 15:04:49 +01001116 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001117 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001118
1119 // Only honor audibility enforced when required. The client will be
1120 // forced to reconnect if the forced usage changes.
1121 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001122 dstAttr->flags = static_cast<audio_flags_mask_t>(
1123 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001124 }
1125
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001126 return NO_ERROR;
1127}
1128
Kevin Rocard153f92d2018-12-18 18:33:28 -08001129status_t AudioPolicyManager::getOutputForAttrInt(
1130 audio_attributes_t *resultAttr,
1131 audio_io_handle_t *output,
1132 audio_session_t session,
1133 const audio_attributes_t *attr,
1134 audio_stream_type_t *stream,
1135 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001136 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001137 audio_output_flags_t *flags,
1138 audio_port_handle_t *selectedDeviceId,
1139 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001140 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001141 output_type_t *outputType,
1142 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001143{
François Gaffiec005e562018-11-06 15:04:49 +01001144 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001145 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001146 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001147 const sp<DeviceDescriptor> requestedDevice =
1148 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1149
Eric Laurent8a1095a2019-11-08 14:44:16 -08001150 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001151 *isSpatialized = false;
1152
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001153 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1154 if (status != NO_ERROR) {
1155 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001156 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001157 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001158 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001159 }
François Gaffiec005e562018-11-06 15:04:49 +01001160 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001161
François Gaffiec005e562018-11-06 15:04:49 +01001162 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1163 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001164
Kevin Rocard153f92d2018-12-18 18:33:28 -08001165 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1166 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1167 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001168 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001169 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1170 .channel_mask = config->channel_mask,
1171 .format = config->format,
1172 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001173 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
1174 primaryMix, secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001175 if (status != OK) {
1176 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001177 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001178
Kevin Rocard153f92d2018-12-18 18:33:28 -08001179 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001180 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001181
1182 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001183 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1184 && !audio_is_linear_pcm(config->format)) {
1185 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001186 return BAD_VALUE;
1187 }
1188 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001189 sp<DeviceDescriptor> deviceDesc =
1190 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1191 primaryMix->mDeviceAddress,
1192 AUDIO_FORMAT_DEFAULT);
1193 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001194 bool tryDirectForFlags = policyDesc == nullptr ||
1195 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1196 // if a direct output can be opened to deliver the track's multi-channel content to the
1197 // output rather than being downmixed by the primary output, then use this direct
1198 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1199 // mix.
1200 bool tryDirectForChannelMask = policyDesc != nullptr
1201 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1202 audio_channel_count_from_out_mask(config->channel_mask));
1203 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001204 audio_io_handle_t newOutput;
1205 status = openDirectOutput(
1206 *stream, session, config,
1207 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1208 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001209 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001210 policyDesc = mOutputs.valueFor(newOutput);
1211 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001212 } else if (tryDirectForFlags) {
1213 policyDesc = nullptr;
1214 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001215 }
1216 if (policyDesc != nullptr) {
1217 policyDesc->mPolicyMix = primaryMix;
1218 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001219 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001220
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001221 ALOGV("getOutputForAttr() returns output %d", *output);
1222 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1223 *outputType = API_OUT_MIX_PLAYBACK;
1224 } else {
1225 *outputType = API_OUTPUT_LEGACY;
1226 }
1227 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001228 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001229 }
François Gaffiec005e562018-11-06 15:04:49 +01001230 // Virtual sources must always be dynamicaly or explicitly routed
1231 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1232 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1233 return BAD_VALUE;
1234 }
1235 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1236 // in order to let the choice of the order to future vendor engine
1237 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001238
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001239 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001240 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001241 }
1242
Nadav Barb2f18162018-07-18 13:01:53 +03001243 // Set incall music only if device was explicitly set, and fallback to the device which is
1244 // chosen by the engine if not.
1245 // FIXME: provide a more generic approach which is not device specific and move this back
1246 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001247 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001248 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001249 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001250 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001251 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001252 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001253 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001254 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001255 }
1256 }
1257
François Gaffiec005e562018-11-06 15:04:49 +01001258 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1259 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1260 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001261
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001262 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001263 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001264 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001265 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001266 ALOGV("%s() Using MSD devices %s instead of devices %s",
1267 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001268 } else {
1269 *output = AUDIO_IO_HANDLE_NONE;
1270 }
1271 }
1272 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001273 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001274 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001275 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001276 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001277 AudioProfileVector profiles;
1278 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1279 if (ret == NO_ERROR && !profiles.empty()) {
1280 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
1281 : *profiles[0]->getChannels().begin();
1282 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
1283 : *profiles[0]->getSampleRates().begin();
1284 config->format = profiles[0]->getFormat();
1285 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001286 return INVALID_OPERATION;
1287 }
Paul McLeanaa981192015-03-21 09:55:15 -07001288
François Gaffiec005e562018-11-06 15:04:49 +01001289 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001290 for (auto &outputDevice : outputDevices) {
1291 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1292 *selectedDeviceId = outputDevice->getId();
1293 break;
1294 }
1295 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001296
Eric Laurent8a1095a2019-11-08 14:44:16 -08001297 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1298 *outputType = API_OUTPUT_TELEPHONY_TX;
1299 } else {
1300 *outputType = API_OUTPUT_LEGACY;
1301 }
1302
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001303 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1304
1305 return NO_ERROR;
1306}
1307
1308status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1309 audio_io_handle_t *output,
1310 audio_session_t session,
1311 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001312 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001313 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001314 audio_output_flags_t *flags,
1315 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001316 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001317 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001318 output_type_t *outputType,
1319 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001320{
1321 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1322 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1323 return INVALID_OPERATION;
1324 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001325 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001326 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001327 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001328 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001329 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001330 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001331 const sp<DeviceDescriptor> requestedDevice =
1332 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1333
1334 // Prevent from storing invalid requested device id in clients
1335 const audio_port_handle_t sanitizedRequestedPortId =
1336 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1337 *selectedDeviceId = sanitizedRequestedPortId;
1338
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001339 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001340 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001341 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001342 if (status != NO_ERROR) {
1343 return status;
1344 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001345 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001346 if (secondaryOutputs != nullptr) {
1347 for (auto &secondaryMix : secondaryMixes) {
1348 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1349 if (outputDesc != nullptr &&
1350 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1351 secondaryOutputs->push_back(outputDesc->mIoHandle);
1352 weakSecondaryOutputDescs.push_back(outputDesc);
1353 }
1354 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001355 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001356
Eric Laurent8fc147b2018-07-22 19:13:55 -07001357 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001358 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001359 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001360 };
jiabin4ef93452019-09-10 14:29:54 -07001361 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001362
Eric Laurentc209fe42020-06-05 18:11:23 -07001363 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001364 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001365 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001366 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001367 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001368 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001369 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001370 std::move(weakSecondaryOutputDescs),
1371 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001372 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001373
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001374 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1375 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001376
Eric Laurente83b55d2014-11-14 10:06:21 -08001377 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001378}
1379
Eric Laurentc529cf62020-04-17 18:19:10 -07001380status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1381 audio_session_t session,
1382 const audio_config_t *config,
1383 audio_output_flags_t flags,
1384 const DeviceVector &devices,
1385 audio_io_handle_t *output) {
1386
1387 *output = AUDIO_IO_HANDLE_NONE;
1388
1389 // skip direct output selection if the request can obviously be attached to a mixed output
1390 // and not explicitly requested
1391 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1392 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1393 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1394 return NAME_NOT_FOUND;
1395 }
1396
1397 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1398 // This prevents creating an offloaded track and tearing it down immediately after start
1399 // when audioflinger detects there is an active non offloadable effect.
1400 // FIXME: We should check the audio session here but we do not have it in this context.
1401 // This may prevent offloading in rare situations where effects are left active by apps
1402 // in the background.
1403 sp<IOProfile> profile;
1404 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1405 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1406 profile = getProfileForOutput(
1407 devices, config->sample_rate, config->format, config->channel_mask,
1408 flags, true /* directOnly */);
1409 }
1410
1411 if (profile == nullptr) {
1412 return NAME_NOT_FOUND;
1413 }
1414
1415 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1416 for (size_t i = 0; i < mOutputs.size(); i++) {
1417 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1418 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1419 // reuse direct output if currently open by the same client
1420 // and configured with same parameters
1421 if ((config->sample_rate == desc->getSamplingRate()) &&
1422 (config->format == desc->getFormat()) &&
1423 (config->channel_mask == desc->getChannelMask()) &&
1424 (session == desc->mDirectClientSession)) {
1425 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001426 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001427 mOutputs.keyAt(i), session);
1428 *output = mOutputs.keyAt(i);
1429 return NO_ERROR;
1430 }
1431 }
1432 }
1433
1434 if (!profile->canOpenNewIo()) {
1435 return NAME_NOT_FOUND;
1436 }
1437
1438 sp<SwAudioOutputDescriptor> outputDesc =
1439 new SwAudioOutputDescriptor(profile, mpClientInterface);
1440
Michael Chan6fb34492020-12-08 15:44:49 +11001441 // An MSD patch may be using the only output stream that can service this request. Release
1442 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001443 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001444
Eric Laurentf1f22e72021-07-13 14:04:14 +02001445 status_t status =
1446 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001447
1448 // only accept an output with the requested parameters
1449 if (status != NO_ERROR ||
1450 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1451 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1452 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1453 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1454 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1455 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1456 config->channel_mask, outputDesc->getChannelMask());
1457 if (*output != AUDIO_IO_HANDLE_NONE) {
1458 outputDesc->close();
1459 }
1460 // fall back to mixer output if possible when the direct output could not be open
1461 if (audio_is_linear_pcm(config->format) &&
1462 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1463 return NAME_NOT_FOUND;
1464 }
1465 *output = AUDIO_IO_HANDLE_NONE;
1466 return BAD_VALUE;
1467 }
1468 outputDesc->mDirectOpenCount = 1;
1469 outputDesc->mDirectClientSession = session;
1470
1471 addOutput(*output, outputDesc);
1472 mPreviousOutputs = mOutputs;
1473 ALOGV("%s returns new direct output %d", __func__, *output);
1474 mpClientInterface->onAudioPortListUpdate();
1475 return NO_ERROR;
1476}
1477
François Gaffie11d30102018-11-02 16:09:09 +01001478audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1479 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001480 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001481 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001482 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001483 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001484 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001485 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001486{
Andy Hungc88b0642018-04-27 15:42:35 -07001487 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001488
jiabine375d412019-02-26 12:54:53 -08001489 // Discard haptic channel mask when forcing muting haptic channels.
1490 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001491 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1492 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001493
Eric Laurente552edb2014-03-10 17:42:56 -07001494 // open a direct output if required by specified parameters
1495 //force direct flag if offload flag is set: offloading implies a direct output stream
1496 // and all common behaviors are driven by checking only the direct flag
1497 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001498 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1499 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001500 }
Nadav Bar766fb022018-01-07 12:18:03 +02001501 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1502 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001503 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001504
1505 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1506
Eric Laurente83b55d2014-11-14 10:06:21 -08001507 // only allow deep buffering for music stream type
1508 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001509 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001510 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001511 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001512 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1513 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001514 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001515 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001516 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001517 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001518 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001519 audio_is_linear_pcm(config->format) &&
1520 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001521 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001522 AUDIO_OUTPUT_FLAG_DIRECT);
1523 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001524 }
Eric Laurente552edb2014-03-10 17:42:56 -07001525
Carter Hsua3abb402021-10-26 11:11:20 +08001526 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1527 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1528 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1529 }
1530
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001531 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001532 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001533 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001534 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001535 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001536 }
1537
Eric Laurentc529cf62020-04-17 18:19:10 -07001538 audio_config_t directConfig = *config;
1539 directConfig.channel_mask = channelMask;
1540 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1541 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001542 return output;
1543 }
1544
Eric Laurent14cbfca2016-03-17 09:42:16 -07001545 // A request for HW A/V sync cannot fallback to a mixed output because time
1546 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001547 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001548 return AUDIO_IO_HANDLE_NONE;
1549 }
1550
Eric Laurente552edb2014-03-10 17:42:56 -07001551 // ignoring channel mask due to downmix capability in mixer
1552
1553 // open a non direct output
1554
1555 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001556 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001557 // get which output is suitable for the specified stream. The actual
1558 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001559 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001560
Eric Laurent8838a382014-09-08 16:44:28 -07001561 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001562 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001563 output = selectOutput(
1564 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001565 }
François Gaffie11d30102018-11-02 16:09:09 +01001566 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001567 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001568 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001569
Eric Laurente552edb2014-03-10 17:42:56 -07001570 return output;
1571}
1572
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001573sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001574 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1575 mAvailableInputDevices);
1576 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1577}
1578
1579DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1580 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1581 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001582}
1583
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001584const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001585 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001586 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1587 if (msdModule != 0) {
1588 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1589 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1590 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1591 const struct audio_port_config *source = &patch->mPatch.sources[j];
1592 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1593 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001594 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001595 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001596 }
1597 }
1598 }
1599 return msdPatches;
1600}
1601
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001602bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1603 ssize_t index = mAudioPatches.indexOfKey(handle);
1604 if (index < 0) {
1605 return false;
1606 }
1607 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1608 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1609 if (msdModule == nullptr) {
1610 return false;
1611 }
1612 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1613 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1614 return true;
1615 }
1616 index = getMsdOutputPatches().indexOfKey(handle);
1617 if (index < 0) {
1618 return false;
1619 }
1620 return true;
1621}
1622
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001623status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1624 const InputProfileCollection &inputProfiles,
1625 const OutputProfileCollection &outputProfiles,
1626 const sp<DeviceDescriptor> &sourceDevice,
1627 const sp<DeviceDescriptor> &sinkDevice,
1628 AudioProfileVector& sourceProfiles,
1629 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001630 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001631 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001632 return NO_INIT;
1633 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001634 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001635 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001636 return NO_INIT;
1637 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001638 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001639 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1640 inProfile->supportsDevice(sourceDevice)) {
1641 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001642 }
1643 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001644 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001645 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001646 outProfile->supportsDevice(sinkDevice)) {
1647 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001648 }
1649 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001650 return NO_ERROR;
1651}
1652
1653status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1654 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1655 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1656{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001657 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001658 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1659 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1660 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001661 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001662 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1663 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001664 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001665 }
1666 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1667 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1668 sinkConfig->format = bestSinkConfig.format;
1669 // For encoded streams force direct flag to prevent downstream mixing.
1670 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1671 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001672 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1673 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001674 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001675 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1676 // raw and IEC61937 framed streams.
1677 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1678 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1679 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001680 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1681 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1682 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1683 sourceConfig->format = bestSinkConfig.format;
1684 // Copy input stream directly without any processing (e.g. resampling).
1685 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1686 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1687 if (hwAvSync) {
1688 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1689 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1690 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1691 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1692 }
1693 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1694 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1695 sinkConfig->config_mask |= config_mask;
1696 sourceConfig->config_mask |= config_mask;
1697 return NO_ERROR;
1698}
1699
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001700PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1701 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001702{
1703 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001704 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1705 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1706 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1707 if (deviceModule == nullptr) {
1708 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1709 return patchBuilder;
1710 }
1711 const InputProfileCollection inputProfiles = msdIsSource ?
1712 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1713 const OutputProfileCollection outputProfiles = msdIsSource ?
1714 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1715
1716 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1717 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1718 device : getMsdAudioOutDevices().itemAt(0);
1719 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1720
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001721 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1722 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001723 AudioProfileVector sourceProfiles;
1724 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001725 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1726 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001727 for (auto hwAvSync : { true, false }) {
1728 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1729 sourceProfiles, sinkProfiles) != NO_ERROR) {
1730 continue;
1731 }
1732 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1733 &sinkConfig) == NO_ERROR) {
1734 // Found a matching config. Re-create PatchBuilder with this config.
1735 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1736 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001737 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001738 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001739 " supporting PCM format conversion.", __func__);
1740 return patchBuilder;
1741}
1742
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001743status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001744 DeviceVector devices;
1745 if (outputDevices != nullptr && outputDevices->size() > 0) {
1746 devices.add(*outputDevices);
1747 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001748 // Use media strategy for unspecified output device. This should only
1749 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1750 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001751 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001752 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001753 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001754 }
Michael Chan6fb34492020-12-08 15:44:49 +11001755 std::vector<PatchBuilder> patchesToCreate;
1756 for (auto i = 0u; i < devices.size(); ++i) {
1757 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001758 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001759 }
1760 // Retain only the MSD patches associated with outputDevices request.
1761 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001762 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001763 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1764 auto retainedPatch = false;
1765 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1766 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1767 patchesToRemove.removeItemsAt(i);
1768 retainedPatch = true;
1769 break;
1770 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771 }
Michael Chan6fb34492020-12-08 15:44:49 +11001772 if (retainedPatch) {
1773 it = patchesToCreate.erase(it);
1774 continue;
1775 }
1776 ++it;
1777 }
1778 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1779 return NO_ERROR;
1780 }
1781 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1782 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001783 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001784 }
Michael Chan6fb34492020-12-08 15:44:49 +11001785 status_t status = NO_ERROR;
1786 for (const auto &p : patchesToCreate) {
1787 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1788 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1789 char message[256];
1790 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1791 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1792 currStatus == NO_ERROR ? "Success" : "Error",
1793 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1794 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1795 if (currStatus == NO_ERROR) {
1796 ALOGD("%s", message);
1797 } else {
1798 ALOGE("%s", message);
1799 if (status == NO_ERROR) {
1800 status = currStatus;
1801 }
1802 }
1803 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001804 return status;
1805}
1806
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001807void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1808 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001809 for (size_t i = 0; i < msdPatches.size(); i++) {
1810 const auto& patch = msdPatches[i];
1811 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1812 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1813 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1814 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1815 releaseAudioPatch(patch->getHandle(), mUidCached);
1816 break;
1817 }
1818 }
1819 }
1820}
1821
Dorin Drimus94d94412022-02-02 09:05:02 +01001822bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1823 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1824 AudioPatchCollection msdPatches = getMsdOutputPatches();
1825 for (size_t i = 0; i < msdPatches.size(); i++) {
1826 const auto& patch = msdPatches[i];
1827 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1828 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1829 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1830 const auto& foundDevice = devicesToCheck.getDevice(
1831 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1832 if (foundDevice != nullptr) {
1833 devicesToCheck.remove(foundDevice);
1834 if (devicesToCheck.isEmpty()) {
1835 return true;
1836 }
1837 }
1838 }
1839 }
1840 }
1841 return false;
1842}
1843
Eric Laurente0720872014-03-11 09:30:41 -07001844audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001845 audio_output_flags_t flags,
1846 audio_format_t format,
1847 audio_channel_mask_t channelMask,
1848 uint32_t samplingRate,
1849 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001850{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001851 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1852 "%s called with format %#x", __func__, format);
1853
jiabinebb6af42020-06-09 17:31:17 -07001854 // Return the output that haptic-generating attached to when 1) session id is specified,
1855 // 2) haptic-generating effect exists for given session id and 3) the output that
1856 // haptic-generating effect attached to is in given outputs.
1857 if (sessionId != AUDIO_SESSION_NONE) {
1858 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1859 sessionId, FX_IID_HAPTICGENERATOR);
1860 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1861 return hapticGeneratingOutput;
1862 }
1863 }
1864
Eric Laurent16c66dd2019-05-01 17:54:10 -07001865 // Flags disqualifying an output: the match must happen before calling selectOutput()
1866 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1867 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1868
1869 // Flags expressing a functional request: must be honored in priority over
1870 // other criteria
1871 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1872 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001873 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1874 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001875 // Flags expressing a performance request: have lower priority than serving
1876 // requested sampling rate or channel mask
1877 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1878 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1879 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1880
1881 const audio_output_flags_t functionalFlags =
1882 (audio_output_flags_t)(flags & kFunctionalFlags);
1883 const audio_output_flags_t performanceFlags =
1884 (audio_output_flags_t)(flags & kPerformanceFlags);
1885
1886 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1887
Eric Laurente552edb2014-03-10 17:42:56 -07001888 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001889 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001890 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001891 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001892 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001893 // with tiebreak preferring the minimum number of extra functional flags
1894 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001895 // 3: the output supporting the exact channel mask
1896 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00001897 // 5: the output with the highest sampling rate if the requested sample rate is
1898 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001899 // 6: the output with the highest number of requested performance flags
1900 // 7: the output with the bit depth the closest to the requested one
1901 // 8: the primary output
1902 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001903
Eric Laurent16c66dd2019-05-01 17:54:10 -07001904 // matching criteria values in priority order for best matching output so far
1905 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001906
Eric Laurent16c66dd2019-05-01 17:54:10 -07001907 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1908 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1909 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001910
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001911 for (audio_io_handle_t output : outputs) {
1912 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001913 // matching criteria values in priority order for current output
1914 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001915
Eric Laurent16c66dd2019-05-01 17:54:10 -07001916 if (outputDesc->isDuplicated()) {
1917 continue;
1918 }
1919 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1920 continue;
1921 }
Eric Laurent8838a382014-09-08 16:44:28 -07001922
Eric Laurent16c66dd2019-05-01 17:54:10 -07001923 // If haptic channel is specified, use the haptic output if present.
1924 // When using haptic output, same audio format and sample rate are required.
1925 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001926 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001927 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1928 continue;
1929 }
1930 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001931 && format == outputDesc->getFormat()
1932 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001933 currentMatchCriteria[0] = outputHapticChannelCount;
1934 }
1935
1936 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001937 const int matchingFunctionalFlags =
1938 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1939 const int totalFunctionalFlags =
1940 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1941 // Prefer matching functional flags, but subtract unnecessary functional flags.
1942 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001943
1944 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001945 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1946 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001947 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1948 channelCount <= outputChannelCount) {
1949 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001950 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1951 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001952 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001953 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001954 currentMatchCriteria[3] = outputChannelCount;
1955 }
1956
1957 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00001958 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001959 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001960 }
1961
1962 // performance flags match
1963 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1964
1965 // format match
1966 if (format != AUDIO_FORMAT_INVALID) {
1967 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001968 PolicyAudioPort::kFormatDistanceMax -
1969 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001970 }
1971
1972 // primary output match
1973 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1974
1975 // compare match criteria by priority then value
1976 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1977 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1978 bestMatchCriteria = currentMatchCriteria;
1979 bestOutput = output;
1980
1981 std::stringstream result;
1982 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1983 std::ostream_iterator<int>(result, " "));
1984 ALOGV("%s new bestOutput %d criteria %s",
1985 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001986 }
1987 }
1988
Eric Laurent16c66dd2019-05-01 17:54:10 -07001989 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001990}
1991
Eric Laurent8fc147b2018-07-22 19:13:55 -07001992status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001993{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001994 ALOGV("%s portId %d", __FUNCTION__, portId);
1995
1996 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1997 if (outputDesc == 0) {
1998 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001999 return BAD_VALUE;
2000 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002001 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002002
Eric Laurent8fc147b2018-07-22 19:13:55 -07002003 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002004 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002005
Eric Laurent733ce942017-12-07 12:18:25 -08002006 status_t status = outputDesc->start();
2007 if (status != NO_ERROR) {
2008 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002009 }
2010
Eric Laurent97ac8712018-07-27 18:59:02 -07002011 uint32_t delayMs;
2012 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002013
2014 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002015 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002016 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002017 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002018 if (delayMs != 0) {
2019 usleep(delayMs * 1000);
2020 }
2021
2022 return status;
2023}
2024
Eric Laurent96d1dda2022-03-14 17:14:19 +01002025bool AudioPolicyManager::isLeUnicastActive() const {
2026 if (isInCall()) {
2027 return true;
2028 }
2029 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2030}
2031
2032bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2033 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2034 return false;
2035 }
2036 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2037 ALOGV("%s active %d", __func__, active);
2038 return active;
2039}
2040
Eric Laurent97ac8712018-07-27 18:59:02 -07002041status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2042 const sp<TrackClientDescriptor>& client,
2043 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002044{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002045 // cannot start playback of STREAM_TTS if any other output is being used
2046 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002047
2048 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002049 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002050 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002051 auto clientStrategy = client->strategy();
2052 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002053 if (stream == AUDIO_STREAM_TTS) {
2054 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002055 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002056 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002057 return INVALID_OPERATION;
2058 } else {
2059 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2060 }
2061 } else {
2062 // some playback other than beacon starts
2063 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2064 }
2065
Eric Laurent77305a62016-07-25 16:39:22 -07002066 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002067 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002068 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002069
François Gaffie11d30102018-11-02 16:09:09 +01002070 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002071 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002072 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002073 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002074 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002075 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002076 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002077 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002078 } else {
2079 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002080 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002081 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2082 AUDIO_FORMAT_DEFAULT);
2083 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2084 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002085 }
2086
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002087 // requiresMuteCheck is false when we can bypass mute strategy.
2088 // It covers a common case when there is no materially active audio
2089 // and muting would result in unnecessary delay and dropped audio.
2090 const uint32_t outputLatencyMs = outputDesc->latency();
2091 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002092 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002093
Eric Laurente552edb2014-03-10 17:42:56 -07002094 // increment usage count for this stream on the requested output:
2095 // NOTE that the usage count is the same for duplicated output and hardware output which is
2096 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002097 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002098
2099 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002100 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2101 client->isPreferredDeviceForExclusiveUse()) {
2102 // Preferred device may be exclusive, use only if no other active clients on this output
2103 devices = DeviceVector(
2104 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2105 } else {
2106 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2107 }
François Gaffie11d30102018-11-02 16:09:09 +01002108 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002109 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002110 }
2111 }
Eric Laurente552edb2014-03-10 17:42:56 -07002112
François Gaffiec005e562018-11-06 15:04:49 +01002113 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002114 selectOutputForMusicEffects();
2115 }
2116
François Gaffie1c878552018-11-22 16:53:21 +01002117 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002118 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002119 if (devices.isEmpty()) {
2120 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002121 }
François Gaffiec005e562018-11-06 15:04:49 +01002122 bool shouldWait =
2123 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2124 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2125 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002126 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002127 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002128 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002129 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002130 // An output has a shared device if
2131 // - managed by the same hw module
2132 // - supports the currently selected device
2133 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002134 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002135
Eric Laurent77305a62016-07-25 16:39:22 -07002136 // force a device change if any other output is:
2137 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002138 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002139 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002140 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002141 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002142 // change the device currently selected by the other output.
2143 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002144 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002145 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002146 force = true;
2147 }
2148 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002149 // a notification so that audio focus effect can propagate, or that a mute/unmute
2150 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002151 const uint32_t latencyMs = desc->latency();
2152 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2153
2154 if (shouldWait && isActive && (waitMs < latencyMs)) {
2155 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002156 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002157
2158 // Require mute check if another output is on a shared device
2159 // and currently active to have proper drain and avoid pops.
2160 // Note restoring AudioTracks onto this output needs to invoke
2161 // a volume ramp if there is no mute.
2162 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002163 }
2164 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002165
2166 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002167 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002168
Eric Laurente552edb2014-03-10 17:42:56 -07002169 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002170 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002171 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002172 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002173 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002174 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002175 outputDesc->useHwGain() /*force*/)) {
2176 // request AudioService to reinitialize the volume curves asynchronously
2177 ALOGE("checkAndSetVolume failed, requesting volume range init");
2178 mpClientInterface->onVolumeRangeInitRequest();
2179 };
Eric Laurente552edb2014-03-10 17:42:56 -07002180
2181 // update the outputs if starting an output with a stream that can affect notification
2182 // routing
2183 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002184
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002185 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002186 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002187 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2188 }
Eric Laurentdc462862016-07-19 12:29:53 -07002189
2190 if (waitMs > muteWaitMs) {
2191 *delayMs = waitMs - muteWaitMs;
2192 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002193
2194 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2195 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2196 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2197 // change occurs after the MixerThread starts and causes a stream volume
2198 // glitch.
2199 //
2200 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002201 }
Eric Laurentdc462862016-07-19 12:29:53 -07002202
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002203 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002204 mEngine->getForceUse(
2205 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002206 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002207 }
2208
Eric Laurent97ac8712018-07-27 18:59:02 -07002209 // Automatically enable the remote submix input when output is started on a re routing mix
2210 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002211 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2212 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002213 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2214 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2215 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002216 "remote-submix",
2217 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002218 }
2219
Eric Laurent96d1dda2022-03-14 17:14:19 +01002220 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2221
Eric Laurente552edb2014-03-10 17:42:56 -07002222 return NO_ERROR;
2223}
2224
Eric Laurent96d1dda2022-03-14 17:14:19 +01002225void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2226 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2227 bool isUnicastActive = isLeUnicastActive();
2228
2229 if (wasUnicastActive != isUnicastActive) {
2230 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2231 for (size_t i = 0; i < mOutputs.size(); i++) {
2232 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2233 if (desc != ignoredOutput && desc->isActive()
2234 && ((isUnicastActive &&
2235 !desc->devices().
2236 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2237 || (wasUnicastActive &&
2238 !desc->devices().getDevicesFromTypes(
2239 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2240 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2241 bool force = desc->devices() != newDevices;
2242 setOutputDevices(desc, newDevices, force, delayMs);
2243 // re-apply device specific volume if not done by setOutputDevice()
2244 if (!force) {
2245 applyStreamVolumes(desc, newDevices.types(), delayMs);
2246 }
2247 }
2248 }
2249 }
2250}
2251
Eric Laurent8fc147b2018-07-22 19:13:55 -07002252status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002253{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002254 ALOGV("%s portId %d", __FUNCTION__, portId);
2255
2256 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2257 if (outputDesc == 0) {
2258 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002259 return BAD_VALUE;
2260 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002261 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002262
Eric Laurent97ac8712018-07-27 18:59:02 -07002263 ALOGV("stopOutput() output %d, stream %d, session %d",
2264 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002265
Eric Laurent97ac8712018-07-27 18:59:02 -07002266 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002267
Eric Laurent733ce942017-12-07 12:18:25 -08002268 if (status == NO_ERROR ) {
2269 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002270 }
2271 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002272}
2273
Eric Laurent97ac8712018-07-27 18:59:02 -07002274status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2275 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002276{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002277 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002278 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002279 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002280 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002281
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002282 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2283
François Gaffie1c878552018-11-22 16:53:21 +01002284 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2285 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002286 // Automatically disable the remote submix input when output is stopped on a
2287 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002288 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002289 if (isSingleDeviceType(
2290 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002291 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002292 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002293 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2294 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002295 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002296 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002297 }
2298 }
2299 bool forceDeviceUpdate = false;
2300 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002301 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002302 forceDeviceUpdate = true;
2303 }
2304
Eric Laurente552edb2014-03-10 17:42:56 -07002305 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002306 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002307
Eric Laurente552edb2014-03-10 17:42:56 -07002308 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002309 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002310 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002311 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002312
2313 // If the routing does not change, if an output is routed on a device using HwGain
2314 // (aka setAudioPortConfig) and there are still active clients following different
2315 // volume group(s), force reapply volume
2316 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2317 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2318
Eric Laurente552edb2014-03-10 17:42:56 -07002319 // delay the device switch by twice the latency because stopOutput() is executed when
2320 // the track stop() command is received and at that time the audio track buffer can
2321 // still contain data that needs to be drained. The latency only covers the audio HAL
2322 // and kernel buffers. Also the latency does not always include additional delay in the
2323 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002324 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2325 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002326
2327 // force restoring the device selection on other active outputs if it differs from the
2328 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002329 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002330 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002331 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002332 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002333 desc->isActive() &&
2334 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002335 (newDevices != desc->devices())) {
2336 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2337 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002338
François Gaffie11d30102018-11-02 16:09:09 +01002339 setOutputDevices(desc, newDevices2, force, delayMs);
2340
Eric Laurent57de36c2016-09-28 16:59:11 -07002341 // re-apply device specific volume if not done by setOutputDevice()
2342 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002343 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002344 }
Eric Laurente552edb2014-03-10 17:42:56 -07002345 }
2346 }
2347 // update the outputs if stopping one with a stream that can affect notification routing
2348 handleNotificationRoutingForStream(stream);
2349 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002350
2351 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2352 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002353 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002354 }
2355
François Gaffiec005e562018-11-06 15:04:49 +01002356 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002357 selectOutputForMusicEffects();
2358 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002359
2360 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2361
Eric Laurente552edb2014-03-10 17:42:56 -07002362 return NO_ERROR;
2363 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002364 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002365 return INVALID_OPERATION;
2366 }
2367}
2368
jiabinbce0c1d2020-10-05 11:20:18 -07002369bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002370{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002371 ALOGV("%s portId %d", __FUNCTION__, portId);
2372
2373 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2374 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002375 // If an output descriptor is closed due to a device routing change,
2376 // then there are race conditions with releaseOutput from tracks
2377 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2378 // destroyed shortly thereafter.
2379 //
2380 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002381 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002382 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002383 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002384
2385 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002386
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302387 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2388 if (outputDesc->isClientActive(client)) {
2389 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2390 stopOutput(portId);
2391 }
2392
Eric Laurent8fc147b2018-07-22 19:13:55 -07002393 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2394 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002395 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002396 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002397 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002398 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002399 if (--outputDesc->mDirectOpenCount == 0) {
2400 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002401 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002402 }
2403 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302404
Andy Hung39efb7a2018-09-26 15:39:28 -07002405 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002406 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2407 // The output is pending reopened to query dynamic profiles and
2408 // there is no active clients
2409 closeOutput(outputDesc->mIoHandle);
2410 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2411 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2412 if (newOutputDesc == nullptr) {
2413 ALOGE("%s failed to open output", __func__);
2414 }
2415 return true;
2416 }
2417 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002418}
2419
Eric Laurentcaf7f482014-11-25 17:50:47 -08002420status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2421 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002422 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002423 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002424 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002425 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002426 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002427 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002428 input_type_t *inputType,
2429 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002430{
François Gaffiec005e562018-11-06 15:04:49 +01002431 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002432 "flags %#x attributes=%s requested device ID %d",
2433 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2434 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002435
Eric Laurentad2e7b92017-09-14 20:06:42 -07002436 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002437 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002438 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002439 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002440 sp<AudioInputDescriptor> inputDesc;
2441 sp<RecordClientDescriptor> clientDesc;
2442 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002443 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002444 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002445
2446 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2447 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2448 return INVALID_OPERATION;
2449 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002450
Francois Gaffie716e1432019-01-14 16:58:59 +01002451 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2452 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002453 }
2454
Paul McLean466dc8e2015-04-17 13:15:36 -06002455 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002456 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002457 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002458
Eric Laurentad2e7b92017-09-14 20:06:42 -07002459 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2460 // possible
2461 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2462 *input != AUDIO_IO_HANDLE_NONE) {
2463 ssize_t index = mInputs.indexOfKey(*input);
2464 if (index < 0) {
2465 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2466 status = BAD_VALUE;
2467 goto error;
2468 }
2469 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002470 RecordClientVector clients = inputDesc->getClientsForSession(session);
2471 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002472 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2473 status = BAD_VALUE;
2474 goto error;
2475 }
2476 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2477 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002478 // corresponds to a new client and is only permitted from the same UID.
2479 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002480 if (clients.size() > 1) {
2481 for (const auto& client : clients) {
2482 // The client map is ordered by key values (portId) and portIds are allocated
2483 // incrementaly. So the first client in this list is the one opened by audio flinger
2484 // when the mmap stream is created and should be ignored as it does not correspond
2485 // to an actual client
2486 if (client == *clients.cbegin()) {
2487 continue;
2488 }
2489 if (uid != client->uid() && !client->isSilenced()) {
2490 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2491 uid, client->portId(), client->uid());
2492 status = INVALID_OPERATION;
2493 goto error;
2494 }
Eric Laurent331679c2018-04-16 17:03:16 -07002495 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002496 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002497 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002498 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002499
Eric Laurentfecbceb2021-02-09 14:46:43 +01002500 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002501 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002502 }
2503
2504 *input = AUDIO_IO_HANDLE_NONE;
2505 *inputType = API_INPUT_INVALID;
2506
Francois Gaffie716e1432019-01-14 16:58:59 +01002507 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002508 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002509 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002510 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002511 ALOGW("%s could not find input mix for attr %s",
2512 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002513 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002514 }
jiabinc1de2df2019-05-07 14:26:40 -07002515 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2516 String8(attr->tags + strlen("addr=")),
2517 AUDIO_FORMAT_DEFAULT);
2518 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002519 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002520 __func__, attributes.source, attributes.tags);
2521 status = BAD_VALUE;
2522 goto error;
2523 }
2524
Kevin Rocard25f9b052019-02-27 15:08:54 -08002525 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2526 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2527 } else {
2528 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2529 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002530 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002531 if (explicitRoutingDevice != nullptr) {
2532 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002533 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002534 // Prevent from storing invalid requested device id in clients
2535 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002536 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002537 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2538 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002539 }
François Gaffie11d30102018-11-02 16:09:09 +01002540 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002541 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002542 status = BAD_VALUE;
2543 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002544 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002545 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2546 *inputType = API_INPUT_MIX_CAPTURE;
2547 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002548 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2549 // there is an external policy, but this input is attached to a mix of recorders,
2550 // meaning it receives audio injected into the framework, so the recorder doesn't
2551 // know about it and is therefore considered "legacy"
2552 *inputType = API_INPUT_LEGACY;
2553 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002554 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002555 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002556 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002557 } else {
2558 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002559 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002560
Eric Laurent599c7582015-12-07 18:05:55 -08002561 }
2562
François Gaffiec005e562018-11-06 15:04:49 +01002563 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002564 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002565 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002566 AudioProfileVector profiles;
2567 status_t ret = getProfilesForDevices(
2568 DeviceVector(device), profiles, flags, true /*isInput*/);
2569 if (ret == NO_ERROR && !profiles.empty()) {
2570 config->channel_mask = profiles[0]->getChannels().empty() ? config->channel_mask
2571 : *profiles[0]->getChannels().begin();
2572 config->sample_rate = profiles[0]->getSampleRates().empty() ? config->sample_rate
2573 : *profiles[0]->getSampleRates().begin();
2574 config->format = profiles[0]->getFormat();
2575 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002576 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002577 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002578
Eric Laurent8f42ea12018-08-08 09:08:25 -07002579exit:
2580
François Gaffiec005e562018-11-06 15:04:49 +01002581 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2582 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002583
Francois Gaffie716e1432019-01-14 16:58:59 +01002584 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002585 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002586 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002587
Mikhail Naganov2996f672019-04-18 12:29:59 -07002588 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002589 requestedDeviceId, attributes.source, flags,
2590 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002591 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002592 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002593
2594 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2595 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002596
Eric Laurent599c7582015-12-07 18:05:55 -08002597 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002598
2599error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002600 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002601}
2602
2603
François Gaffie11d30102018-11-02 16:09:09 +01002604audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002605 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002606 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002607 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002608 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002609 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002610{
2611 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002612 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002613 bool isSoundTrigger = false;
2614
François Gaffiec005e562018-11-06 15:04:49 +01002615 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002616 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2617 if (index >= 0) {
2618 input = mSoundTriggerSessions.valueFor(session);
2619 isSoundTrigger = true;
2620 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2621 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2622 } else {
2623 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002624 }
François Gaffiec005e562018-11-06 15:04:49 +01002625 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002626 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002627 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002628 }
2629
Carter Hsua3abb402021-10-26 11:11:20 +08002630 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2631 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2632 }
2633
Eric Laurentfe231122017-11-17 17:48:06 -08002634 // sampling rate and flags may be updated by getInputProfile
2635 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2636 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002637 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002638 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002639 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002640 // find a compatible input profile (not necessarily identical in parameters)
2641 sp<IOProfile> profile = getInputProfile(
2642 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2643 if (profile == nullptr) {
2644 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002645 }
jiabin2fd710d2022-05-02 23:20:22 +00002646
Glenn Kasten05ddca52016-02-11 08:17:12 -08002647 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002648 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002649 if (samplingRate == 0) {
2650 samplingRate = profileSamplingRate;
2651 }
Eric Laurente552edb2014-03-10 17:42:56 -07002652
Eric Laurent322b4d22015-04-03 15:57:54 -07002653 if (profile->getModuleHandle() == 0) {
2654 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002655 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002656 }
2657
Eric Laurentec376dc2021-04-08 20:41:22 +02002658 // Reuse an already opened input if a client with the same session ID already exists
2659 // on that input
2660 for (size_t i = 0; i < mInputs.size(); i++) {
2661 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2662 if (desc->mProfile != profile) {
2663 continue;
2664 }
2665 RecordClientVector clients = desc->clientsList();
2666 for (const auto &client : clients) {
2667 if (session == client->session()) {
2668 return desc->mIoHandle;
2669 }
2670 }
2671 }
2672
Eric Laurent3974e3b2017-12-07 17:58:43 -08002673 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002674 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002675 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002676 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002677 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002678 continue;
2679 }
2680 // if sound trigger, reuse input if used by other sound trigger on same session
2681 // else
2682 // reuse input if active client app is not in IDLE state
2683 //
2684 RecordClientVector clients = desc->clientsList();
2685 bool doClose = false;
2686 for (const auto& client : clients) {
2687 if (isSoundTrigger != client->isSoundTrigger()) {
2688 continue;
2689 }
2690 if (client->isSoundTrigger()) {
2691 if (session == client->session()) {
2692 return desc->mIoHandle;
2693 }
2694 continue;
2695 }
2696 if (client->active() && client->appState() != APP_STATE_IDLE) {
2697 return desc->mIoHandle;
2698 }
2699 doClose = true;
2700 }
2701 if (doClose) {
2702 closeInput(desc->mIoHandle);
2703 } else {
2704 i++;
2705 }
2706 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002707 }
2708
Eric Laurentfe231122017-11-17 17:48:06 -08002709 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002710
Eric Laurentfe231122017-11-17 17:48:06 -08002711 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2712 lConfig.sample_rate = profileSamplingRate;
2713 lConfig.channel_mask = profileChannelMask;
2714 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002715
François Gaffie11d30102018-11-02 16:09:09 +01002716 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002717
2718 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002719 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002720 (profileSamplingRate != lConfig.sample_rate) ||
2721 !audio_formats_match(profileFormat, lConfig.format) ||
2722 (profileChannelMask != lConfig.channel_mask)) {
2723 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002724 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002725 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002726 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002727 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002728 }
Eric Laurent599c7582015-12-07 18:05:55 -08002729 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002730 }
2731
Eric Laurentc722f302014-12-10 11:21:49 -08002732 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002733
Eric Laurent599c7582015-12-07 18:05:55 -08002734 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002735 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002736
Eric Laurent599c7582015-12-07 18:05:55 -08002737 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002738}
2739
Eric Laurent4eb58f12018-12-07 16:41:02 -08002740status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002741{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002742 ALOGV("%s portId %d", __FUNCTION__, portId);
2743
2744 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2745 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002746 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002747 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002748 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002749 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002750 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002751 if (client->active()) {
2752 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2753 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002754 }
2755
Eric Laurent8f42ea12018-08-08 09:08:25 -07002756 audio_session_t session = client->session();
2757
Eric Laurent4eb58f12018-12-07 16:41:02 -08002758 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002759
Eric Laurent4eb58f12018-12-07 16:41:02 -08002760 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002761
Eric Laurent4eb58f12018-12-07 16:41:02 -08002762 status_t status = inputDesc->start();
2763 if (status != NO_ERROR) {
2764 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002765 }
Eric Laurente552edb2014-03-10 17:42:56 -07002766
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002767 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002768 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002769 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002770
Eric Laurent8f42ea12018-08-08 09:08:25 -07002771 // indicate active capture to sound trigger service if starting capture from a mic on
2772 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002773 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002774 if (device != nullptr) {
2775 status = setInputDevice(input, device, true /* force */);
2776 } else {
2777 ALOGW("%s no new input device can be found for descriptor %d",
2778 __FUNCTION__, inputDesc->getId());
2779 status = BAD_VALUE;
2780 }
Eric Laurente552edb2014-03-10 17:42:56 -07002781
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002782 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002783 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002784 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002785 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002786 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2787 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002788 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002789 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002790
François Gaffie11d30102018-11-02 16:09:09 +01002791 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2792 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002793 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002794 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002795 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002796
Eric Laurent8f42ea12018-08-08 09:08:25 -07002797 // automatically enable the remote submix output when input is started if not
2798 // used by a policy mix of type MIX_TYPE_RECORDERS
2799 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002800 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002801 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002802 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002803 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002804 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2805 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002806 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002807 if (address != "") {
2808 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2809 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002810 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002811 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002812 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002813 } else if (status != NO_ERROR) {
2814 // Restore client activity state.
2815 inputDesc->setClientActive(client, false);
2816 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002817 }
2818
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002819 ALOGV("%s input %d source = %d status = %d exit",
2820 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002821
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002822 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002823}
2824
Eric Laurent8fc147b2018-07-22 19:13:55 -07002825status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002826{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002827 ALOGV("%s portId %d", __FUNCTION__, portId);
2828
2829 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2830 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002831 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002832 return BAD_VALUE;
2833 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002835 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002836 if (!client->active()) {
2837 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002838 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002839 }
Carter Hsue6139d52021-07-08 10:30:20 +08002840 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002841 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002842
Eric Laurent8f42ea12018-08-08 09:08:25 -07002843 inputDesc->stop();
2844 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002845 auto current_source = inputDesc->source();
2846 setInputDevice(input, getNewInputDevice(inputDesc),
2847 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002848 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002849 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002850 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002851 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002852 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2853 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002854 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002855 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002856
2857 // automatically disable the remote submix output when input is stopped if not
2858 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002859 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002860 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002861 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002862 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002863 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2864 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002865 }
2866 if (address != "") {
2867 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2868 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002869 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002870 }
2871 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002872 resetInputDevice(input);
2873
2874 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2875 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002876 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2877 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002878 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002879 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002880 }
2881 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002882 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002883 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002884}
2885
Eric Laurent8fc147b2018-07-22 19:13:55 -07002886void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002887{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002888 ALOGV("%s portId %d", __FUNCTION__, portId);
2889
2890 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2891 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002892 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002893 return;
2894 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002895 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002896 audio_io_handle_t input = inputDesc->mIoHandle;
2897
Eric Laurent8f42ea12018-08-08 09:08:25 -07002898 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002899
Andy Hung39efb7a2018-09-26 15:39:28 -07002900 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002901
Andy Hung39efb7a2018-09-26 15:39:28 -07002902 if (inputDesc->getClientCount() > 0) {
2903 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002904 return;
2905 }
2906
Eric Laurent05b90f82014-08-27 15:32:29 -07002907 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002908 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002909 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002910}
2911
Eric Laurent8f42ea12018-08-08 09:08:25 -07002912void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002913{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002914 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002915
2916 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002917 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002918 }
2919}
2920
Eric Laurent8f42ea12018-08-08 09:08:25 -07002921void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2922{
2923 stopInput(portId);
2924 releaseInput(portId);
2925}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002926
Eric Laurent0dd51852019-04-19 18:18:58 -07002927void AudioPolicyManager::checkCloseInputs() {
2928 // After connecting or disconnecting an input device, close input if:
2929 // - it has no client (was just opened to check profile) OR
2930 // - none of its supported devices are connected anymore OR
2931 // - one of its clients cannot be routed to one of its supported
2932 // devices anymore. Otherwise update device selection
2933 std::vector<audio_io_handle_t> inputsToClose;
2934 for (size_t i = 0; i < mInputs.size(); i++) {
2935 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2936 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002937 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002938 inputsToClose.push_back(mInputs.keyAt(i));
2939 } else {
2940 bool close = false;
2941 for (const auto& client : input->clientsList()) {
2942 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002943 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
2944 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07002945 if (!input->supportedDevices().contains(device)) {
2946 close = true;
2947 break;
2948 }
2949 }
2950 if (close) {
2951 inputsToClose.push_back(mInputs.keyAt(i));
2952 } else {
2953 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2954 }
2955 }
2956 }
2957
2958 for (const audio_io_handle_t handle : inputsToClose) {
2959 ALOGV("%s closing input %d", __func__, handle);
2960 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002961 }
Eric Laurentd4692962014-05-05 18:13:44 -07002962}
2963
François Gaffie251c7f02018-11-07 10:41:08 +01002964void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002965{
2966 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002967 if (indexMin < 0 || indexMax < 0) {
2968 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2969 return;
2970 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002971 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002972
2973 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002974 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2975 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002976 continue;
2977 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002978 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002979 }
Eric Laurente552edb2014-03-10 17:42:56 -07002980}
2981
Eric Laurente0720872014-03-11 09:30:41 -07002982status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002983 int index,
2984 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002985{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002986 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002987 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2988 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2989 return NO_ERROR;
2990 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002991 ALOGV("%s: stream %s attributes=%s", __func__,
2992 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002993 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002994}
2995
Eric Laurente0720872014-03-11 09:30:41 -07002996status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002997 int *index,
2998 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002999{
François Gaffiec005e562018-11-06 15:04:49 +01003000 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3001 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003002 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003003 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003004 deviceTypes = mEngine->getOutputDevicesForStream(
3005 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003006 }
jiabin9a3361e2019-10-01 09:38:30 -07003007 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003008}
3009
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003010status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003011 int index,
3012 audio_devices_t device)
3013{
3014 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003015 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3016 if (group == VOLUME_GROUP_NONE) {
3017 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003018 return BAD_VALUE;
3019 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003020 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003021 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003022 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003023 VolumeSource vs = toVolumeSource(group);
3024 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3025
3026 status = setVolumeCurveIndex(index, device, curves);
3027 if (status != NO_ERROR) {
3028 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3029 return status;
3030 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003031
jiabin9a3361e2019-10-01 09:38:30 -07003032 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003033 auto curCurvAttrs = curves.getAttributes();
3034 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3035 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003036 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003037 } else if (!curves.getStreamTypes().empty()) {
3038 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003039 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003040 } else {
3041 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3042 return BAD_VALUE;
3043 }
jiabin9a3361e2019-10-01 09:38:30 -07003044 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3045 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003046
François Gaffiecfe17322018-11-07 13:41:29 +01003047 // update volume on all outputs and streams matching the following:
3048 // - The requested stream (or a stream matching for volume control) is active on the output
3049 // - The device (or devices) selected by the engine for this stream includes
3050 // the requested device
3051 // - For non default requested device, currently selected device on the output is either the
3052 // requested device or one of the devices selected by the engine for this stream
3053 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3054 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003055 for (size_t i = 0; i < mOutputs.size(); i++) {
3056 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003057 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003058
jiabin9a3361e2019-10-01 09:38:30 -07003059 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3060 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003061 }
François Gaffieed91f582020-01-31 10:35:37 +01003062 if (!(desc->isActive(vs) || isInCall())) {
3063 continue;
3064 }
3065 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3066 curDevices.find(device) == curDevices.end()) {
3067 continue;
3068 }
3069 bool applyVolume = false;
3070 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3071 curSrcDevices.insert(device);
3072 applyVolume = (curSrcDevices.find(
3073 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3074 } else {
3075 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3076 }
3077 if (!applyVolume) {
3078 continue; // next output
3079 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003080 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3081 // If a higher priority strategy is active, and the output is routed to a device with a
3082 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003083 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003084 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003085 // If the volume source is active with higher priority source, ensure at least Sw Muted
3086 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003087 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3088 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3089 false /*preferredDevice*/);
3090 if (activeClients.empty()) {
3091 continue;
3092 }
3093 bool isPreempted = false;
3094 bool isHigherPriority = productStrategy < strategy;
3095 for (const auto &client : activeClients) {
3096 if (isHigherPriority && (client->volumeSource() != vs)) {
3097 ALOGV("%s: Strategy=%d (\nrequester:\n"
3098 " group %d, volumeGroup=%d attributes=%s)\n"
3099 " higher priority source active:\n"
3100 " volumeGroup=%d attributes=%s) \n"
3101 " on output %zu, bailing out", __func__, productStrategy,
3102 group, group, toString(attributes).c_str(),
3103 client->volumeSource(), toString(client->attributes()).c_str(), i);
3104 applyVolume = false;
3105 isPreempted = true;
3106 break;
3107 }
3108 // However, continue for loop to ensure no higher prio clients running on output
3109 if (client->volumeSource() == vs) {
3110 applyVolume = true;
3111 }
3112 }
3113 if (isPreempted || applyVolume) {
3114 break;
3115 }
3116 }
3117 if (!applyVolume) {
3118 continue; // next output
3119 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003120 }
François Gaffieed91f582020-01-31 10:35:37 +01003121 //FIXME: workaround for truncated touch sounds
3122 // delayed volume change for system stream to be removed when the problem is
3123 // handled by system UI
3124 status_t volStatus = checkAndSetVolume(
3125 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003126 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003127 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3128 if (volStatus != NO_ERROR) {
3129 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003130 }
3131 }
François Gaffiecfe17322018-11-07 13:41:29 +01003132 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3133 return status;
3134}
3135
François Gaffieaaac0fd2018-11-22 17:56:39 +01003136status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003137 audio_devices_t device,
3138 IVolumeCurves &volumeCurves)
3139{
3140 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3141 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003142 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3143 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003144 (index > volumeCurves.getVolumeIndexMax())) {
3145 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3146 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3147 return BAD_VALUE;
3148 }
3149 if (!audio_is_output_device(device)) {
3150 return BAD_VALUE;
3151 }
3152
3153 // Force max volume if stream cannot be muted
3154 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3155
François Gaffieaaac0fd2018-11-22 17:56:39 +01003156 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003157 volumeCurves.addCurrentVolumeIndex(device, index);
3158 return NO_ERROR;
3159}
3160
3161status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3162 int &index,
3163 audio_devices_t device)
3164{
3165 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3166 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003167 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003168 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003169 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003170 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003171 }
jiabin9a3361e2019-10-01 09:38:30 -07003172 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003173}
3174
3175status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3176 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003177 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003178{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003179 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003180 return BAD_VALUE;
3181 }
jiabin9a3361e2019-10-01 09:38:30 -07003182 index = curves.getVolumeIndex(deviceTypes);
3183 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003184 return NO_ERROR;
3185}
3186
3187status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3188 int &index)
3189{
3190 index = getVolumeCurves(attr).getVolumeIndexMin();
3191 return NO_ERROR;
3192}
3193
3194status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3195 int &index)
3196{
3197 index = getVolumeCurves(attr).getVolumeIndexMax();
3198 return NO_ERROR;
3199}
3200
Eric Laurent36829f92017-04-07 19:04:42 -07003201audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003202{
3203 // select one output among several suitable for global effects.
3204 // The priority is as follows:
3205 // 1: An offloaded output. If the effect ends up not being offloadable,
3206 // AudioFlinger will invalidate the track and the offloaded output
3207 // will be closed causing the effect to be moved to a PCM output.
3208 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003209 // 3: The primary output
3210 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003211
François Gaffiec005e562018-11-06 15:04:49 +01003212 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3213 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003214 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003215
Eric Laurent36829f92017-04-07 19:04:42 -07003216 if (outputs.size() == 0) {
3217 return AUDIO_IO_HANDLE_NONE;
3218 }
Eric Laurente552edb2014-03-10 17:42:56 -07003219
Eric Laurent36829f92017-04-07 19:04:42 -07003220 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3221 bool activeOnly = true;
3222
3223 while (output == AUDIO_IO_HANDLE_NONE) {
3224 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3225 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3226 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3227
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003228 for (audio_io_handle_t output : outputs) {
3229 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003230 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003231 continue;
3232 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003233 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3234 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003235 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003236 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003237 }
3238 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003239 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003240 }
3241 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003242 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003243 }
3244 }
3245 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3246 output = outputOffloaded;
3247 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3248 output = outputDeepBuffer;
3249 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3250 output = outputPrimary;
3251 } else {
3252 output = outputs[0];
3253 }
3254 activeOnly = false;
3255 }
3256
3257 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003258 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003259 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3260 mMusicEffectOutput = output;
3261 }
3262
3263 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003264 return output;
3265}
3266
Eric Laurent36829f92017-04-07 19:04:42 -07003267audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3268{
3269 return selectOutputForMusicEffects();
3270}
3271
Eric Laurente0720872014-03-11 09:30:41 -07003272status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003273 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003274 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003275 int session,
3276 int id)
3277{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003278 if (session != AUDIO_SESSION_DEVICE) {
3279 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003280 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003281 index = mInputs.indexOfKey(io);
3282 if (index < 0) {
3283 ALOGW("registerEffect() unknown io %d", io);
3284 return INVALID_OPERATION;
3285 }
Eric Laurente552edb2014-03-10 17:42:56 -07003286 }
3287 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003288 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3289 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3290 || strategy == PRODUCT_STRATEGY_NONE));
3291 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003292}
3293
Eric Laurentc241b0d2018-11-28 09:08:49 -08003294status_t AudioPolicyManager::unregisterEffect(int id)
3295{
3296 if (mEffects.getEffect(id) == nullptr) {
3297 return INVALID_OPERATION;
3298 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003299 if (mEffects.isEffectEnabled(id)) {
3300 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3301 setEffectEnabled(id, false);
3302 }
3303 return mEffects.unregisterEffect(id);
3304}
3305
3306status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3307{
3308 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3309 if (effect == nullptr) {
3310 return INVALID_OPERATION;
3311 }
3312
3313 status_t status = mEffects.setEffectEnabled(id, enabled);
3314 if (status == NO_ERROR) {
3315 mInputs.trackEffectEnabled(effect, enabled);
3316 }
3317 return status;
3318}
3319
Eric Laurent6c796322019-04-09 14:13:17 -07003320
3321status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3322{
3323 mEffects.moveEffects(ids, io);
3324 return NO_ERROR;
3325}
3326
Eric Laurentc75307b2015-03-17 15:29:32 -07003327bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3328{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003329 auto vs = toVolumeSource(stream, false);
3330 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003331}
3332
3333bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3334{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003335 auto vs = toVolumeSource(stream, false);
3336 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003337}
3338
Eric Laurente0720872014-03-11 09:30:41 -07003339bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003340{
3341 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003342 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003343 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003344 return true;
3345 }
3346 }
3347 return false;
3348}
3349
Eric Laurent275e8e92014-11-30 15:14:47 -08003350// Register a list of custom mixes with their attributes and format.
3351// When a mix is registered, corresponding input and output profiles are
3352// added to the remote submix hw module. The profile contains only the
3353// parameters (sampling rate, format...) specified by the mix.
3354// The corresponding input remote submix device is also connected.
3355//
3356// When a remote submix device is connected, the address is checked to select the
3357// appropriate profile and the corresponding input or output stream is opened.
3358//
3359// When capture starts, getInputForAttr() will:
3360// - 1 look for a mix matching the address passed in attribtutes tags if any
3361// - 2 if none found, getDeviceForInputSource() will:
3362// - 2.1 look for a mix matching the attributes source
3363// - 2.2 if none found, default to device selection by policy rules
3364// At this time, the corresponding output remote submix device is also connected
3365// and active playback use cases can be transferred to this mix if needed when reconnecting
3366// after AudioTracks are invalidated
3367//
3368// When playback starts, getOutputForAttr() will:
3369// - 1 look for a mix matching the address passed in attribtutes tags if any
3370// - 2 if none found, look for a mix matching the attributes usage
3371// - 3 if none found, default to device and output selection by policy rules.
3372
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003373status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003374{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003375 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3376 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003377 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003378 sp<HwModule> rSubmixModule;
3379 // examine each mix's route type
3380 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003381 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003382 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3383 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3384 ALOGE("Unsupported Policy Mix %zu of %zu: "
3385 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3386 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003387 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003388 break;
3389 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003390 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3391 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003392 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003393 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3394 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003395 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003396 rSubmixModule = mHwModules.getModuleFromName(
3397 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3398 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003399 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003400 i);
3401 res = INVALID_OPERATION;
3402 break;
3403 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003404 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003405
Eric Laurent97ac8712018-07-27 18:59:02 -07003406 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003407 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003408 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003409 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003410 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3411 } else {
3412 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3413 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003414 }
François Gaffie036e1e92015-03-19 10:16:24 +01003415
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003416 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003417 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003418 res = INVALID_OPERATION;
3419 break;
3420 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003421 audio_config_t outputConfig = mix.mFormat;
3422 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003423 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3424 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003425 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3426 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003427 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003428 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003429 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003430 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003431
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003432 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003433 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3434 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3435 ALOGE("Failed to set remote submix device available, type %u, address %s",
3436 mix.mDeviceType, address.string());
3437 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003438 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003439 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3440 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003441 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003442 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003443 i, mixes.size(), type, address.string());
3444
3445 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3446 mix.mDeviceType, mix.mDeviceAddress,
3447 String8(), AUDIO_FORMAT_DEFAULT);
3448 if (device == nullptr) {
3449 res = INVALID_OPERATION;
3450 break;
3451 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003452
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003453 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003454 // First try to find an already opened output supporting the device
3455 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003456 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003457
Eric Laurentc529cf62020-04-17 18:19:10 -07003458 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003459 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003460 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3461 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003462 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003463 } else {
3464 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003465 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003466 }
3467 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003468 // If no output found, try to find a direct output profile supporting the device
3469 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3470 sp<HwModule> module = mHwModules[i];
3471 for (size_t j = 0;
3472 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3473 j++) {
3474 sp<IOProfile> profile = module->getOutputProfiles()[j];
3475 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3476 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3477 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3478 address.string());
3479 res = INVALID_OPERATION;
3480 } else {
3481 foundOutput = true;
3482 }
3483 }
3484 }
3485 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003486 if (res != NO_ERROR) {
3487 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003488 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003489 res = INVALID_OPERATION;
3490 break;
3491 } else if (!foundOutput) {
3492 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003493 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003494 res = INVALID_OPERATION;
3495 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003496 } else {
3497 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003498 }
Eric Laurentc722f302014-12-10 11:21:49 -08003499 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003500 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003501 if (res != NO_ERROR) {
3502 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003503 } else if (checkOutputs) {
3504 checkForDeviceAndOutputChanges();
3505 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003506 }
3507 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003508}
3509
3510status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3511{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003512 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003513 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003514 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003515 sp<HwModule> rSubmixModule;
3516 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003517 for (const auto& mix : mixes) {
3518 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003519
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003520 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003521 rSubmixModule = mHwModules.getModuleFromName(
3522 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3523 if (rSubmixModule == 0) {
3524 res = INVALID_OPERATION;
3525 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003526 }
3527 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003528
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003529 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003530
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003531 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003532 res = INVALID_OPERATION;
3533 continue;
3534 }
3535
Kevin Rocard04ed0462019-05-02 17:53:24 -07003536 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3537 if (getDeviceConnectionState(device, address.string()) ==
3538 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3539 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3540 address.string(), "remote-submix",
3541 AUDIO_FORMAT_DEFAULT);
3542 if (res != OK) {
3543 ALOGE("Error making RemoteSubmix device unavailable for mix "
3544 "with type %d, address %s", device, address.string());
3545 }
3546 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003547 }
jiabin5740f082019-08-19 15:08:30 -07003548 rSubmixModule->removeOutputProfile(address.c_str());
3549 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003550
Kevin Rocard153f92d2018-12-18 18:33:28 -08003551 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003552 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003553 res = INVALID_OPERATION;
3554 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003555 } else {
3556 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003557 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003558 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003559 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003560 if (res == NO_ERROR && checkOutputs) {
3561 checkForDeviceAndOutputChanges();
3562 updateCallAndOutputRouting();
3563 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003564 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003565}
3566
Mikhail Naganov100f0122018-11-29 11:22:16 -08003567void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3568{
3569 size_t i = 0;
3570 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3571 for (const auto& fmt : mManualSurroundFormats) {
3572 if (i++ != 0) dst->append(", ");
3573 std::string sfmt;
3574 FormatConverter::toString(fmt, sfmt);
3575 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3576 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3577 }
3578}
3579
Eric Laurentc529cf62020-04-17 18:19:10 -07003580// Returns true if all devices types match the predicate and are supported by one HW module
3581bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003582 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003583 std::function<bool(audio_devices_t)> predicate,
3584 const char *context) {
3585 for (size_t i = 0; i < devices.size(); i++) {
3586 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003587 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003588 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003589 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003590 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003591 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003592 return false;
3593 }
3594 }
3595 return true;
3596}
3597
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003598status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003599 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003600 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003601 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3602 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003603 }
3604 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003605 if (res != NO_ERROR) {
3606 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3607 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003608 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003609
3610 checkForDeviceAndOutputChanges();
3611 updateCallAndOutputRouting();
3612
3613 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003614}
3615
3616status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3617 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003618 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3619 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003620 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003621 __FUNCTION__, uid);
3622 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003623 }
3624
Eric Laurentc529cf62020-04-17 18:19:10 -07003625 checkForDeviceAndOutputChanges();
3626 updateCallAndOutputRouting();
3627
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003628 return res;
3629}
3630
Eric Laurent2517af32020-11-25 15:31:27 +01003631
jiabin0a488932020-08-07 17:32:40 -07003632status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3633 device_role_t role,
3634 const AudioDeviceTypeAddrVector &devices) {
3635 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3636 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003637
Eric Laurentc529cf62020-04-17 18:19:10 -07003638 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003639 return BAD_VALUE;
3640 }
jiabin0a488932020-08-07 17:32:40 -07003641 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003642 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003643 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3644 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003645 return status;
3646 }
3647
3648 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003649
3650 bool forceVolumeReeval = false;
3651 // FIXME: workaround for truncated touch sounds
3652 // to be removed when the problem is handled by system UI
3653 uint32_t delayMs = 0;
3654 if (strategy == mCommunnicationStrategy) {
3655 forceVolumeReeval = true;
3656 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3657 updateInputRouting();
3658 }
3659 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003660
3661 return NO_ERROR;
3662}
3663
3664void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3665{
3666 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003667 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003668 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003669 // Only apply special touch sound delay once
3670 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003671 }
3672 for (size_t i = 0; i < mOutputs.size(); i++) {
3673 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3674 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003675 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3676 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003677 // As done in setDeviceConnectionState, we could also fix default device issue by
3678 // preventing the force re-routing in case of default dev that distinguishes on address.
3679 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003680 bool forceRouting = !newDevices.isEmpty();
3681 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3682 true /*requiresMuteCheck*/,
3683 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003684 // Only apply special touch sound delay once
3685 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003686 }
3687 if (forceVolumeReeval && !newDevices.isEmpty()) {
3688 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3689 }
3690 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003691 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003692}
3693
Eric Laurent2517af32020-11-25 15:31:27 +01003694void AudioPolicyManager::updateInputRouting() {
3695 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303696 // Skip for hotword recording as the input device switch
3697 // is handled within sound trigger HAL
3698 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3699 continue;
3700 }
Eric Laurent2517af32020-11-25 15:31:27 +01003701 auto newDevice = getNewInputDevice(activeDesc);
3702 // Force new input selection if the new device can not be reached via current input
3703 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3704 setInputDevice(activeDesc->mIoHandle, newDevice);
3705 } else {
3706 closeInput(activeDesc->mIoHandle);
3707 }
3708 }
3709}
3710
jiabin0a488932020-08-07 17:32:40 -07003711status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3712 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003713{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003714 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003715
jiabin0a488932020-08-07 17:32:40 -07003716 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003717 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003718 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3719 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003720 return status;
3721 }
3722
3723 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003724
3725 bool forceVolumeReeval = false;
3726 // FIXME: workaround for truncated touch sounds
3727 // to be removed when the problem is handled by system UI
3728 uint32_t delayMs = 0;
3729 if (strategy == mCommunnicationStrategy) {
3730 forceVolumeReeval = true;
3731 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3732 updateInputRouting();
3733 }
3734 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003735
3736 return NO_ERROR;
3737}
3738
jiabin0a488932020-08-07 17:32:40 -07003739status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3740 device_role_t role,
3741 AudioDeviceTypeAddrVector &devices) {
3742 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003743}
3744
Jiabin Huang3b98d322020-09-03 17:54:16 +00003745status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3746 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3747 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3748 dumpAudioDeviceTypeAddrVector(devices).c_str());
3749
Mikhail Naganov55773032020-10-01 15:08:13 -07003750 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003751 return BAD_VALUE;
3752 }
3753 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3754 ALOGW_IF(status != NO_ERROR,
3755 "Engine could not set preferred devices %s for audio source %d role %d",
3756 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3757
3758 return status;
3759}
3760
3761status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3762 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3763 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3764 dumpAudioDeviceTypeAddrVector(devices).c_str());
3765
Mikhail Naganov55773032020-10-01 15:08:13 -07003766 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003767 return BAD_VALUE;
3768 }
3769 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3770 ALOGW_IF(status != NO_ERROR,
3771 "Engine could not add preferred devices %s for audio source %d role %d",
3772 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3773
Eric Laurent2517af32020-11-25 15:31:27 +01003774 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003775 return status;
3776}
3777
3778status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3779 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3780{
3781 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3782 dumpAudioDeviceTypeAddrVector(devices).c_str());
3783
Mikhail Naganov55773032020-10-01 15:08:13 -07003784 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003785 return BAD_VALUE;
3786 }
3787
3788 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3789 audioSource, role, devices);
3790 ALOGW_IF(status != NO_ERROR,
3791 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3792
Eric Laurent2517af32020-11-25 15:31:27 +01003793 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003794 return status;
3795}
3796
3797status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3798 device_role_t role) {
3799 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3800
3801 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3802 ALOGW_IF(status != NO_ERROR,
3803 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3804
Eric Laurent2517af32020-11-25 15:31:27 +01003805 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003806 return status;
3807}
3808
3809status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3810 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3811 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3812}
3813
Oscar Azucena90e77632019-11-27 17:12:28 -08003814status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003815 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003816 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003817 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3818 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003819 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003820 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3821 if (status != NO_ERROR) {
3822 ALOGE("%s() could not set device affinity for userId %d",
3823 __FUNCTION__, userId);
3824 return status;
3825 }
3826
3827 // reevaluate outputs for all devices
3828 checkForDeviceAndOutputChanges();
3829 updateCallAndOutputRouting();
3830
3831 return NO_ERROR;
3832}
3833
3834status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003835 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003836 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3837 if (status != NO_ERROR) {
3838 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3839 __FUNCTION__, userId);
3840 return status;
3841 }
3842
3843 // reevaluate outputs for all devices
3844 checkForDeviceAndOutputChanges();
3845 updateCallAndOutputRouting();
3846
3847 return NO_ERROR;
3848}
3849
Andy Hungc29d82b2018-10-05 12:23:17 -07003850void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003851{
Andy Hungc29d82b2018-10-05 12:23:17 -07003852 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003853 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003854 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003855 std::string stateLiteral;
3856 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003857 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003858 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3859 "communications", "media", "record", "dock", "system",
3860 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3861 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3862 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003863 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3864 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3865 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3866 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3867 dst->append(" (MANUAL: ");
3868 dumpManualSurroundFormats(dst);
3869 dst->append(")");
3870 }
3871 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003872 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003873 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3874 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003875 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003876 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003877
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003878 dst->append("\n");
3879 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3880 dst->append("\n");
3881 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003882 mHwModulesAll.dump(dst);
3883 mOutputs.dump(dst);
3884 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003885 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003886 mAudioPatches.dump(dst);
3887 mPolicyMixes.dump(dst);
3888 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003889
Kevin Rocardb99cc752019-03-21 20:52:24 -07003890 dst->appendFormat(" AllowedCapturePolicies:\n");
3891 for (auto& policy : mAllowedCapturePolicies) {
3892 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3893 }
3894
François Gaffiec005e562018-11-06 15:04:49 +01003895 dst->appendFormat("\nPolicy Engine dump:\n");
3896 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003897}
3898
3899status_t AudioPolicyManager::dump(int fd)
3900{
3901 String8 result;
3902 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003903 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003904 return NO_ERROR;
3905}
3906
Kevin Rocardb99cc752019-03-21 20:52:24 -07003907status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3908{
3909 mAllowedCapturePolicies[uid] = capturePolicy;
3910 return NO_ERROR;
3911}
3912
Eric Laurente552edb2014-03-10 17:42:56 -07003913// This function checks for the parameters which can be offloaded.
3914// This can be enhanced depending on the capability of the DSP and policy
3915// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003916audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003917{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003918 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003919 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003920 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003921 offloadInfo.format,
3922 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3923 offloadInfo.has_video);
3924
jiabin2b9d5a12021-12-10 01:06:29 +00003925 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003926 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003927 }
3928
3929 // See if there is a profile to support this.
3930 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003931 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003932 offloadInfo.sample_rate,
3933 offloadInfo.format,
3934 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003935 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3936 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003937 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3938 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3939 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003940 if (profile == nullptr) {
3941 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3942 }
3943 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3944 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3945 }
3946 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003947}
3948
Michael Chana94fbb22018-04-24 14:31:19 +10003949bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3950 const audio_attributes_t& attributes) {
3951 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003952 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003953 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3954 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003955 config.sample_rate,
3956 config.format,
3957 config.channel_mask,
3958 output_flags,
3959 true /* directOnly */);
3960 ALOGV("%s() profile %sfound with name: %s, "
3961 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3962 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003963 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003964 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003965
3966 // also try the MSD module if compatible profile not found
3967 if (profile == nullptr) {
3968 profile = getMsdProfileForOutput(outputDevices,
3969 config.sample_rate,
3970 config.format,
3971 config.channel_mask,
3972 output_flags,
3973 true /* directOnly */);
3974 ALOGV("%s() MSD profile %sfound with name: %s, "
3975 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3976 __FUNCTION__, profile != 0 ? "" : "NOT ",
3977 (profile != 0 ? profile->getTagName().c_str() : "null"),
3978 config.sample_rate, config.format, config.channel_mask, output_flags);
3979 }
3980 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003981}
3982
jiabin2b9d5a12021-12-10 01:06:29 +00003983bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3984 bool durationIgnored) {
3985 if (mMasterMono) {
3986 return false; // no offloading if mono is set.
3987 }
3988
3989 // Check if offload has been disabled
3990 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3991 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3992 return false;
3993 }
3994
3995 // Check if stream type is music, then only allow offload as of now.
3996 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3997 {
3998 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3999 return false;
4000 }
4001
4002 //TODO: enable audio offloading with video when ready
4003 const bool allowOffloadWithVideo =
4004 property_get_bool("audio.offload.video", false /* default_value */);
4005 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4006 ALOGV("%s: has_video == true, returning false", __func__);
4007 return false;
4008 }
4009
4010 //If duration is less than minimum value defined in property, return false
4011 const int min_duration_secs = property_get_int32(
4012 "audio.offload.min.duration.secs", -1 /* default_value */);
4013 if (!durationIgnored) {
4014 if (min_duration_secs >= 0) {
4015 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4016 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4017 __func__, min_duration_secs);
4018 return false;
4019 }
4020 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4021 ALOGV("%s: Offload denied by duration < default min(=%u)",
4022 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4023 return false;
4024 }
4025 }
4026
4027 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4028 // creating an offloaded track and tearing it down immediately after start when audioflinger
4029 // detects there is an active non offloadable effect.
4030 // FIXME: We should check the audio session here but we do not have it in this context.
4031 // This may prevent offloading in rare situations where effects are left active by apps
4032 // in the background.
4033 if (mEffects.isNonOffloadableEffectEnabled()) {
4034 return false;
4035 }
4036
4037 return true;
4038}
4039
4040audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4041 const audio_config_t *config) {
4042 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4043 offloadInfo.format = config->format;
4044 offloadInfo.sample_rate = config->sample_rate;
4045 offloadInfo.channel_mask = config->channel_mask;
4046 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4047 offloadInfo.has_video = false;
4048 offloadInfo.is_streaming = false;
4049 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4050
4051 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4052 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4053 audio_flags_to_audio_output_flags(attr->flags, &flags);
4054 // only retain flags that will drive compressed offload or passthrough
4055 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4056 if (offloadPossible) {
4057 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4058 }
4059 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4060
Dorin Drimusfae3c642022-03-17 18:36:30 +01004061 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004062 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004063 DeviceVector outputDevices = engineOutputDevices;
4064 // the MSD module checks for different conditions and output devices
4065 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4066 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4067 continue;
4068 }
4069 outputDevices = getMsdAudioOutDevices();
4070 }
jiabin2b9d5a12021-12-10 01:06:29 +00004071 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004072 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004073 config->sample_rate, nullptr /*updatedSamplingRate*/,
4074 config->format, nullptr /*updatedFormat*/,
4075 config->channel_mask, nullptr /*updatedChannelMask*/,
4076 flags)) {
4077 continue;
4078 }
4079 // reject profiles not corresponding to a device currently available
4080 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4081 continue;
4082 }
4083 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4084 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004085 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004086 != AUDIO_DIRECT_NOT_SUPPORTED) {
4087 // Already reports offload gapless supported. No need to report offload support.
4088 continue;
4089 }
4090 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4091 != AUDIO_OUTPUT_FLAG_NONE) {
4092 // If offload gapless is reported, no need to report offload support.
4093 directMode = (audio_direct_mode_t) ((directMode &
4094 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4095 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4096 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004097 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004098 }
4099 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004100 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004101 }
4102 }
4103 }
4104 return directMode;
4105}
4106
Dorin Drimusf2196d82022-01-03 12:11:18 +01004107status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4108 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004109 if (mEffects.isNonOffloadableEffectEnabled()) {
4110 return OK;
4111 }
jiabinf1c73972022-04-14 16:28:52 -07004112 DeviceVector devices;
4113 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004114 if (status != OK) {
4115 return status;
4116 }
4117 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4118 if (devices.empty()) {
4119 return OK; // no output devices for the attributes
4120 }
jiabinf1c73972022-04-14 16:28:52 -07004121 return getProfilesForDevices(devices, audioProfilesVector,
4122 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004123}
4124
Eric Laurent6a94d692014-05-20 11:18:06 -07004125status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4126 audio_port_type_t type,
4127 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004128 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004129 unsigned int *generation)
4130{
jiabin19cdba52020-11-24 11:28:58 -08004131 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4132 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004133 return BAD_VALUE;
4134 }
4135 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004136 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004137 *num_ports = 0;
4138 }
4139
4140 size_t portsWritten = 0;
4141 size_t portsMax = *num_ports;
4142 *num_ports = 0;
4143 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004144 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4145 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004146 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004147 for (const auto& dev : mAvailableOutputDevices) {
4148 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004149 continue;
4150 }
4151 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004152 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004153 }
4154 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004155 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004156 }
4157 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004158 for (const auto& dev : mAvailableInputDevices) {
4159 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004160 continue;
4161 }
4162 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004163 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004164 }
4165 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004166 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004167 }
4168 }
4169 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4170 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4171 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4172 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4173 }
4174 *num_ports += mInputs.size();
4175 }
4176 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004177 size_t numOutputs = 0;
4178 for (size_t i = 0; i < mOutputs.size(); i++) {
4179 if (!mOutputs[i]->isDuplicated()) {
4180 numOutputs++;
4181 if (portsWritten < portsMax) {
4182 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4183 }
4184 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004185 }
Eric Laurent84c70242014-06-23 08:46:27 -07004186 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004187 }
4188 }
4189 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004190 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004191 return NO_ERROR;
4192}
4193
jiabin19cdba52020-11-24 11:28:58 -08004194status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004195{
Eric Laurent99fcae42018-05-17 16:59:18 -07004196 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4197 return BAD_VALUE;
4198 }
4199 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4200 if (dev != 0) {
4201 dev->toAudioPort(port);
4202 return NO_ERROR;
4203 }
4204 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4205 if (dev != 0) {
4206 dev->toAudioPort(port);
4207 return NO_ERROR;
4208 }
4209 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4210 if (out != 0) {
4211 out->toAudioPort(port);
4212 return NO_ERROR;
4213 }
4214 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4215 if (in != 0) {
4216 in->toAudioPort(port);
4217 return NO_ERROR;
4218 }
4219 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004220}
4221
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004222status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4223 audio_patch_handle_t *handle,
4224 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004225{
François Gaffieafd4cea2019-11-18 15:50:22 +01004226 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004227 if (handle == NULL || patch == NULL) {
4228 return BAD_VALUE;
4229 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004230 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004231 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004232 return BAD_VALUE;
4233 }
4234 // only one source per audio patch supported for now
4235 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004236 return INVALID_OPERATION;
4237 }
Eric Laurent874c42872014-08-08 15:13:39 -07004238 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004239 return INVALID_OPERATION;
4240 }
Eric Laurent874c42872014-08-08 15:13:39 -07004241 for (size_t i = 0; i < patch->num_sinks; i++) {
4242 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4243 return INVALID_OPERATION;
4244 }
4245 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004246
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004247 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4248 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4249 if (srcDevice == nullptr || sinkDevice == nullptr) {
4250 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4251 return BAD_VALUE;
4252 }
4253 ALOGV("%s between source %s and sink %s", __func__,
4254 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4255 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4256 // Default attributes, default volume priority, not to infer with non raw audio patches.
4257 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4258 const struct audio_port_config *source = &patch->sources[0];
4259 sp<SourceClientDescriptor> sourceDesc =
4260 new InternalSourceClientDescriptor(
4261 portId, uid, attributes, *source, srcDevice, sinkDevice,
4262 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4263
4264 status_t status =
4265 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4266
4267 if (status != NO_ERROR) {
4268 return INVALID_OPERATION;
4269 }
4270 mAudioSources.add(portId, sourceDesc);
4271 return NO_ERROR;
4272}
4273
4274status_t AudioPolicyManager::connectAudioSourceToSink(
4275 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4276 const struct audio_patch *patch,
4277 audio_patch_handle_t &handle,
4278 uid_t uid, uint32_t delayMs)
4279{
4280 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4281 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4282 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4283 return INVALID_OPERATION;
4284 }
4285 sourceDesc->connect(handle, sinkDevice);
4286 if (isMsdPatch(handle)) {
4287 return NO_ERROR;
4288 }
4289 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4290 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4291 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4292 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4293 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4294 goto FailurePatchAdded;
4295 }
4296 status = swOutput->start();
4297 if (status != NO_ERROR) {
4298 goto FailureSourceAdded;
4299 }
4300 swOutput->addClient(sourceDesc);
4301 status = startSource(swOutput, sourceDesc, &delayMs);
4302 if (status != NO_ERROR) {
4303 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4304 goto FailureSourceActive;
4305 }
4306 if (delayMs != 0) {
4307 usleep(delayMs * 1000);
4308 }
4309 return NO_ERROR;
4310
4311FailureSourceActive:
4312 swOutput->stop();
4313 releaseOutput(sourceDesc->portId());
4314FailureSourceAdded:
4315 sourceDesc->setSwOutput(nullptr);
4316FailurePatchAdded:
4317 releaseAudioPatchInternal(handle);
4318 return INVALID_OPERATION;
4319}
4320
4321status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4322 audio_patch_handle_t *handle,
4323 uid_t uid, uint32_t delayMs,
4324 const sp<SourceClientDescriptor>& sourceDesc)
4325{
4326 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004327 sp<AudioPatch> patchDesc;
4328 ssize_t index = mAudioPatches.indexOfKey(*handle);
4329
François Gaffieafd4cea2019-11-18 15:50:22 +01004330 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4331 patch->sources[0].role,
4332 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004333#if LOG_NDEBUG == 0
4334 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004335 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4336 patch->sinks[i].role,
4337 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004338 }
4339#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004340
4341 if (index >= 0) {
4342 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004343 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4344 __func__, mUidCached, patchDesc->getUid(), uid);
4345 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004346 return INVALID_OPERATION;
4347 }
4348 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004349 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004350 }
4351
4352 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004353 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004354 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004355 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004356 return BAD_VALUE;
4357 }
Eric Laurent84c70242014-06-23 08:46:27 -07004358 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4359 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004360 if (patchDesc != 0) {
4361 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004362 ALOGV("%s source id differs for patch current id %d new id %d",
4363 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004364 return BAD_VALUE;
4365 }
4366 }
Eric Laurent874c42872014-08-08 15:13:39 -07004367 DeviceVector devices;
4368 for (size_t i = 0; i < patch->num_sinks; i++) {
4369 // Only support mix to devices connection
4370 // TODO add support for mix to mix connection
4371 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004372 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004373 return INVALID_OPERATION;
4374 }
4375 sp<DeviceDescriptor> devDesc =
4376 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4377 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004378 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004379 return BAD_VALUE;
4380 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004381
François Gaffie11d30102018-11-02 16:09:09 +01004382 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004383 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004384 NULL, // updatedSamplingRate
4385 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004386 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004387 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004388 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004389 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004390 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004391 return INVALID_OPERATION;
4392 }
4393 devices.add(devDesc);
4394 }
4395 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004396 return INVALID_OPERATION;
4397 }
Eric Laurent874c42872014-08-08 15:13:39 -07004398
Eric Laurent6a94d692014-05-20 11:18:06 -07004399 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004400 ALOGV("%s setting device %s on output %d",
4401 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004402 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004403 index = mAudioPatches.indexOfKey(*handle);
4404 if (index >= 0) {
4405 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004406 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004407 }
4408 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004409 patchDesc->setUid(uid);
4410 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004411 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004412 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004413 return INVALID_OPERATION;
4414 }
4415 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4416 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4417 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004418 // only one sink supported when connecting an input device to a mix
4419 if (patch->num_sinks > 1) {
4420 return INVALID_OPERATION;
4421 }
François Gaffie53615e22015-03-19 09:24:12 +01004422 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004423 if (inputDesc == NULL) {
4424 return BAD_VALUE;
4425 }
4426 if (patchDesc != 0) {
4427 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4428 return BAD_VALUE;
4429 }
4430 }
François Gaffie11d30102018-11-02 16:09:09 +01004431 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004432 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004433 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004434 return BAD_VALUE;
4435 }
4436
François Gaffie11d30102018-11-02 16:09:09 +01004437 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004438 patch->sinks[0].sample_rate,
4439 NULL, /*updatedSampleRate*/
4440 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004441 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004442 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004443 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004444 // FIXME for the parameter type,
4445 // and the NONE
4446 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004447 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004448 return INVALID_OPERATION;
4449 }
4450 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004451 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004452 device->toString().c_str(), inputDesc->mIoHandle);
4453 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004454 index = mAudioPatches.indexOfKey(*handle);
4455 if (index >= 0) {
4456 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004457 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004458 }
4459 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004460 patchDesc->setUid(uid);
4461 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004462 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004463 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004464 return INVALID_OPERATION;
4465 }
4466 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4467 // device to device connection
4468 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004469 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004470 return BAD_VALUE;
4471 }
4472 }
François Gaffie11d30102018-11-02 16:09:09 +01004473 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004474 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004475 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004476 return BAD_VALUE;
4477 }
Eric Laurent874c42872014-08-08 15:13:39 -07004478
Eric Laurent6a94d692014-05-20 11:18:06 -07004479 //update source and sink with our own data as the data passed in the patch may
4480 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004481 PatchBuilder patchBuilder;
4482 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004483
4484 // if first sink is to MSD, establish single MSD patch
4485 if (getMsdAudioOutDevices().contains(
4486 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4487 ALOGV("%s patching to MSD", __FUNCTION__);
4488 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4489 goto installPatch;
4490 }
4491
François Gaffieafd4cea2019-11-18 15:50:22 +01004492 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4493 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004494
Eric Laurent874c42872014-08-08 15:13:39 -07004495 for (size_t i = 0; i < patch->num_sinks; i++) {
4496 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004497 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004498 return INVALID_OPERATION;
4499 }
François Gaffie11d30102018-11-02 16:09:09 +01004500 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004501 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004502 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004503 return BAD_VALUE;
4504 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004505 audio_port_config sinkPortConfig = {};
4506 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4507 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004508
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004509 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4510 // volume management purpose (tracking activity)
4511 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4512 // in config XML to reach the sink so that is can be declared as available.
4513 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02004514 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004515 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004516 // take care of dynamic routing for SwOutput selection,
4517 audio_attributes_t attributes = sourceDesc->attributes();
4518 audio_stream_type_t stream = sourceDesc->stream();
4519 audio_attributes_t resultAttr;
4520 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4521 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02004522 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
4523 config.channel_mask =
4524 (audio_channel_mask_get_representation(sourceMask)
4525 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
4526 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004527 config.format = sourceDesc->config().format;
4528 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4529 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4530 bool isRequestedDeviceForExclusiveUse = false;
4531 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004532 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004533 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4534 &stream, sourceDesc->uid(), &config, &flags,
4535 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004536 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004537 if (output == AUDIO_IO_HANDLE_NONE) {
4538 ALOGV("%s no output for device %s",
4539 __FUNCTION__, sinkDevice->toString().c_str());
4540 return INVALID_OPERATION;
4541 }
4542 outputDesc = mOutputs.valueFor(output);
4543 if (outputDesc->isDuplicated()) {
4544 ALOGE("%s output is duplicated", __func__);
4545 return INVALID_OPERATION;
4546 }
François Gaffie7e39df22022-04-26 12:48:49 +02004547 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4548 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004549 } else {
4550 // Same for "raw patches" aka created from createAudioPatch API
4551 SortedVector<audio_io_handle_t> outputs =
4552 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4553 // if the sink device is reachable via an opened output stream, request to
4554 // go via this output stream by adding a second source to the patch
4555 // description
4556 output = selectOutput(outputs);
4557 if (output == AUDIO_IO_HANDLE_NONE) {
4558 ALOGE("%s no output available for internal patch sink", __func__);
4559 return INVALID_OPERATION;
4560 }
4561 outputDesc = mOutputs.valueFor(output);
4562 if (outputDesc->isDuplicated()) {
4563 ALOGV("%s output for device %s is duplicated",
4564 __func__, sinkDevice->toString().c_str());
4565 return INVALID_OPERATION;
4566 }
François Gaffie7e39df22022-04-26 12:48:49 +02004567 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004568 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004569 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004570 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004571 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004572 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004573 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4574 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004575 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4576 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004577 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004578 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004579 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004580 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004581 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004582 return INVALID_OPERATION;
4583 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004584 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004585 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004586 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004587 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004588 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02004589 srcMixPortConfig.ext.mix.usecase.stream =
4590 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004591 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4592 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004593 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004594 }
Eric Laurent83b88082014-06-20 18:31:16 -07004595 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004596 }
4597 // TODO: check from routing capabilities in config file and other conflicting patches
4598
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004599installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004600 status_t status = installPatch(
4601 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004602 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004603 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004604 return INVALID_OPERATION;
4605 }
4606 } else {
4607 return BAD_VALUE;
4608 }
4609 } else {
4610 return BAD_VALUE;
4611 }
4612 return NO_ERROR;
4613}
4614
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004615status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004616{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004617 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004618 ssize_t index = mAudioPatches.indexOfKey(handle);
4619
4620 if (index < 0) {
4621 return BAD_VALUE;
4622 }
4623 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004624 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4625 __func__, mUidCached, patchDesc->getUid(), uid);
4626 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004627 return INVALID_OPERATION;
4628 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004629 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4630 for (size_t i = 0; i < mAudioSources.size(); i++) {
4631 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4632 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4633 portId = sourceDesc->portId();
4634 break;
4635 }
4636 }
4637 return portId != AUDIO_PORT_HANDLE_NONE ?
4638 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004639}
Eric Laurent6a94d692014-05-20 11:18:06 -07004640
François Gaffieafd4cea2019-11-18 15:50:22 +01004641status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004642 uint32_t delayMs,
4643 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004644{
4645 ALOGV("%s patch %d", __func__, handle);
4646 if (mAudioPatches.indexOfKey(handle) < 0) {
4647 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4648 return BAD_VALUE;
4649 }
4650 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004651 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004652 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004653 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004654 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004655 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004656 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004657 return BAD_VALUE;
4658 }
4659
François Gaffie11d30102018-11-02 16:09:09 +01004660 setOutputDevices(outputDesc,
4661 getNewOutputDevices(outputDesc, true /*fromCache*/),
4662 true,
4663 0,
4664 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004665 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4666 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004667 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004668 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004669 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004670 return BAD_VALUE;
4671 }
4672 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004673 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004674 true,
4675 NULL);
4676 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004677 status_t status =
4678 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4679 ALOGV("%s patch panel returned %d patchHandle %d",
4680 __func__, status, patchDesc->getAfHandle());
4681 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004682 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004683 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004684 // SW or HW Bridge
4685 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4686 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004687 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004688 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4689 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4690 outputDesc = sourceDesc->swOutput().promote();
4691 }
4692 if (outputDesc == nullptr) {
4693 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4694 // releaseOutput has already called closeOutput in case of direct output
4695 return NO_ERROR;
4696 }
François Gaffie7e39df22022-04-26 12:48:49 +02004697 patchHandle = outputDesc->getPatchHandle();
4698 // When a Sw bridge is released, the mixer used by this bridge will release its
4699 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4700 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4701 // updating hal patch handle (prevent leaks).
4702 // While using a HwBridge, force reconsidering device only if not reusing an existing
4703 // output and no more activity on output (will force to close).
4704 bool force = sourceDesc->useSwBridge() ||
4705 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4706 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4707 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4708 // Reconsider device only for cases:
4709 // 1 / Active Output
4710 // 2 / Inactive Output previously hosting HwBridge
4711 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4712 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4713 sourceDesc->canCloseOutput();
4714 setOutputDevices(outputDesc,
4715 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4716 outputDesc->devices(),
4717 force,
4718 0,
4719 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004720 } else {
4721 return BAD_VALUE;
4722 }
4723 } else {
4724 return BAD_VALUE;
4725 }
4726 return NO_ERROR;
4727}
4728
4729status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4730 struct audio_patch *patches,
4731 unsigned int *generation)
4732{
François Gaffie53615e22015-03-19 09:24:12 +01004733 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004734 return BAD_VALUE;
4735 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004736 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004737 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004738}
4739
Eric Laurente1715a42014-05-20 11:30:42 -07004740status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004741{
Eric Laurente1715a42014-05-20 11:30:42 -07004742 ALOGV("setAudioPortConfig()");
4743
4744 if (config == NULL) {
4745 return BAD_VALUE;
4746 }
4747 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4748 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004749 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4750 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004751 }
4752
Eric Laurenta121f902014-06-03 13:32:54 -07004753 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004754 if (config->type == AUDIO_PORT_TYPE_MIX) {
4755 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004756 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004757 if (outputDesc == NULL) {
4758 return BAD_VALUE;
4759 }
Eric Laurent84c70242014-06-23 08:46:27 -07004760 ALOG_ASSERT(!outputDesc->isDuplicated(),
4761 "setAudioPortConfig() called on duplicated output %d",
4762 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004763 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004764 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004765 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004766 if (inputDesc == NULL) {
4767 return BAD_VALUE;
4768 }
Eric Laurenta121f902014-06-03 13:32:54 -07004769 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004770 } else {
4771 return BAD_VALUE;
4772 }
4773 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4774 sp<DeviceDescriptor> deviceDesc;
4775 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4776 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4777 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4778 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4779 } else {
4780 return BAD_VALUE;
4781 }
4782 if (deviceDesc == NULL) {
4783 return BAD_VALUE;
4784 }
Eric Laurenta121f902014-06-03 13:32:54 -07004785 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004786 } else {
4787 return BAD_VALUE;
4788 }
4789
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004790 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004791 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4792 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004793 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004794 audioPortConfig->toAudioPortConfig(&newConfig, config);
4795 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004796 }
Eric Laurenta121f902014-06-03 13:32:54 -07004797 if (status != NO_ERROR) {
4798 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004799 }
Eric Laurente1715a42014-05-20 11:30:42 -07004800
4801 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004802}
4803
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004804void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4805{
Eric Laurentd60560a2015-04-10 11:31:20 -07004806 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004807 clearAudioPatches(uid);
4808 clearSessionRoutes(uid);
4809}
4810
Eric Laurent6a94d692014-05-20 11:18:06 -07004811void AudioPolicyManager::clearAudioPatches(uid_t uid)
4812{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004813 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004814 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004815 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004816 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004817 }
4818 }
4819}
4820
François Gaffiec005e562018-11-06 15:04:49 +01004821void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004822{
François Gaffiec005e562018-11-06 15:04:49 +01004823 // Take the first attributes following the product strategy as it is used to retrieve the routed
4824 // device. All attributes wihin a strategy follows the same "routing strategy"
4825 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4826 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004827 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004828 for (size_t j = 0; j < mOutputs.size(); j++) {
4829 if (mOutputs.keyAt(j) == ouptutToSkip) {
4830 continue;
4831 }
4832 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004833 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004834 continue;
4835 }
4836 // If the default device for this strategy is on another output mix,
4837 // invalidate all tracks in this strategy to force re connection.
4838 // Otherwise select new device on the output mix.
4839 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004840 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4841 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004842 }
4843 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004844 setOutputDevices(
4845 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004846 }
4847 }
4848}
4849
4850void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4851{
4852 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004853 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004854 for (size_t i = 0; i < mOutputs.size(); i++) {
4855 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004856 for (const auto& client : outputDesc->getClientIterable()) {
4857 if (client->hasPreferredDevice() && client->uid() == uid) {
4858 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004859 auto clientStrategy = client->strategy();
4860 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4861 end(affectedStrategies)) {
4862 continue;
4863 }
4864 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004865 }
4866 }
4867 }
4868 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004869 for (const auto& strategy : affectedStrategies) {
4870 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004871 }
4872
4873 // remove input routes associated with this uid
4874 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004875 for (size_t i = 0; i < mInputs.size(); i++) {
4876 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004877 for (const auto& client : inputDesc->getClientIterable()) {
4878 if (client->hasPreferredDevice() && client->uid() == uid) {
4879 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4880 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004881 }
4882 }
4883 }
4884 // reroute inputs if necessary
4885 SortedVector<audio_io_handle_t> inputsToClose;
4886 for (size_t i = 0; i < mInputs.size(); i++) {
4887 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004888 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004889 inputsToClose.add(inputDesc->mIoHandle);
4890 }
4891 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004892 for (const auto& input : inputsToClose) {
4893 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004894 }
4895}
4896
Eric Laurentd60560a2015-04-10 11:31:20 -07004897void AudioPolicyManager::clearAudioSources(uid_t uid)
4898{
4899 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004900 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4901 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004902 stopAudioSource(mAudioSources.keyAt(i));
4903 }
4904 }
4905}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004906
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004907status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4908 audio_io_handle_t *ioHandle,
4909 audio_devices_t *device)
4910{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004911 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4912 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004913 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004914 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004915
François Gaffiedf372692015-03-19 10:43:27 +01004916 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004917}
4918
Eric Laurentd60560a2015-04-10 11:31:20 -07004919status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004920 const audio_attributes_t *attributes,
4921 audio_port_handle_t *portId,
4922 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004923{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004924 ALOGV("%s", __FUNCTION__);
4925 *portId = AUDIO_PORT_HANDLE_NONE;
4926
4927 if (source == NULL || attributes == NULL || portId == NULL) {
4928 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4929 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004930 return BAD_VALUE;
4931 }
4932
Eric Laurentd60560a2015-04-10 11:31:20 -07004933 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4934 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004935 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4936 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004937 return INVALID_OPERATION;
4938 }
4939
François Gaffie11d30102018-11-02 16:09:09 +01004940 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004941 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004942 String8(source->ext.device.address),
4943 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004944 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004945 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004946 return BAD_VALUE;
4947 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004948
jiabin4ef93452019-09-10 14:29:54 -07004949 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004950
François Gaffieaaac0fd2018-11-22 17:56:39 +01004951 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004952 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004953 mEngine->getStreamTypeForAttributes(*attributes),
4954 mEngine->getProductStrategyForAttributes(*attributes),
4955 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004956
4957 status_t status = connectAudioSource(sourceDesc);
4958 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004959 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004960 }
4961 return status;
4962}
4963
Francois Gaffie601801d2021-06-22 13:27:39 +02004964sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4965 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4966{
4967 ALOGV("%s", __FUNCTION__);
4968 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4969
4970 status_t status = startAudioSource(source, attributes, &portId, uid);
4971 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4972 return mAudioSources.valueFor(portId);
4973}
4974
4975
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004976status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004977{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004978 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004979
4980 // make sure we only have one patch per source.
4981 disconnectAudioSource(sourceDesc);
4982
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004983 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004984 // May the device (dynamic) have been disconnected/reconnected, id has changed.
4985 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
4986 sourceDesc->srcDevice()->type(),
4987 String8(sourceDesc->srcDevice()->address().c_str()),
4988 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01004989 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02004990 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01004991 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01004992 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02004993 if (!mAvailableOutputDevices.contains(sinkDevice)) {
4994 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
4995 return INVALID_OPERATION;
4996 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004997 PatchBuilder patchBuilder;
4998 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
4999 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005000
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005001 return connectAudioSourceToSink(
5002 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005003}
5004
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005005status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005006{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005007 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5008 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005009 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005010 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005011 return BAD_VALUE;
5012 }
5013 status_t status = disconnectAudioSource(sourceDesc);
5014
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005015 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005016 return status;
5017}
5018
Andy Hung2ddee192015-12-18 17:34:44 -08005019status_t AudioPolicyManager::setMasterMono(bool mono)
5020{
5021 if (mMasterMono == mono) {
5022 return NO_ERROR;
5023 }
5024 mMasterMono = mono;
5025 // if enabling mono we close all offloaded devices, which will invalidate the
5026 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5027 // for recreating the new AudioTrack as non-offloaded PCM.
5028 //
5029 // If disabling mono, we leave all tracks as is: we don't know which clients
5030 // and tracks are able to be recreated as offloaded. The next "song" should
5031 // play back offloaded.
5032 if (mMasterMono) {
5033 Vector<audio_io_handle_t> offloaded;
5034 for (size_t i = 0; i < mOutputs.size(); ++i) {
5035 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5036 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5037 offloaded.push(desc->mIoHandle);
5038 }
5039 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005040 for (const auto& handle : offloaded) {
5041 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005042 }
5043 }
5044 // update master mono for all remaining outputs
5045 for (size_t i = 0; i < mOutputs.size(); ++i) {
5046 updateMono(mOutputs.keyAt(i));
5047 }
5048 return NO_ERROR;
5049}
5050
5051status_t AudioPolicyManager::getMasterMono(bool *mono)
5052{
5053 *mono = mMasterMono;
5054 return NO_ERROR;
5055}
5056
Eric Laurentac9cef52017-06-09 15:46:26 -07005057float AudioPolicyManager::getStreamVolumeDB(
5058 audio_stream_type_t stream, int index, audio_devices_t device)
5059{
jiabin9a3361e2019-10-01 09:38:30 -07005060 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005061}
5062
jiabin81772902018-04-02 17:52:27 -07005063status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5064 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005065 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005066{
Kriti Dang6537def2021-03-02 13:46:59 +01005067 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5068 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005069 return BAD_VALUE;
5070 }
Kriti Dang6537def2021-03-02 13:46:59 +01005071 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5072 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005073
5074 size_t formatsWritten = 0;
5075 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005076
Kriti Dang6537def2021-03-02 13:46:59 +01005077 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005078 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5079 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005080 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005081 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005082 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005083 bool formatEnabled = true;
5084 switch (forceUse) {
5085 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005086 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005087 break;
5088 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5089 formatEnabled = false;
5090 break;
5091 default: // AUTO or ALWAYS => true
5092 break;
jiabin81772902018-04-02 17:52:27 -07005093 }
5094 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5095 }
jiabin81772902018-04-02 17:52:27 -07005096 }
5097 return NO_ERROR;
5098}
5099
Kriti Dang6537def2021-03-02 13:46:59 +01005100status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5101 audio_format_t *surroundFormats) {
5102 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5103 return BAD_VALUE;
5104 }
5105 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5106 __func__, *numSurroundFormats, surroundFormats);
5107
5108 size_t formatsWritten = 0;
5109 size_t formatsMax = *numSurroundFormats;
5110 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5111
5112 // Return formats from all device profiles that have already been resolved by
5113 // checkOutputsForDevice().
5114 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5115 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5116 audio_devices_t deviceType = device->type();
5117 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5118 // returns formats reported by HDMI devices.
5119 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5120 continue;
5121 }
5122 // Formats reported by sink devices
5123 std::unordered_set<audio_format_t> formatset;
5124 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5125 formatset.insert(it->second.begin(), it->second.end());
5126 }
5127
5128 // Formats hard-coded in the in policy configuration file (if any).
5129 FormatVector encodedFormats = device->encodedFormats();
5130 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5131 // Filter the formats which are supported by the vendor hardware.
5132 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5133 if (mConfig.getSurroundFormats().count(*it) != 0) {
5134 formats.insert(*it);
5135 } else {
5136 for (const auto& pair : mConfig.getSurroundFormats()) {
5137 if (pair.second.count(*it) != 0) {
5138 formats.insert(pair.first);
5139 break;
5140 }
5141 }
5142 }
5143 }
5144 }
5145 *numSurroundFormats = formats.size();
5146 for (const auto& format: formats) {
5147 if (formatsWritten < formatsMax) {
5148 surroundFormats[formatsWritten++] = format;
5149 }
5150 }
5151 return NO_ERROR;
5152}
5153
jiabin81772902018-04-02 17:52:27 -07005154status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5155{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005156 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005157 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5158 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005159 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005160 return BAD_VALUE;
5161 }
5162
Mikhail Naganov100f0122018-11-29 11:22:16 -08005163 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5164 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005165 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005166 return INVALID_OPERATION;
5167 }
5168
Mikhail Naganov100f0122018-11-29 11:22:16 -08005169 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005170 return NO_ERROR;
5171 }
5172
Mikhail Naganov100f0122018-11-29 11:22:16 -08005173 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005174 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005175 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005176 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005177 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005178 }
5179 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005180 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005181 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005182 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005183 }
5184 }
5185
5186 sp<SwAudioOutputDescriptor> outputDesc;
5187 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005188 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5189 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005190 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5191 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005192 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005193 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005194 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5195 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5196 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005197 name.c_str(),
5198 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005199 if (status != NO_ERROR) {
5200 continue;
5201 }
5202 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5203 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5204 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005205 name.c_str(),
5206 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005207 profileUpdated |= (status == NO_ERROR);
5208 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005209 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005210 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005211 AUDIO_DEVICE_IN_HDMI);
5212 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5213 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005214 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005215 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005216 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5217 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5218 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005219 name.c_str(),
5220 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005221 if (status != NO_ERROR) {
5222 continue;
5223 }
5224 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5225 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5226 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005227 name.c_str(),
5228 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005229 profileUpdated |= (status == NO_ERROR);
5230 }
5231
jiabin81772902018-04-02 17:52:27 -07005232 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005233 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005234 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005235 }
5236
5237 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5238}
5239
Eric Laurent5ada82e2019-08-29 17:53:54 -07005240void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005241{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005242 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005243 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005244 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005245 }
5246}
5247
jiabin6012f912018-11-02 17:06:30 -07005248bool AudioPolicyManager::isHapticPlaybackSupported()
5249{
5250 for (const auto& hwModule : mHwModules) {
5251 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5252 for (const auto &outProfile : outputProfiles) {
5253 struct audio_port audioPort;
5254 outProfile->toAudioPort(&audioPort);
5255 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5256 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5257 return true;
5258 }
5259 }
5260 }
5261 }
5262 return false;
5263}
5264
Carter Hsu325a8eb2022-01-19 19:56:51 +08005265bool AudioPolicyManager::isUltrasoundSupported()
5266{
5267 bool hasUltrasoundOutput = false;
5268 bool hasUltrasoundInput = false;
5269 for (const auto& hwModule : mHwModules) {
5270 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5271 if (!hasUltrasoundOutput) {
5272 for (const auto &outProfile : outputProfiles) {
5273 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5274 hasUltrasoundOutput = true;
5275 break;
5276 }
5277 }
5278 }
5279
5280 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5281 if (!hasUltrasoundInput) {
5282 for (const auto &inputProfile : inputProfiles) {
5283 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5284 hasUltrasoundInput = true;
5285 break;
5286 }
5287 }
5288 }
5289
5290 if (hasUltrasoundOutput && hasUltrasoundInput)
5291 return true;
5292 }
5293 return false;
5294}
5295
Eric Laurent8340e672019-11-06 11:01:08 -08005296bool AudioPolicyManager::isCallScreenModeSupported()
5297{
5298 return getConfig().isCallScreenModeSupported();
5299}
5300
5301
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005302status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005303{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005304 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005305 if (!sourceDesc->isConnected()) {
5306 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5307 return NO_ERROR;
5308 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005309 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5310 if (swOutput != 0) {
5311 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005312 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005313 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005314 }
jiabinbce0c1d2020-10-05 11:20:18 -07005315 if (releaseOutput(sourceDesc->portId())) {
5316 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5317 // no need to release audio patch here but just return NO_ERROR.
5318 return NO_ERROR;
5319 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005320 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005321 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005322 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005323 // close Hwoutput and remove from mHwOutputs
5324 } else {
5325 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5326 }
5327 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005328 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005329 sourceDesc->disconnect();
5330 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005331}
5332
François Gaffiec005e562018-11-06 15:04:49 +01005333sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5334 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005335{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005336 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005337 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005338 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005339 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005340 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5341 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005342 source = sourceDesc;
5343 break;
5344 }
5345 }
5346 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005347}
5348
Eric Laurentb4f42a92022-01-17 17:37:31 +01005349bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005350 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005351 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005352{
5353 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5354 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005355 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005356 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005357 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5358 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5359 return false;
5360 }
5361 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5362 return false;
5363 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005364 }
5365
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005366 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005367 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005368 if (profile == nullptr) {
5369 return false;
5370 }
5371
5372 // The caller can have the audio config criteria ignored by either passing a null ptr or
5373 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005374 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005375 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005376
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005377 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005378 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005379 return false;
5380 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005381 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005382 return true;
5383}
5384
5385void AudioPolicyManager::checkVirtualizerClientRoutes() {
5386 std::set<audio_stream_type_t> streamsToInvalidate;
5387 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005388 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5389 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005390 audio_attributes_t attr = client->attributes();
5391 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5392 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5393 audio_config_base_t clientConfig = client->config();
5394 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005395 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005396 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005397 streamsToInvalidate.insert(client->stream());
5398 }
5399 }
5400 }
5401
5402 for (audio_stream_type_t stream : streamsToInvalidate) {
5403 mpClientInterface->invalidateStream(stream);
5404 }
5405}
5406
Eric Laurente191d1b2022-04-15 11:59:25 +02005407
5408bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5409 const sp<SwAudioOutputDescriptor>& outputDesc) {
5410 if (outputDesc->isDuplicated()) {
5411 return false;
5412 }
5413 DeviceVector devices = outputDesc->supportedDevices();
5414 for (size_t i = 0; i < mOutputs.size(); i++) {
5415 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5416 if (desc == outputDesc || desc->isDuplicated()) {
5417 continue;
5418 }
5419 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5420 if (!sharedDevices.isEmpty()
5421 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5422 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5423 return false;
5424 }
5425 }
5426 return true;
5427}
5428
5429
Eric Laurentfa0f6742021-08-17 18:39:44 +02005430status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005431 const audio_attributes_t *attr,
5432 audio_io_handle_t *output) {
5433 *output = AUDIO_IO_HANDLE_NONE;
5434
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005435 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5436 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5437 audio_config_t *configPtr = nullptr;
5438 audio_config_t config;
5439 if (mixerConfig != nullptr) {
5440 config = audio_config_initializer(mixerConfig);
5441 configPtr = &config;
5442 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005443 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005444 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005445 return BAD_VALUE;
5446 }
5447
5448 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005449 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005450 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005451 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005452 return BAD_VALUE;
5453 }
5454
Eric Laurente191d1b2022-04-15 11:59:25 +02005455 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005456 for (size_t i = 0; i < mOutputs.size(); i++) {
5457 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005458 if (!desc->isDuplicated()
5459 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5460 spatializerOutputs.push_back(desc);
5461 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005462 }
5463 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005464 mSpatializerOutput.clear();
5465 bool outputsChanged = false;
5466 for (const auto& desc : spatializerOutputs) {
5467 if (desc->mProfile == profile
5468 && (configPtr == nullptr
5469 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5470 mSpatializerOutput = desc;
5471 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5472 } else {
5473 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5474 " and devices %s", __func__, desc->mIoHandle,
5475 configPtr != nullptr ? configPtr->channel_mask : 0,
5476 devices.toString().c_str());
5477 closeOutput(desc->mIoHandle);
5478 outputsChanged = true;
5479 }
Eric Laurent39095982021-08-24 18:29:27 +02005480 }
5481
Eric Laurente191d1b2022-04-15 11:59:25 +02005482 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005483 sp<SwAudioOutputDescriptor> desc =
5484 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005485 if (desc != nullptr) {
5486 mSpatializerOutput = desc;
5487 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005488 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005489 }
5490
5491 checkVirtualizerClientRoutes();
5492
Eric Laurente191d1b2022-04-15 11:59:25 +02005493 if (outputsChanged) {
5494 mPreviousOutputs = mOutputs;
5495 mpClientInterface->onAudioPortListUpdate();
5496 }
5497
5498 if (mSpatializerOutput == nullptr) {
5499 ALOGV("%s could not open spatializer output with requested config", __func__);
5500 return BAD_VALUE;
5501 }
Eric Laurent39095982021-08-24 18:29:27 +02005502 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005503 ALOGV("%s returning new spatializer output %d", __func__, *output);
5504 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005505}
5506
Eric Laurentfa0f6742021-08-17 18:39:44 +02005507status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5508 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005509 return INVALID_OPERATION;
5510 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005511 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005512 return BAD_VALUE;
5513 }
Eric Laurent39095982021-08-24 18:29:27 +02005514
Eric Laurente191d1b2022-04-15 11:59:25 +02005515 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5516 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5517 closeOutput(mSpatializerOutput->mIoHandle);
5518 //from now on mSpatializerOutput is null
5519 checkVirtualizerClientRoutes();
5520 }
Eric Laurent39095982021-08-24 18:29:27 +02005521
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005522 return NO_ERROR;
5523}
5524
Eric Laurente552edb2014-03-10 17:42:56 -07005525// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005526// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005527// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005528uint32_t AudioPolicyManager::nextAudioPortGeneration()
5529{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005530 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005531}
5532
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005533static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005534 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5535 !audioPolicyXmlConfigFile.empty()) {
5536 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5537 if (ret == NO_ERROR) {
5538 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005539 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005540 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005541 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005542 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005543}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005544
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005545AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5546 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005547 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005548 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005549 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005550 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005551 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005552 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005553 mAudioPortGeneration(1),
5554 mBeaconMuteRefCount(0),
5555 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005556 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005557 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005558 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005559 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005560{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005561}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005562
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005563AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5564 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5565{
5566 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005567}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005568
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005569void AudioPolicyManager::loadConfig() {
5570 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005571 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005572 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005573 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005574}
5575
5576status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005577 {
5578 auto engLib = EngineLibrary::load(
5579 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5580 if (!engLib) {
5581 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5582 return NO_INIT;
5583 }
5584 mEngine = engLib->createEngine();
5585 if (mEngine == nullptr) {
5586 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5587 return NO_INIT;
5588 }
François Gaffie2110e042015-03-24 08:41:51 +01005589 }
5590 mEngine->setObserver(this);
5591 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005592 if (status != NO_ERROR) {
5593 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5594 return status;
5595 }
François Gaffie2110e042015-03-24 08:41:51 +01005596
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005597 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005598 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5599 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5600
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005601 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005602 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005603 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005604
Eric Laurent3a4311c2014-03-17 12:00:47 -07005605 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005606 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5607 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5608 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005609 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005610 }
jiabin9ff780e2018-03-19 18:19:52 -07005611 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005612 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005613 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005614 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005615 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005616 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005617 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005618 }
5619 }
5620 }
Eric Laurente552edb2014-03-10 17:42:56 -07005621
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005622 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005623
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005624 // Silence ALOGV statements
5625 property_set("log.tag." LOG_TAG, "D");
5626
Eric Laurente552edb2014-03-10 17:42:56 -07005627 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005628 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005629}
5630
Eric Laurente0720872014-03-11 09:30:41 -07005631AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005632{
Eric Laurente552edb2014-03-10 17:42:56 -07005633 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005634 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005635 }
5636 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005637 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005638 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005639 mAvailableOutputDevices.clear();
5640 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005641 mOutputs.clear();
5642 mInputs.clear();
5643 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005644 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005645 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005646}
5647
Eric Laurente0720872014-03-11 09:30:41 -07005648status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005649{
Eric Laurent87ffa392015-05-22 10:32:38 -07005650 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005651}
5652
Eric Laurente552edb2014-03-10 17:42:56 -07005653// ---
5654
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005655void AudioPolicyManager::onNewAudioModulesAvailable()
5656{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005657 DeviceVector newDevices;
5658 onNewAudioModulesAvailableInt(&newDevices);
5659 if (!newDevices.empty()) {
5660 nextAudioPortGeneration();
5661 mpClientInterface->onAudioPortListUpdate();
5662 }
5663}
5664
5665void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5666{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005667 for (const auto& hwModule : mHwModulesAll) {
5668 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5669 continue;
5670 }
5671 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5672 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5673 ALOGW("could not open HW module %s", hwModule->getName());
5674 continue;
5675 }
5676 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005677 // open all output streams needed to access attached devices.
5678 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005679 // This also validates mAvailableOutputDevices list
5680 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5681 if (!outProfile->canOpenNewIo()) {
5682 ALOGE("Invalid Output profile max open count %u for profile %s",
5683 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5684 continue;
5685 }
5686 if (!outProfile->hasSupportedDevices()) {
5687 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5688 continue;
5689 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005690 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5691 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005692 mTtsOutputAvailable = true;
5693 }
5694
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005695 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5696 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5697 sp<DeviceDescriptor> supportedDevice = 0;
5698 if (supportedDevices.contains(mDefaultOutputDevice)) {
5699 supportedDevice = mDefaultOutputDevice;
5700 } else {
5701 // choose first device present in profile's SupportedDevices also part of
5702 // mAvailableOutputDevices.
5703 if (availProfileDevices.isEmpty()) {
5704 continue;
5705 }
5706 supportedDevice = availProfileDevices.itemAt(0);
5707 }
5708 if (!mOutputDevicesAll.contains(supportedDevice)) {
5709 continue;
5710 }
5711 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5712 mpClientInterface);
5713 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005714 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5715 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005716 AUDIO_STREAM_DEFAULT,
5717 AUDIO_OUTPUT_FLAG_NONE, &output);
5718 if (status != NO_ERROR) {
5719 ALOGW("Cannot open output stream for devices %s on hw module %s",
5720 supportedDevice->toString().c_str(), hwModule->getName());
5721 continue;
5722 }
5723 for (const auto &device : availProfileDevices) {
5724 // give a valid ID to an attached device once confirmed it is reachable
5725 if (!device->isAttached()) {
5726 device->attach(hwModule);
5727 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005728 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005729 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005730 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5731 }
5732 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005733 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005734 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5735 mPrimaryOutput = outputDesc;
5736 }
Eric Laurent39095982021-08-24 18:29:27 +02005737 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005738 outputDesc->close();
5739 } else {
5740 addOutput(output, outputDesc);
5741 setOutputDevices(outputDesc,
5742 DeviceVector(supportedDevice),
5743 true,
5744 0,
5745 NULL);
5746 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005747 }
5748 // open input streams needed to access attached devices to validate
5749 // mAvailableInputDevices list
5750 for (const auto& inProfile : hwModule->getInputProfiles()) {
5751 if (!inProfile->canOpenNewIo()) {
5752 ALOGE("Invalid Input profile max open count %u for profile %s",
5753 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5754 continue;
5755 }
5756 if (!inProfile->hasSupportedDevices()) {
5757 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5758 continue;
5759 }
5760 // chose first device present in profile's SupportedDevices also part of
5761 // available input devices
5762 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5763 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5764 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005765 ALOGV("%s: Input device list is empty! for profile %s",
5766 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005767 continue;
5768 }
5769 sp<AudioInputDescriptor> inputDesc =
5770 new AudioInputDescriptor(inProfile, mpClientInterface);
5771
5772 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5773 status_t status = inputDesc->open(nullptr,
5774 availProfileDevices.itemAt(0),
5775 AUDIO_SOURCE_MIC,
5776 AUDIO_INPUT_FLAG_NONE,
5777 &input);
5778 if (status != NO_ERROR) {
5779 ALOGW("Cannot open input stream for device %s on hw module %s",
5780 availProfileDevices.toString().c_str(),
5781 hwModule->getName());
5782 continue;
5783 }
5784 for (const auto &device : availProfileDevices) {
5785 // give a valid ID to an attached device once confirmed it is reachable
5786 if (!device->isAttached()) {
5787 device->attach(hwModule);
5788 device->importAudioPortAndPickAudioProfile(inProfile, true);
5789 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005790 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005791 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5792 }
5793 }
5794 inputDesc->close();
5795 }
5796 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005797
5798 // Check if spatializer outputs can be closed until used.
5799 // mOutputs vector never contains duplicated outputs at this point.
5800 std::vector<audio_io_handle_t> outputsClosed;
5801 for (size_t i = 0; i < mOutputs.size(); i++) {
5802 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5803 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5804 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5805 outputsClosed.push_back(desc->mIoHandle);
5806 desc->close();
5807 }
5808 }
5809 for (auto output : outputsClosed) {
5810 removeOutput(output);
5811 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005812}
5813
Eric Laurent98e38192018-02-15 18:31:53 -08005814void AudioPolicyManager::addOutput(audio_io_handle_t output,
5815 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005816{
Eric Laurent1c333e22014-05-20 10:48:17 -07005817 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005818 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005819 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005820 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005821 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005822}
5823
François Gaffie53615e22015-03-19 09:24:12 +01005824void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5825{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005826 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5827 ALOGV("%s: removing primary output", __func__);
5828 mPrimaryOutput = nullptr;
5829 }
François Gaffie53615e22015-03-19 09:24:12 +01005830 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005831 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005832}
5833
Eric Laurent98e38192018-02-15 18:31:53 -08005834void AudioPolicyManager::addInput(audio_io_handle_t input,
5835 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005836{
Eric Laurent1c333e22014-05-20 10:48:17 -07005837 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005838 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005839}
Eric Laurente552edb2014-03-10 17:42:56 -07005840
François Gaffie11d30102018-11-02 16:09:09 +01005841status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005842 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005843 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005844{
François Gaffie11d30102018-11-02 16:09:09 +01005845 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005846 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005847 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005848
François Gaffie11d30102018-11-02 16:09:09 +01005849 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005850 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005851 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005852 }
Eric Laurente552edb2014-03-10 17:42:56 -07005853
Eric Laurent3b73df72014-03-11 09:06:29 -07005854 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005855 // first call getAudioPort to get the supported attributes from the HAL
5856 struct audio_port_v7 port = {};
5857 device->toAudioPort(&port);
5858 status_t status = mpClientInterface->getAudioPort(&port);
5859 if (status == NO_ERROR) {
5860 device->importAudioPort(port);
5861 }
5862
5863 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005864 for (size_t i = 0; i < mOutputs.size(); i++) {
5865 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005866 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005867 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005868 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5869 mOutputs.keyAt(i), device->toString().c_str());
5870 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005871 }
5872 }
5873 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005874 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005875 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005876 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5877 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005878 if (profile->supportsDevice(device)) {
5879 profiles.add(profile);
5880 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5881 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005882 }
5883 }
5884 }
5885
Eric Laurent7b279bb2015-12-14 10:18:23 -08005886 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005887
Eric Laurente552edb2014-03-10 17:42:56 -07005888 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005889 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005890 return BAD_VALUE;
5891 }
5892
5893 // open outputs for matching profiles if needed. Direct outputs are also opened to
5894 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5895 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005896 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005897
5898 // nothing to do if one output is already opened for this profile
5899 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005900 for (j = 0; j < outputs.size(); j++) {
5901 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005902 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005903 // matching profile: save the sample rates, format and channel masks supported
5904 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005905 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005906 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005907 }
Eric Laurente552edb2014-03-10 17:42:56 -07005908 break;
5909 }
5910 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005911 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005912 continue;
5913 }
5914
Eric Laurent3974e3b2017-12-07 17:58:43 -08005915 if (!profile->canOpenNewIo()) {
5916 ALOGW("Max Output number %u already opened for this profile %s",
5917 profile->maxOpenCount, profile->getTagName().c_str());
5918 continue;
5919 }
5920
Eric Laurent83efe1c2017-07-09 16:51:08 -07005921 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005922 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005923 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5924 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005925 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005926 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005927 profiles.removeAt(profile_index);
5928 profile_index--;
5929 } else {
5930 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005931 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005932 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005933 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5934 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005935 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005936 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005937
François Gaffie11d30102018-11-02 16:09:09 +01005938 if (device_distinguishes_on_address(deviceType)) {
5939 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5940 device->toString().c_str());
5941 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5942 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005943 }
Eric Laurente552edb2014-03-10 17:42:56 -07005944 ALOGV("checkOutputsForDevice(): adding output %d", output);
5945 }
5946 }
5947
5948 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005949 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005950 return BAD_VALUE;
5951 }
Eric Laurentd4692962014-05-05 18:13:44 -07005952 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005953 // check if one opened output is not needed any more after disconnecting one device
5954 for (size_t i = 0; i < mOutputs.size(); i++) {
5955 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005956 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005957 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005958 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005959 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005960 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005961 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005962 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5963 mOutputs.keyAt(i));
5964 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005965 }
Eric Laurente552edb2014-03-10 17:42:56 -07005966 }
5967 }
Eric Laurentd4692962014-05-05 18:13:44 -07005968 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005969 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005970 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5971 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005972 if (!profile->supportsDevice(device)) {
5973 continue;
5974 }
5975 ALOGV("checkOutputsForDevice(): "
5976 "clearing direct output profile %zu on module %s",
5977 j, hwModule->getName());
5978 profile->clearAudioProfiles();
5979 if (!profile->hasDynamicAudioProfile()) {
5980 continue;
5981 }
5982 // When a device is disconnected, if there is an IOProfile that contains dynamic
5983 // profiles and supports the disconnected device, call getAudioPort to repopulate
5984 // the capabilities of the devices that is supported by the IOProfile.
5985 for (const auto& supportedDevice : profile->getSupportedDevices()) {
5986 if (supportedDevice == device ||
5987 !mAvailableOutputDevices.contains(supportedDevice)) {
5988 continue;
5989 }
5990 struct audio_port_v7 port;
5991 supportedDevice->toAudioPort(&port);
5992 status_t status = mpClientInterface->getAudioPort(&port);
5993 if (status == NO_ERROR) {
5994 supportedDevice->importAudioPort(port);
5995 }
Eric Laurente552edb2014-03-10 17:42:56 -07005996 }
5997 }
5998 }
5999 }
6000 return NO_ERROR;
6001}
6002
François Gaffie11d30102018-11-02 16:09:09 +01006003status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006004 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006005{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006006 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006007
François Gaffie11d30102018-11-02 16:09:09 +01006008 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006009 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006010 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006011 }
6012
Eric Laurentd4692962014-05-05 18:13:44 -07006013 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006014 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006015 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006016 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006017 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006018 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006019 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006020 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006021
François Gaffie11d30102018-11-02 16:09:09 +01006022 if (profile->supportsDevice(device)) {
6023 profiles.add(profile);
6024 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6025 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006026 }
6027 }
6028 }
6029
Eric Laurent0dd51852019-04-19 18:18:58 -07006030 if (profiles.isEmpty()) {
6031 ALOGW("%s: No input profile available for device %s",
6032 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006033 return BAD_VALUE;
6034 }
6035
6036 // open inputs for matching profiles if needed. Direct inputs are also opened to
6037 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6038 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6039
Eric Laurent1c333e22014-05-20 10:48:17 -07006040 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006041
Eric Laurentd4692962014-05-05 18:13:44 -07006042 // nothing to do if one input is already opened for this profile
6043 size_t input_index;
6044 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6045 desc = mInputs.valueAt(input_index);
6046 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006047 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006048 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006049 }
Eric Laurentd4692962014-05-05 18:13:44 -07006050 break;
6051 }
6052 }
6053 if (input_index != mInputs.size()) {
6054 continue;
6055 }
6056
Eric Laurent3974e3b2017-12-07 17:58:43 -08006057 if (!profile->canOpenNewIo()) {
6058 ALOGW("Max Input number %u already opened for this profile %s",
6059 profile->maxOpenCount, profile->getTagName().c_str());
6060 continue;
6061 }
6062
Eric Laurentfe231122017-11-17 17:48:06 -08006063 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006064 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006065 status_t status = desc->open(nullptr,
6066 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006067 AUDIO_SOURCE_MIC,
6068 AUDIO_INPUT_FLAG_NONE,
6069 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006070
Eric Laurentcf2c0212014-07-25 16:20:43 -07006071 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006072 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006073 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006074 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006075 mpClientInterface->setParameters(input, String8(param));
6076 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006077 }
François Gaffie11d30102018-11-02 16:09:09 +01006078 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006079 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006080 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006081 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006082 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006083 }
6084
Eric Laurent0dd51852019-04-19 18:18:58 -07006085 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006086 addInput(input, desc);
6087 }
6088 } // endif input != 0
6089
Eric Laurentcf2c0212014-07-25 16:20:43 -07006090 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006091 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006092 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006093 profiles.removeAt(profile_index);
6094 profile_index--;
6095 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006096 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006097 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006098 }
Eric Laurentd4692962014-05-05 18:13:44 -07006099 ALOGV("checkInputsForDevice(): adding input %d", input);
6100 }
6101 } // end scan profiles
6102
6103 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006104 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006105 return BAD_VALUE;
6106 }
6107 } else {
6108 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006109 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006110 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006111 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006112 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006113 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006114 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006115 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006116 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6117 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006118 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006119 }
6120 }
6121 }
6122 } // end disconnect
6123
6124 return NO_ERROR;
6125}
6126
6127
Eric Laurente0720872014-03-11 09:30:41 -07006128void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006129{
6130 ALOGV("closeOutput(%d)", output);
6131
François Gaffie1c878552018-11-22 16:53:21 +01006132 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6133 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006134 ALOGW("closeOutput() unknown output %d", output);
6135 return;
6136 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006137 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006138 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006139
Eric Laurente552edb2014-03-10 17:42:56 -07006140 // look for duplicated outputs connected to the output being removed.
6141 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006142 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6143 if (dupOutput->isDuplicated() &&
6144 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6145 sp<SwAudioOutputDescriptor> remainingOutput =
6146 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006147 // As all active tracks on duplicated output will be deleted,
6148 // and as they were also referenced on the other output, the reference
6149 // count for their stream type must be adjusted accordingly on
6150 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006151 const bool wasActive = remainingOutput->isActive();
6152 // Note: no-op on the closing output where all clients has already been set inactive
6153 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006154 // stop() will be a no op if the output is still active but is needed in case all
6155 // active streams refcounts where cleared above
6156 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006157 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006158 }
Eric Laurente552edb2014-03-10 17:42:56 -07006159 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6160 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6161
6162 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006163 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006164 }
6165 }
6166
Eric Laurent05b90f82014-08-27 15:32:29 -07006167 nextAudioPortGeneration();
6168
François Gaffie1c878552018-11-22 16:53:21 +01006169 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006170 if (index >= 0) {
6171 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006172 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6173 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006174 mAudioPatches.removeItemsAt(index);
6175 mpClientInterface->onAudioPatchListUpdate();
6176 }
6177
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006178 if (closingOutputWasActive) {
6179 closingOutput->stop();
6180 }
François Gaffie1c878552018-11-22 16:53:21 +01006181 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006182
François Gaffie53615e22015-03-19 09:24:12 +01006183 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006184 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006185 if (closingOutput == mSpatializerOutput) {
6186 mSpatializerOutput.clear();
6187 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006188
6189 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6190 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006191 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006192 bool directOutputOpen = false;
6193 for (size_t i = 0; i < mOutputs.size(); i++) {
6194 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6195 directOutputOpen = true;
6196 break;
6197 }
6198 }
6199 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006200 ALOGV("no direct outputs open, reset MSD patches");
6201 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6202 // how output devices for patching are resolved. Avoid by caching and reusing the
6203 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6204 // devices to patch to. This may be complicated by the fact that devices may become
6205 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006206 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006207 }
6208 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006209}
6210
6211void AudioPolicyManager::closeInput(audio_io_handle_t input)
6212{
6213 ALOGV("closeInput(%d)", input);
6214
6215 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6216 if (inputDesc == NULL) {
6217 ALOGW("closeInput() unknown input %d", input);
6218 return;
6219 }
6220
Eric Laurent6a94d692014-05-20 11:18:06 -07006221 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006222
François Gaffie11d30102018-11-02 16:09:09 +01006223 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006224 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006225 if (index >= 0) {
6226 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006227 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6228 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006229 mAudioPatches.removeItemsAt(index);
6230 mpClientInterface->onAudioPatchListUpdate();
6231 }
6232
Eric Laurentfe231122017-11-17 17:48:06 -08006233 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006234 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006235
François Gaffie11d30102018-11-02 16:09:09 +01006236 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6237 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006238 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006239 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006240 }
Eric Laurente552edb2014-03-10 17:42:56 -07006241}
6242
François Gaffie11d30102018-11-02 16:09:09 +01006243SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6244 const DeviceVector &devices,
6245 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006246{
6247 SortedVector<audio_io_handle_t> outputs;
6248
François Gaffie11d30102018-11-02 16:09:09 +01006249 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006250 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006251 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006252 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006253 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006254 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006255 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006256 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006257 outputs.add(openOutputs.keyAt(i));
6258 }
6259 }
6260 return outputs;
6261}
6262
Mikhail Naganov37977152018-07-11 15:54:44 -07006263void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6264{
6265 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6266 // output is suspended before any tracks are moved to it
6267 checkA2dpSuspend();
6268 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006269 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006270 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006271 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006272 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006273 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6274 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6275 // configuration changes will ultimately be rerouted correctly. We can still avoid
6276 // unnecessary rerouting by caching and reusing the arguments to
6277 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6278 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006279 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006280 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006281 // an event that changed routing likely occurred, inform upper layers
6282 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006283}
6284
François Gaffiec005e562018-11-06 15:04:49 +01006285bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6286 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006287{
François Gaffiec005e562018-11-06 15:04:49 +01006288 return mEngine->getProductStrategyForAttributes(lAttr) ==
6289 mEngine->getProductStrategyForAttributes(rAttr);
6290}
6291
Francois Gaffieff1eb522020-05-06 18:37:04 +02006292void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6293{
6294 for (size_t i = 0; i < mAudioSources.size(); i++) {
6295 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6296 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006297 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006298 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006299 connectAudioSource(sourceDesc);
6300 }
6301 }
6302}
6303
6304void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6305{
6306 for (size_t i = 0; i < mAudioSources.size(); i++) {
6307 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6308 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6309 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6310 disconnectAudioSource(sourceDesc);
6311 }
6312 }
6313}
6314
François Gaffiec005e562018-11-06 15:04:49 +01006315void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6316{
6317 auto psId = mEngine->getProductStrategyForAttributes(attr);
6318
6319 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6320 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006321
François Gaffie11d30102018-11-02 16:09:09 +01006322 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6323 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006324
Eric Laurentc209fe42020-06-05 18:11:23 -07006325 uint32_t maxLatency = 0;
Eric Laurent56ed8842022-11-15 16:04:41 +01006326 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006327 // take into account dynamic audio policies related changes: if a client is now associated
6328 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006329 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006330 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6331 if (desc->isDuplicated()) {
6332 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006333 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006334 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6335 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6336 continue;
6337 }
6338 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006339 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006340 client->uid(), client->session(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006341 if (status != OK) {
6342 continue;
6343 }
yucliuf4de36d2020-09-14 14:57:56 -07006344 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006345 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006346 maxLatency = desc->latency();
6347 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006348 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006349 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006350 }
6351 }
6352
Eric Laurent56ed8842022-11-15 16:04:41 +01006353 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006354 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6355 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006356 for (audio_io_handle_t srcOut : srcOutputs) {
6357 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006358 if (desc == nullptr) continue;
6359
6360 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006361 maxLatency = desc->latency();
6362 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006363
Eric Laurent56ed8842022-11-15 16:04:41 +01006364 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006365 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006366 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006367 // a client on a non direct outputs has necessarily a linear PCM format
6368 // so we can call selectOutput() safely
6369 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6370 client->flags(),
6371 client->config().format,
6372 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006373 client->config().sample_rate,
6374 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006375 if (newOutput != srcOut) {
6376 invalidate = true;
6377 break;
6378 }
6379 } else {
6380 sp<IOProfile> profile = getProfileForOutput(newDevices,
6381 client->config().sample_rate,
6382 client->config().format,
6383 client->config().channel_mask,
6384 client->flags(),
6385 true /* directOnly */);
6386 if (profile != desc->mProfile) {
6387 invalidate = true;
6388 break;
6389 }
6390 }
6391 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006392 // mute strategy while moving tracks from one output to another
6393 if (invalidate) {
6394 invalidatedOutputs.push_back(desc);
6395 if (desc->isStrategyActive(psId)) {
6396 setStrategyMute(psId, true, desc);
6397 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6398 newDevices.types());
6399 }
Eric Laurente552edb2014-03-10 17:42:56 -07006400 }
François Gaffiec005e562018-11-06 15:04:49 +01006401 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006402 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006403 connectAudioSource(source);
6404 }
Eric Laurente552edb2014-03-10 17:42:56 -07006405 }
6406
Eric Laurent56ed8842022-11-15 16:04:41 +01006407 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6408 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6409 std::to_string(srcOutputs[0]).c_str(),
6410 std::to_string(dstOutputs[0]).c_str());
6411
François Gaffiec005e562018-11-06 15:04:49 +01006412 // Move effects associated to this stream from previous output to new output
6413 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006414 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006415 }
François Gaffiec005e562018-11-06 15:04:49 +01006416 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006417 if (!invalidatedOutputs.empty()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006418 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6419 mpClientInterface->invalidateStream(stream);
6420 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006421 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006422 desc->setTracksInvalidatedStatusByStrategy(psId);
6423 }
Eric Laurente552edb2014-03-10 17:42:56 -07006424 }
6425 }
6426}
6427
Eric Laurente0720872014-03-11 09:30:41 -07006428void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006429{
François Gaffiec005e562018-11-06 15:04:49 +01006430 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6431 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6432 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006433 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006434 }
Eric Laurente552edb2014-03-10 17:42:56 -07006435}
6436
Kevin Rocard153f92d2018-12-18 18:33:28 -08006437void AudioPolicyManager::checkSecondaryOutputs() {
6438 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006439 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006440 for (size_t i = 0; i < mOutputs.size(); i++) {
6441 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6442 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006443 sp<AudioPolicyMix> primaryMix;
6444 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006445 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006446 client->uid(), client->session(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006447 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6448 for (auto &secondaryMix : secondaryMixes) {
6449 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6450 if (outputDesc != nullptr &&
6451 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6452 secondaryDescs.push_back(outputDesc);
6453 }
6454 }
6455
jiabin10a03f12021-05-07 23:46:28 +00006456 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006457 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006458 } else if (!std::equal(
6459 client->getSecondaryOutputs().begin(),
6460 client->getSecondaryOutputs().end(),
6461 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006462 if (!audio_is_linear_pcm(client->config().format)) {
6463 // If the format is not PCM, the tracks should be invalidated to get correct
6464 // behavior when the secondary output is changed.
6465 streamsToInvalidate.insert(client->stream());
6466 } else {
6467 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6468 std::vector<audio_io_handle_t> secondaryOutputIds;
6469 for (const auto &secondaryDesc: secondaryDescs) {
6470 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6471 weakSecondaryDescs.push_back(secondaryDesc);
6472 }
6473 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6474 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006475 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006476 }
6477 }
6478 }
jiabin10a03f12021-05-07 23:46:28 +00006479 if (!trackSecondaryOutputs.empty()) {
6480 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6481 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006482 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006483 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006484 mpClientInterface->invalidateStream(stream);
6485 }
6486}
6487
Eric Laurent2517af32020-11-25 15:31:27 +01006488bool AudioPolicyManager::isScoRequestedForComm() const {
6489 AudioDeviceTypeAddrVector devices;
6490 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6491 for (const auto &device : devices) {
6492 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6493 return true;
6494 }
6495 }
6496 return false;
6497}
6498
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006499bool AudioPolicyManager::isHearingAidUsedForComm() const {
6500 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6501 true /*fromCache*/);
6502 for (const auto &device : devices) {
6503 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6504 return true;
6505 }
6506 }
6507 return false;
6508}
6509
6510
Eric Laurente0720872014-03-11 09:30:41 -07006511void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006512{
François Gaffie53615e22015-03-19 09:24:12 +01006513 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006514 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006515 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006516 return;
6517 }
6518
Eric Laurent3a4311c2014-03-17 12:00:47 -07006519 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006520 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6521 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006522 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006523
6524 // if suspended, restore A2DP output if:
6525 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006526 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006527 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006528 //
Eric Laurentf732e072016-08-03 19:30:28 -07006529 // if not suspended, suspend A2DP output if:
6530 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006531 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006532 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006533 //
6534 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006535 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006536 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006537 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006538 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006539
6540 mpClientInterface->restoreOutput(a2dpOutput);
6541 mA2dpSuspended = false;
6542 }
6543 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006544 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006545 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006546 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006547 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006548
6549 mpClientInterface->suspendOutput(a2dpOutput);
6550 mA2dpSuspended = true;
6551 }
6552 }
6553}
6554
François Gaffie11d30102018-11-02 16:09:09 +01006555DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6556 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006557{
François Gaffie11d30102018-11-02 16:09:09 +01006558 DeviceVector devices;
6559
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006560 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006561 if (index >= 0) {
6562 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006563 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006564 ALOGV("%s device %s forced by patch %d", __func__,
6565 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6566 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006567 }
6568 }
6569
Dean Wheatley514b4312020-06-17 21:45:00 +10006570 // Do not retrieve engine device for outputs through MSD
6571 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6572 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6573 return outputDesc->devices();
6574 }
6575
Eric Laurent97ac8712018-07-27 18:59:02 -07006576 // Honor explicit routing requests only if no client using default routing is active on this
6577 // input: a specific app can not force routing for other apps by setting a preferred device.
6578 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006579 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006580 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006581 if (device != nullptr) {
6582 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006583 }
6584
François Gaffiea807ef92018-11-05 10:44:33 +01006585 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6586 // of setForceUse / Default Bus device here
6587 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6588 if (device != nullptr) {
6589 return DeviceVector(device);
6590 }
6591
François Gaffiec005e562018-11-06 15:04:49 +01006592 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6593 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6594 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306595 auto hasStreamActive = [&](auto stream) {
6596 return hasStream(streams, stream) && isStreamActive(stream, 0);
6597 };
Eric Laurent484e9272018-06-07 17:29:23 -07006598
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306599 auto doGetOutputDevicesForVoice = [&]() {
6600 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006601 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306602 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006603 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6604 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306605 };
6606
6607 // With low-latency playing on speaker, music on WFD, when the first low-latency
6608 // output is stopped, getNewOutputDevices checks for a product strategy
6609 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006610 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306611 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6612 // stream is associated to the output descriptor.
6613 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6614 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6615 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6616 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006617 // Retrieval of devices for voice DL is done on primary output profile, cannot
6618 // check the route (would force modifying configuration file for this profile)
6619 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6620 break;
6621 }
Eric Laurente552edb2014-03-10 17:42:56 -07006622 }
François Gaffiec005e562018-11-06 15:04:49 +01006623 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006624 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006625}
6626
François Gaffie11d30102018-11-02 16:09:09 +01006627sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6628 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006629{
François Gaffie11d30102018-11-02 16:09:09 +01006630 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006631
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006632 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006633 if (index >= 0) {
6634 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006635 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006636 ALOGV("getNewInputDevice() device %s forced by patch %d",
6637 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6638 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006639 }
6640 }
6641
Eric Laurent97ac8712018-07-27 18:59:02 -07006642 // Honor explicit routing requests only if no client using default routing is active on this
6643 // input: a specific app can not force routing for other apps by setting a preferred device.
6644 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006645 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6646 if (device != nullptr) {
6647 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006648 }
6649
Eric Laurentdc95a252018-04-12 12:46:56 -07006650 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006651 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006652 audio_attributes_t attributes;
6653 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006654 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006655 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6656 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006657 attributes = topClient->attributes();
6658 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006659 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006660 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006661 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6662 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006663 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006664 }
6665
Francois Gaffie716e1432019-01-14 16:58:59 +01006666 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6667 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006668 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006669 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02006670 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006671 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006672
Eric Laurente552edb2014-03-10 17:42:56 -07006673 return device;
6674}
6675
Eric Laurent794fde22016-03-11 09:50:45 -08006676bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6677 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006678 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006679}
6680
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006681status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006682 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006683 if (devices == nullptr) {
6684 return BAD_VALUE;
6685 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006686
Andy Hung6d23c0f2022-02-16 09:37:15 -08006687 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07006688 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
6689 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08006690 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006691 for (const auto& device : curDevices) {
6692 devices->push_back(device->getDeviceTypeAddr());
6693 }
6694 return NO_ERROR;
6695}
6696
Eric Laurente0720872014-03-11 09:30:41 -07006697void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006698 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006699 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006700 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006701 updateDevicesAndOutputs();
6702 break;
6703 default:
6704 break;
6705 }
6706}
6707
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006708uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006709
6710 // skip beacon mute management if a dedicated TTS output is available
6711 if (mTtsOutputAvailable) {
6712 return 0;
6713 }
6714
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006715 switch(event) {
6716 case STARTING_OUTPUT:
6717 mBeaconMuteRefCount++;
6718 break;
6719 case STOPPING_OUTPUT:
6720 if (mBeaconMuteRefCount > 0) {
6721 mBeaconMuteRefCount--;
6722 }
6723 break;
6724 case STARTING_BEACON:
6725 mBeaconPlayingRefCount++;
6726 break;
6727 case STOPPING_BEACON:
6728 if (mBeaconPlayingRefCount > 0) {
6729 mBeaconPlayingRefCount--;
6730 }
6731 break;
6732 }
6733
6734 if (mBeaconMuteRefCount > 0) {
6735 // any playback causes beacon to be muted
6736 return setBeaconMute(true);
6737 } else {
6738 // no other playback: unmute when beacon starts playing, mute when it stops
6739 return setBeaconMute(mBeaconPlayingRefCount == 0);
6740 }
6741}
6742
6743uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6744 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6745 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6746 // keep track of muted state to avoid repeating mute/unmute operations
6747 if (mBeaconMuted != mute) {
6748 // mute/unmute AUDIO_STREAM_TTS on all outputs
6749 ALOGV("\t muting %d", mute);
6750 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006751 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6752 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6753 ALOGV("\t no tts volume source available");
6754 return 0;
6755 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006756 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006757 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006758 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006759 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006760 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006761 maxLatency = latency;
6762 }
6763 }
6764 mBeaconMuted = mute;
6765 return maxLatency;
6766 }
6767 return 0;
6768}
6769
Eric Laurente0720872014-03-11 09:30:41 -07006770void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006771{
François Gaffiec005e562018-11-06 15:04:49 +01006772 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006773 mPreviousOutputs = mOutputs;
6774}
6775
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006776uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006777 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006778 uint32_t delayMs)
6779{
6780 // mute/unmute strategies using an incompatible device combination
6781 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6782 // if unmuting, unmute only after the specified delay
6783 if (outputDesc->isDuplicated()) {
6784 return 0;
6785 }
6786
6787 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006788 DeviceVector devices = outputDesc->devices();
6789 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006790
François Gaffiec005e562018-11-06 15:04:49 +01006791 auto productStrategies = mEngine->getOrderedProductStrategies();
6792 for (const auto &productStrategy : productStrategies) {
6793 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6794 DeviceVector curDevices =
6795 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6796 curDevices = curDevices.filter(outputDesc->supportedDevices());
6797 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006798 bool doMute = false;
6799
François Gaffiec005e562018-11-06 15:04:49 +01006800 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006801 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006802 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6803 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006804 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006805 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006806 }
Eric Laurent99401132014-05-07 19:48:15 -07006807 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006808 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006809 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006810 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006811 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006812 continue;
6813 }
François Gaffiec005e562018-11-06 15:04:49 +01006814 ALOGVV("%s() %s (curDevice %s)", __func__,
6815 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6816 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6817 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006818 if (mute) {
6819 // FIXME: should not need to double latency if volume could be applied
6820 // immediately by the audioflinger mixer. We must account for the delay
6821 // between now and the next time the audioflinger thread for this output
6822 // will process a buffer (which corresponds to one buffer size,
6823 // usually 1/2 or 1/4 of the latency).
6824 if (muteWaitMs < desc->latency() * 2) {
6825 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006826 }
6827 }
6828 }
6829 }
6830 }
6831 }
6832
Eric Laurent99401132014-05-07 19:48:15 -07006833 // temporary mute output if device selection changes to avoid volume bursts due to
6834 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006835 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006836 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006837
Eric Laurentdc462862016-07-19 12:29:53 -07006838 if (muteWaitMs < tempMuteWaitMs) {
6839 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006840 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006841
6842 // If recommended duration is defined, replace temporary mute duration to avoid
6843 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6844 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6845 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6846 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6847 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6848
François Gaffieaaac0fd2018-11-22 17:56:39 +01006849 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6850 // make sure that we do not start the temporary mute period too early in case of
6851 // delayed device change
6852 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6853 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006854 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006855 }
6856 }
6857
Eric Laurente552edb2014-03-10 17:42:56 -07006858 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6859 if (muteWaitMs > delayMs) {
6860 muteWaitMs -= delayMs;
6861 usleep(muteWaitMs * 1000);
6862 return muteWaitMs;
6863 }
6864 return 0;
6865}
6866
François Gaffie11d30102018-11-02 16:09:09 +01006867uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6868 const DeviceVector &devices,
6869 bool force,
6870 int delayMs,
6871 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006872 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006873{
François Gaffie11d30102018-11-02 16:09:09 +01006874 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006875 uint32_t muteWaitMs;
6876
6877 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006878 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6879 nullptr /* patchHandle */, requiresMuteCheck);
6880 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6881 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006882 return muteWaitMs;
6883 }
Eric Laurente552edb2014-03-10 17:42:56 -07006884
6885 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006886 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006887 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006888 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006889
François Gaffie11d30102018-11-02 16:09:09 +01006890 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6891
6892 if (!filteredDevices.isEmpty()) {
6893 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006894 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006895
6896 // if the outputs are not materially active, there is no need to mute.
6897 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006898 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006899 } else {
6900 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6901 muteWaitMs = 0;
6902 }
Eric Laurente552edb2014-03-10 17:42:56 -07006903
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006904 bool outputRouted = outputDesc->isRouted();
6905
Eric Laurent79ea9582020-06-11 18:49:24 -07006906 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6907 // output profile or if new device is not supported AND previous device(s) is(are) still
6908 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006909 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006910 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6911 // restore previous device after evaluating strategy mute state
6912 outputDesc->setDevices(prevDevices);
6913 return muteWaitMs;
6914 }
6915
Eric Laurente552edb2014-03-10 17:42:56 -07006916 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006917 // the requested device is AUDIO_DEVICE_NONE
6918 // OR the requested device is the same as current device
6919 // AND force is not specified
6920 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006921 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006922 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01006923 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
6924 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02006925 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
6926 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
6927 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
6928 }
Eric Laurente552edb2014-03-10 17:42:56 -07006929 return muteWaitMs;
6930 }
6931
François Gaffie11d30102018-11-02 16:09:09 +01006932 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07006933
Eric Laurente552edb2014-03-10 17:42:56 -07006934 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02006935 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006936 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07006937 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006938 PatchBuilder patchBuilder;
6939 patchBuilder.addSource(outputDesc);
6940 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
6941 for (const auto &filteredDevice : filteredDevices) {
6942 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07006943 }
6944
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08006945 // Add half reported latency to delayMs when muteWaitMs is null in order
6946 // to avoid disordered sequence of muting volume and changing devices.
6947 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
6948 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006949 }
Eric Laurente552edb2014-03-10 17:42:56 -07006950
6951 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01006952 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006953
6954 return muteWaitMs;
6955}
6956
Eric Laurentc75307b2015-03-17 15:29:32 -07006957status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07006958 int delayMs,
6959 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006960{
Eric Laurent6a94d692014-05-20 11:18:06 -07006961 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006962 if (patchHandle == nullptr && !outputDesc->isRouted()) {
6963 return INVALID_OPERATION;
6964 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006965 if (patchHandle) {
6966 index = mAudioPatches.indexOfKey(*patchHandle);
6967 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006968 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006969 }
6970 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006971 return INVALID_OPERATION;
6972 }
Eric Laurent6a94d692014-05-20 11:18:06 -07006973 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006974 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07006975 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07006976 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01006977 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006978 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07006979 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07006980 return status;
6981}
6982
6983status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01006984 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07006985 bool force,
6986 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07006987{
6988 status_t status = NO_ERROR;
6989
Eric Laurent1f2f2232014-06-02 12:01:23 -07006990 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01006991 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
6992 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07006993
François Gaffie11d30102018-11-02 16:09:09 +01006994 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07006995 PatchBuilder patchBuilder;
6996 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07006997 // AUDIO_SOURCE_HOTWORD is for internal use only:
6998 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07006999 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7000 auto result = usecase;
7001 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7002 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7003 }
7004 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007005 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007006 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007007 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007008 }
7009 }
7010 return status;
7011}
7012
Eric Laurent6a94d692014-05-20 11:18:06 -07007013status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7014 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007015{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007016 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007017 ssize_t index;
7018 if (patchHandle) {
7019 index = mAudioPatches.indexOfKey(*patchHandle);
7020 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007021 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007022 }
7023 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007024 return INVALID_OPERATION;
7025 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007026 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007027 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007028 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007029 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007030 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007031 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007032 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007033 return status;
7034}
7035
François Gaffie11d30102018-11-02 16:09:09 +01007036sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007037 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007038 audio_format_t& format,
7039 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007040 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007041{
7042 // Choose an input profile based on the requested capture parameters: select the first available
7043 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007044 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007045 //
7046 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7047 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007048
jiabin2fd710d2022-05-02 23:20:22 +00007049 const audio_input_flags_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ;
7050 const audio_input_flags_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007051
jiabin2fd710d2022-05-02 23:20:22 +00007052 for (;;) {
7053 sp<IOProfile> firstInexact = nullptr;
7054 uint32_t updatedSamplingRate = 0;
7055 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7056 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7057 for (const auto& hwModule : mHwModules) {
7058 for (const auto& profile : hwModule->getInputProfiles()) {
7059 // profile->log();
7060 //updatedFormat = format;
7061 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7062 &samplingRate /*updatedSamplingRate*/,
7063 format,
7064 &format, /*updatedFormat*/
7065 channelMask,
7066 &channelMask /*updatedChannelMask*/,
7067 // FIXME ugly cast
7068 (audio_output_flags_t) flags,
7069 true /*exactMatchRequiredForInputFlags*/)) {
7070 return profile;
7071 }
7072 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7073 samplingRate,
7074 &updatedSamplingRate,
7075 format,
7076 &updatedFormat,
7077 channelMask,
7078 &updatedChannelMask,
7079 // FIXME ugly cast
7080 (audio_output_flags_t) flags,
7081 false /*exactMatchRequiredForInputFlags*/)) {
7082 firstInexact = profile;
7083 }
7084 }
7085 }
7086
7087 if (firstInexact != nullptr) {
7088 samplingRate = updatedSamplingRate;
7089 format = updatedFormat;
7090 channelMask = updatedChannelMask;
7091 return firstInexact;
7092 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7093 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7094 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7095 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7096 flags = AUDIO_INPUT_FLAG_NONE;
7097 } else { // fail
7098 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7099 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7100 samplingRate, format, channelMask, oriFlags);
7101 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007102 }
7103 }
jiabin2fd710d2022-05-02 23:20:22 +00007104
7105 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007106}
7107
François Gaffieaaac0fd2018-11-22 17:56:39 +01007108float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7109 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007110 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007111 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007112{
jiabin9a3361e2019-10-01 09:38:30 -07007113 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007114
7115 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7116 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7117 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7118 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007119 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7120 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7121 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7122 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7123 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007124
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007125 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007126 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7127 mOutputs.isActive(ringVolumeSrc, 0)) {
7128 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007129 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007130 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007131 }
7132
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007133 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007134 if ((volumeSource != callVolumeSrc && (isInCall() ||
7135 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007136 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007137 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7138 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007139 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7140 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7141 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007142 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007143 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007144 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007145 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007146 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007147 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007148 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7149 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7150 // programmatically muted.
7151 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7152 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7153 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007154 bool exemptFromCapping =
7155 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7156 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007157 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7158 volumeSource, volumeDb);
7159 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007160 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7161 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7162 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007163 }
7164 }
Eric Laurente552edb2014-03-10 17:42:56 -07007165 // if a headset is connected, apply the following rules to ring tones and notifications
7166 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007167 // - always attenuate notifications volume by 6dB
7168 // - attenuate ring tones volume by 6dB unless music is not playing and
7169 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007170 // - if music is playing, always limit the volume to current music volume,
7171 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007172 if (!Intersection(deviceTypes,
7173 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7174 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007175 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7176 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007177 ((volumeSource == alarmVolumeSrc ||
7178 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007179 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7180 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7181 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007182 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7183 curves.canBeMuted()) {
7184
Eric Laurente552edb2014-03-10 17:42:56 -07007185 // when the phone is ringing we must consider that music could have been paused just before
7186 // by the music application and behave as if music was active if the last music track was
7187 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007188 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007189 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007190 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007191 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007192 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7193 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007194 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007195 float musicVolDb = computeVolume(musicCurves,
7196 musicVolumeSrc,
7197 musicCurves.getVolumeIndex(musicDevice),
7198 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007199 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7200 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7201 if (volumeDb > minVolDb) {
7202 volumeDb = minVolDb;
7203 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007204 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007205 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7206 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7207 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007208 // on A2DP, also ensure notification volume is not too low compared to media when
7209 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007210 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007211 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007212 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7213 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007214 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7215 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007216 }
7217 }
jiabin9a3361e2019-10-01 09:38:30 -07007218 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007219 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007220 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007221 }
7222 }
7223
François Gaffie43c73442018-11-08 08:21:55 +01007224 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007225}
7226
Eric Laurent3839bc02018-07-10 18:33:34 -07007227int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007228 VolumeSource fromVolumeSource,
7229 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007230{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007231 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007232 return srcIndex;
7233 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007234 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7235 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007236 float minSrc = (float)srcCurves.getVolumeIndexMin();
7237 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7238 float minDst = (float)dstCurves.getVolumeIndexMin();
7239 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007240
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007241 // preserve mute request or correct range
7242 if (srcIndex < minSrc) {
7243 if (srcIndex == 0) {
7244 return 0;
7245 }
7246 srcIndex = minSrc;
7247 } else if (srcIndex > maxSrc) {
7248 srcIndex = maxSrc;
7249 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007250 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7251}
7252
François Gaffieaaac0fd2018-11-22 17:56:39 +01007253status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7254 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007255 int index,
7256 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007257 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007258 int delayMs,
7259 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007260{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007261 // do not change actual attributes volume if the attributes is muted
7262 if (outputDesc->isMuted(volumeSource)) {
7263 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7264 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007265 return NO_ERROR;
7266 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007267 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7268 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7269 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7270 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007271
Eric Laurent2517af32020-11-25 15:31:27 +01007272 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007273 bool isHAUsed = isHearingAidUsedForComm();
7274
Eric Laurente552edb2014-03-10 17:42:56 -07007275 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007276 // if sco and call follow same curves, bypass forceUseForComm
7277 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007278 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007279 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007280 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007281 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007282 // Do not return an error here as AudioService will always set both voice call
7283 // and bluetooth SCO volumes due to stream aliasing.
7284 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007285 }
jiabin9a3361e2019-10-01 09:38:30 -07007286 if (deviceTypes.empty()) {
7287 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007288 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007289
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007290 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7291 ALOGE("invalid volume index range");
7292 return BAD_VALUE;
7293 }
7294
jiabin9a3361e2019-10-01 09:38:30 -07007295 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7296 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007297 // Force VoIP volume to max for bluetooth SCO device except if muted
7298 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007299 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007300 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007301 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007302 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007303 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007304 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007305
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007306 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007307 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007308 // 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 +01007309 if (isVoiceVolSrc) {
7310 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007311 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007312 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007313 }
Eric Laurent18fba842016-03-31 14:41:26 -07007314 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007315 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7316 mLastVoiceVolume = voiceVolume;
7317 }
7318 }
Eric Laurente552edb2014-03-10 17:42:56 -07007319 return NO_ERROR;
7320}
7321
Eric Laurentc75307b2015-03-17 15:29:32 -07007322void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007323 const DeviceTypeSet& deviceTypes,
7324 int delayMs,
7325 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007326{
jiabincd510522020-01-22 09:40:55 -08007327 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007328 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7329 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7330 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007331 curves.getVolumeIndex(deviceTypes),
7332 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007333 }
7334}
7335
François Gaffiec005e562018-11-06 15:04:49 +01007336void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7337 bool on,
7338 const sp<AudioOutputDescriptor>& outputDesc,
7339 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007340 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007341{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007342 std::vector<VolumeSource> sourcesToMute;
7343 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7344 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7345 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007346 VolumeSource source = toVolumeSource(attributes, false);
7347 if ((source != VOLUME_SOURCE_NONE) &&
7348 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7349 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007350 sourcesToMute.push_back(source);
7351 }
Eric Laurente552edb2014-03-10 17:42:56 -07007352 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007353 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007354 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007355 }
7356
Eric Laurente552edb2014-03-10 17:42:56 -07007357}
7358
François Gaffieaaac0fd2018-11-22 17:56:39 +01007359void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7360 bool on,
7361 const sp<AudioOutputDescriptor>& outputDesc,
7362 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007363 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007364{
jiabin9a3361e2019-10-01 09:38:30 -07007365 if (deviceTypes.empty()) {
7366 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007367 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007368 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007369 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007370 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007371 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007372 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007373 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7374 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007375 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007376 }
7377 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007378 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7379 // ignored
7380 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007381 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007382 if (!outputDesc->isMuted(volumeSource)) {
7383 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007384 return;
7385 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007386 if (outputDesc->decMuteCount(volumeSource) == 0) {
7387 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007388 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007389 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007390 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007391 delayMs);
7392 }
7393 }
7394}
7395
François Gaffie53615e22015-03-19 09:24:12 +01007396bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7397{
François Gaffiec005e562018-11-06 15:04:49 +01007398 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007399 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7400 return true;
7401 }
7402
7403 // has known usage?
7404 switch (paa->usage) {
7405 case AUDIO_USAGE_UNKNOWN:
7406 case AUDIO_USAGE_MEDIA:
7407 case AUDIO_USAGE_VOICE_COMMUNICATION:
7408 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7409 case AUDIO_USAGE_ALARM:
7410 case AUDIO_USAGE_NOTIFICATION:
7411 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7412 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7413 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7414 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7415 case AUDIO_USAGE_NOTIFICATION_EVENT:
7416 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7417 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7418 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7419 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007420 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007421 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007422 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007423 case AUDIO_USAGE_EMERGENCY:
7424 case AUDIO_USAGE_SAFETY:
7425 case AUDIO_USAGE_VEHICLE_STATUS:
7426 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007427 break;
7428 default:
7429 return false;
7430 }
7431 return true;
7432}
7433
François Gaffie2110e042015-03-24 08:41:51 +01007434audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7435{
7436 return mEngine->getForceUse(usage);
7437}
7438
Eric Laurent96d1dda2022-03-14 17:14:19 +01007439bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007440 return isStateInCall(mEngine->getPhoneState());
7441}
7442
Eric Laurent96d1dda2022-03-14 17:14:19 +01007443bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007444 return is_state_in_call(state);
7445}
7446
Eric Laurent74b71512019-11-06 17:21:57 -08007447bool AudioPolicyManager::isCallAudioAccessible()
7448{
7449 audio_mode_t mode = mEngine->getPhoneState();
7450 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007451 || (mode == AUDIO_MODE_CALL_SCREEN)
7452 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007453}
7454
Eric Laurentd60560a2015-04-10 11:31:20 -07007455void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7456{
7457 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007458 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007459 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007460 sourceDesc->sinkDevice()->equals(deviceDesc))
7461 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007462 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007463 }
7464 }
7465
7466 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7467 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7468 bool release = false;
7469 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7470 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7471 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7472 source->ext.device.type == deviceDesc->type()) {
7473 release = true;
7474 }
7475 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007476 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007477 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7478 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7479 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007480 sink->ext.device.type == deviceDesc->type() &&
7481 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7482 || strncmp(sink->ext.device.address, address,
7483 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007484 release = true;
7485 }
7486 }
7487 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007488 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7489 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007490 }
7491 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007492
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007493 mInputs.clearSessionRoutesForDevice(deviceDesc);
7494
Francois Gaffie716e1432019-01-14 16:58:59 +01007495 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007496}
7497
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007498void AudioPolicyManager::modifySurroundFormats(
7499 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007500 std::unordered_set<audio_format_t> enforcedSurround(
7501 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007502 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7503 for (const auto& pair : mConfig.getSurroundFormats()) {
7504 allSurround.insert(pair.first);
7505 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7506 }
Phil Burk09bc4612016-02-24 15:58:15 -08007507
7508 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7509 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007510 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007511 // This is the resulting set of formats depending on the surround mode:
7512 // 'all surround' = allSurround
7513 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7514 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7515 // 'manual surround' = mManualSurroundFormats
7516 // AUTO: formats v 'enforced surround'
7517 // ALWAYS: formats v 'all surround' v 'enforced surround'
7518 // NEVER: formats ^ 'non-surround'
7519 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007520
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007521 std::unordered_set<audio_format_t> formatSet;
7522 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7523 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007524 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007525 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007526 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007527 formatSet.insert(*formatIter);
7528 }
7529 }
7530 } else {
7531 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7532 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007533 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007534
jiabin81772902018-04-02 17:52:27 -07007535 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007536 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007537 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7538 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7539 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007540 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007541 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7542 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7543 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007544 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007545 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007546 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007547 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007548 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007549 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007550}
7551
jiabin06e4bab2019-07-29 10:13:34 -07007552void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7553 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007554 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7555 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7556
7557 // If NEVER, then remove support for channelMasks > stereo.
7558 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007559 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7560 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007561 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007562 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007563 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007564 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007565 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007566 }
7567 }
jiabin81772902018-04-02 17:52:27 -07007568 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7569 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7570 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007571 bool supports5dot1 = false;
7572 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007573 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007574 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7575 supports5dot1 = true;
7576 break;
7577 }
7578 }
7579 // If not then add 5.1 support.
7580 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007581 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007582 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007583 }
Phil Burk09bc4612016-02-24 15:58:15 -08007584 }
7585}
7586
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007587void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007588 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007589 AudioProfileVector &profiles)
7590{
7591 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007592 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007593
François Gaffie112b0af2015-11-19 16:13:25 +01007594 // Format MUST be checked first to update the list of AudioProfile
7595 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007596 reply = mpClientInterface->getParameters(
7597 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007598 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007599 AudioParameter repliedParameters(reply);
7600 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007601 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007602 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7603 return;
7604 }
Phil Burk09bc4612016-02-24 15:58:15 -08007605 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007606 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007607 if (device == AUDIO_DEVICE_OUT_HDMI
7608 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007609 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007610 }
jiabin3e277cc2019-09-10 14:27:34 -07007611 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007612 }
François Gaffie112b0af2015-11-19 16:13:25 +01007613
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007614 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007615 ChannelMaskSet channelMasks;
7616 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007617 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007618 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007619
7620 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007621 reply = mpClientInterface->getParameters(
7622 ioHandle,
7623 requestedParameters.toString() + ";" +
7624 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007625 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007626 AudioParameter repliedParameters(reply);
7627 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007628 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007629 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007630 }
7631 }
7632 if (profiles.hasDynamicChannelsFor(format)) {
7633 reply = mpClientInterface->getParameters(ioHandle,
7634 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007635 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007636 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007637 AudioParameter repliedParameters(reply);
7638 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007639 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007640 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007641 if (device == AUDIO_DEVICE_OUT_HDMI
7642 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007643 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007644 }
François Gaffie112b0af2015-11-19 16:13:25 +01007645 }
7646 }
jiabin3e277cc2019-09-10 14:27:34 -07007647 addDynamicAudioProfileAndSort(
7648 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007649 }
7650}
Eric Laurentd60560a2015-04-10 11:31:20 -07007651
Mikhail Naganovdc769682018-05-04 15:34:08 -07007652status_t AudioPolicyManager::installPatch(const char *caller,
7653 audio_patch_handle_t *patchHandle,
7654 AudioIODescriptorInterface *ioDescriptor,
7655 const struct audio_patch *patch,
7656 int delayMs)
7657{
7658 ssize_t index = mAudioPatches.indexOfKey(
7659 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7660 *patchHandle : ioDescriptor->getPatchHandle());
7661 sp<AudioPatch> patchDesc;
7662 status_t status = installPatch(
7663 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7664 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007665 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007666 }
7667 return status;
7668}
7669
7670status_t AudioPolicyManager::installPatch(const char *caller,
7671 ssize_t index,
7672 audio_patch_handle_t *patchHandle,
7673 const struct audio_patch *patch,
7674 int delayMs,
7675 uid_t uid,
7676 sp<AudioPatch> *patchDescPtr)
7677{
7678 sp<AudioPatch> patchDesc;
7679 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7680 if (index >= 0) {
7681 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007682 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007683 }
7684
7685 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7686 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7687 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7688 if (status == NO_ERROR) {
7689 if (index < 0) {
7690 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007691 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007692 } else {
7693 patchDesc->mPatch = *patch;
7694 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007695 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007696 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007697 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007698 }
7699 nextAudioPortGeneration();
7700 mpClientInterface->onAudioPatchListUpdate();
7701 }
7702 if (patchDescPtr) *patchDescPtr = patchDesc;
7703 return status;
7704}
7705
jiabinbce0c1d2020-10-05 11:20:18 -07007706bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7707{
7708 const TrackClientVector activeClients = output->getActiveClients();
7709 if (activeClients.empty()) {
7710 return true;
7711 }
7712 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7713 if (index < 0) {
7714 ALOGE("%s, no audio patch found while there are active clients on output %d",
7715 __func__, output->getId());
7716 return false;
7717 }
7718 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7719 DeviceVector routedDevices;
7720 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7721 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7722 patchDesc->mPatch.sinks[i].id);
7723 if (device == nullptr) {
7724 ALOGE("%s, no audio device found with id(%d)",
7725 __func__, patchDesc->mPatch.sinks[i].id);
7726 return false;
7727 }
7728 routedDevices.add(device);
7729 }
7730 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007731 if (client->isInvalid()) {
7732 // No need to take care about invalidated clients.
7733 continue;
7734 }
jiabinbce0c1d2020-10-05 11:20:18 -07007735 sp<DeviceDescriptor> preferredDevice =
7736 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7737 if (mEngine->getOutputDevicesForAttributes(
7738 client->attributes(), preferredDevice, false) == routedDevices) {
7739 return false;
7740 }
7741 }
7742 return true;
7743}
7744
7745sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007746 const sp<IOProfile>& profile, const DeviceVector& devices,
7747 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007748{
7749 for (const auto& device : devices) {
7750 // TODO: This should be checking if the profile supports the device combo.
7751 if (!profile->supportsDevice(device)) {
7752 return nullptr;
7753 }
7754 }
7755 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7756 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007757 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007758 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7759 if (status != NO_ERROR) {
7760 return nullptr;
7761 }
7762
7763 // Here is where the out_set_parameters() for card & device gets called
7764 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7765 const audio_devices_t deviceType = device->type();
7766 const String8 &address = String8(device->address().c_str());
7767 if (!address.isEmpty()) {
7768 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7769 mpClientInterface->setParameters(output, String8(param));
7770 free(param);
7771 }
7772 updateAudioProfiles(device, output, profile->getAudioProfiles());
7773 if (!profile->hasValidAudioProfile()) {
7774 ALOGW("%s() missing param", __func__);
7775 desc->close();
7776 return nullptr;
7777 } else if (profile->hasDynamicAudioProfile()) {
7778 desc->close();
7779 output = AUDIO_IO_HANDLE_NONE;
7780 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7781 profile->pickAudioProfile(
7782 config.sample_rate, config.channel_mask, config.format);
7783 config.offload_info.sample_rate = config.sample_rate;
7784 config.offload_info.channel_mask = config.channel_mask;
7785 config.offload_info.format = config.format;
7786
Eric Laurentb4f42a92022-01-17 17:37:31 +01007787 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007788 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7789 if (status != NO_ERROR) {
7790 return nullptr;
7791 }
7792 }
7793
7794 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007795
baek.kim -61c20122022-07-27 10:05:32 +00007796 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
7797 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
7798
jiabinbce0c1d2020-10-05 11:20:18 -07007799 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7800 sp<AudioPolicyMix> policyMix;
7801 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7802 policyMix->setOutput(desc);
7803 desc->mPolicyMix = policyMix;
7804 } else {
7805 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7806 address.string());
7807 }
7808
baek.kim -61c20122022-07-27 10:05:32 +00007809 } else if (hasPrimaryOutput() && speaker != nullptr
7810 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01007811 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7812 // no duplicated output for:
7813 // - direct outputs
7814 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00007815 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07007816 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7817
7818 //TODO: configure audio effect output stage here
7819
7820 // open a duplicating output thread for the new output and the primary output
7821 sp<SwAudioOutputDescriptor> dupOutputDesc =
7822 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7823 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7824 if (status == NO_ERROR) {
7825 // add duplicated output descriptor
7826 addOutput(duplicatedOutput, dupOutputDesc);
7827 } else {
7828 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7829 mPrimaryOutput->mIoHandle, output);
7830 desc->close();
7831 removeOutput(output);
7832 nextAudioPortGeneration();
7833 return nullptr;
7834 }
7835 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007836 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7837 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7838 mPrimaryOutput = desc;
7839 }
jiabinbce0c1d2020-10-05 11:20:18 -07007840 return desc;
7841}
7842
jiabinf1c73972022-04-14 16:28:52 -07007843status_t AudioPolicyManager::getDevicesForAttributes(
7844 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
7845 // Devices are determined in the following precedence:
7846 //
7847 // 1) Devices associated with a dynamic policy matching the attributes. This is often
7848 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
7849 //
7850 // If no such dynamic policy then
7851 // 2) Devices containing an active client using setPreferredDevice
7852 // with same strategy as the attributes.
7853 // (from the default Engine::getOutputDevicesForAttributes() implementation).
7854 //
7855 // If no corresponding active client with setPreferredDevice then
7856 // 3) Devices associated with the strategy determined by the attributes
7857 // (from the default Engine::getOutputDevicesForAttributes() implementation).
7858 //
7859 // See related getOutputForAttrInt().
7860
7861 // check dynamic policies but only for primary descriptors (secondary not used for audible
7862 // audio routing, only used for duplication for playback capture)
7863 sp<AudioPolicyMix> policyMix;
7864 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007865 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE, policyMix,
jiabinf1c73972022-04-14 16:28:52 -07007866 nullptr /* secondaryMixes */);
7867 if (status != OK) {
7868 return status;
7869 }
7870
7871 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
7872 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
7873 // as they are unaffected by device/stream volume
7874 // (per SwAudioOutputDescriptor::isFixedVolume()).
7875 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
7876 ) {
7877 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
7878 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
7879 devices.add(deviceDesc);
7880 } else {
7881 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
7882 // which selects setPreferredDevice if active. This means forVolume call
7883 // will take an active setPreferredDevice, if such exists.
7884
7885 devices = mEngine->getOutputDevicesForAttributes(
7886 attr, nullptr /* preferredDevice */, false /* fromCache */);
7887 }
7888
7889 if (forVolume) {
7890 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
7891 // for single volume control in AudioService (such relationship should exist if
7892 // SPEAKER_SAFE is present).
7893 //
7894 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
7895 DeviceVector speakerSafeDevices =
7896 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
7897 if (!speakerSafeDevices.isEmpty()) {
7898 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
7899 devices.remove(speakerSafeDevices);
7900 }
7901 }
7902
7903 return NO_ERROR;
7904}
7905
7906status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
7907 AudioProfileVector& audioProfiles,
7908 uint32_t flags,
7909 bool isInput) {
7910 for (const auto& hwModule : mHwModules) {
7911 // the MSD module checks for different conditions
7912 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
7913 continue;
7914 }
7915 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
7916 : hwModule->getOutputProfiles();
7917 for (const auto& profile : ioProfiles) {
7918 if (!profile->areAllDevicesSupported(devices) ||
7919 !profile->isCompatibleProfileForFlags(
7920 flags, false /*exactMatchRequiredForInputFlags*/)) {
7921 continue;
7922 }
7923 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
7924 }
7925 }
7926
7927 if (!isInput) {
7928 // add the direct profiles from MSD if present and has audio patches to all the output(s)
7929 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
7930 if (msdModule != nullptr) {
7931 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
7932 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
7933 for (const auto &profile: msdModule->getOutputProfiles()) {
7934 if (!profile->asAudioPort()->isDirectOutput()) {
7935 continue;
7936 }
7937 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
7938 }
7939 } else {
7940 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
7941 }
7942 }
7943 }
7944
7945 return NO_ERROR;
7946}
7947
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007948} // namespace android