blob: 63c0ba56390bb125ef44f395cbc51e7109308db2 [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
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070044#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070045#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070046#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070047#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070048#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070049#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070050#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070051#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070052#include <utils/Log.h>
53
Eric Laurentd4692962014-05-05 18:13:44 -070054#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010055#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070056
Eric Laurent3b73df72014-03-11 09:06:29 -070057namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070058
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010059using android::media::audio::common::AudioDevice;
60using android::media::audio::common::AudioDeviceAddress;
61using android::media::audio::common::AudioPortDeviceExt;
62using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000063using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070064
Eric Laurentdc462862016-07-19 12:29:53 -070065//FIXME: workaround for truncated touch sounds
66// to be removed when the problem is handled by system UI
67#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070068
69// Largest difference in dB on earpiece in call between the voice volume and another
70// media / notification / system volume.
71constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
72
jiabin06e4bab2019-07-29 10:13:34 -070073template <typename T>
74bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
75{
76 if (left.size() != right.size()) {
77 return false;
78 }
79 for (size_t index = 0; index < right.size(); index++) {
80 if (left[index] != right[index]) {
81 return false;
82 }
83 }
84 return true;
85}
86
87template <typename T>
88bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
89{
90 return !(left == right);
91}
92
Eric Laurente552edb2014-03-10 17:42:56 -070093// ----------------------------------------------------------------------------
94// AudioPolicyInterface implementation
95// ----------------------------------------------------------------------------
96
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010097status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
98 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
99 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800100 nextAudioPortGeneration();
101 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800102}
103
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100104status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
105 audio_policy_dev_state_t state,
106 const char* device_address,
107 const char* device_name,
108 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800109 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
111 status == OK) {
112 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
113 } else {
114 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
115 return status;
116 }
117}
118
François Gaffie11d30102018-11-02 16:09:09 +0100119void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000120 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200121{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000122 audio_port_v7 devicePort;
123 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000124 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000125 status != OK) {
jiabinc0048632023-04-27 22:04:31 +0000126 ALOGE("Error %d while setting connected state for device %s", state,
Mikhail Naganov516d3982022-02-01 23:53:59 +0000127 device->getDeviceTypeAddr().toString(false).c_str());
128 }
François Gaffie44481e72016-04-20 07:49:57 +0200129}
130
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100131status_t AudioPolicyManager::setDeviceConnectionStateInt(
132 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
133 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100134 if (port.ext.getTag() != AudioPortExt::device) {
135 return BAD_VALUE;
136 }
137 audio_devices_t device_type;
138 std::string device_address;
139 if (status_t status = aidl2legacy_AudioDevice_audio_device(
140 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
141 status != OK) {
142 return status;
143 };
144 const char* device_name = port.name.c_str();
145 // connect/disconnect only 1 device at a time
146 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
147 return BAD_VALUE;
148
149 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
150 device_type, device_address.c_str(), device_name, encodedFormat,
151 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000152 if (device == nullptr) {
153 return INVALID_OPERATION;
154 }
155 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
156 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
157 }
158 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100159}
160
François Gaffie11d30102018-11-02 16:09:09 +0100161status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800162 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100163 const char* device_address,
164 const char* device_name,
165 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800166 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100167 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
168 status == OK) {
169 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
170 } else {
171 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
172 return status;
173 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700174}
Paul McLeane743a472015-01-28 11:07:31 -0800175
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700176status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
177 audio_policy_dev_state_t state)
178{
Eric Laurente552edb2014-03-10 17:42:56 -0700179 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700180 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700181 SortedVector <audio_io_handle_t> outputs;
182
François Gaffie11d30102018-11-02 16:09:09 +0100183 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700184
Eric Laurente552edb2014-03-10 17:42:56 -0700185 // save a copy of the opened output descriptors before any output is opened or closed
186 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
187 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100188
189 bool wasLeUnicastActive = isLeUnicastActive();
190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 switch (state)
192 {
193 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800194 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700195 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100196 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700197 return INVALID_OPERATION;
198 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800199 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700200 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700201
Eric Laurente552edb2014-03-10 17:42:56 -0700202 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200203 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700204 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700205 }
206
François Gaffie44481e72016-04-20 07:49:57 +0200207 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
208 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000209 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200210
François Gaffie11d30102018-11-02 16:09:09 +0100211 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
212 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200213
Francois Gaffie716e1432019-01-14 16:58:59 +0100214 mHwModules.cleanUpForDevice(device);
215
jiabinc0048632023-04-27 22:04:31 +0000216 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700217 return INVALID_OPERATION;
218 }
François Gaffie2110e042015-03-24 08:41:51 +0100219
jiabin1c4794b2020-05-05 10:08:05 -0700220 // Populate encapsulation information when a output device is connected.
221 device->setEncapsulationInfoFromHal(mpClientInterface);
222
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700223 // outputs should never be empty here
224 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
225 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100226 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800227
Eric Laurent3ae5f312015-02-03 17:12:08 -0800228 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700229 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700230 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700231 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100232 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700233 return INVALID_OPERATION;
234 }
235
François Gaffie11d30102018-11-02 16:09:09 +0100236 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700237
jiabinc0048632023-04-27 22:04:31 +0000238 // Notify the HAL to prepare to disconnect device
239 broadcastDeviceConnectionState(
240 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700241
Eric Laurente552edb2014-03-10 17:42:56 -0700242 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100243 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700244
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100245 mOutputs.clearSessionRoutesForDevice(device);
246
François Gaffie11d30102018-11-02 16:09:09 +0100247 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100248
jiabinc0048632023-04-27 22:04:31 +0000249 // Send Disconnect to HALs
250 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
251
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800252 // Reset active device codec
253 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
254
Kriti Dangef6be8f2020-11-05 11:58:19 +0100255 // remove device from mReportedFormatsMap cache
256 mReportedFormatsMap.erase(device);
257
jiabina84c3d32022-12-02 18:59:55 +0000258 // remove preferred mixer configurations
259 mPreferredMixerAttrInfos.erase(device->getId());
260
Eric Laurente552edb2014-03-10 17:42:56 -0700261 } break;
262
263 default:
François Gaffie11d30102018-11-02 16:09:09 +0100264 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700265 return BAD_VALUE;
266 }
267
Eric Laurent736a1022019-03-27 18:28:46 -0700268 // Propagate device availability to Engine
269 setEngineDeviceConnectionState(device, state);
270
Eric Laurentae970022019-01-29 14:25:04 -0800271 // No need to evaluate playback routing when connecting a remote submix
272 // output device used by a dynamic policy of type recorder as no
273 // playback use case is affected.
274 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700275 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800276 for (audio_io_handle_t output : outputs) {
277 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800278 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
279 if (policyMix != nullptr
280 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000281 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800282 doCheckForDeviceAndOutputChanges = false;
283 break;
284 }
285 }
286 }
287
288 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700289 // outputs must be closed after checkOutputForAllStrategies() is executed
290 if (!outputs.isEmpty()) {
291 for (audio_io_handle_t output : outputs) {
292 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100293 // close unused outputs after device disconnection or direct outputs that have
294 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200295 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200296 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
297 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200298 (desc->mDirectOpenCount == 0))
299 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
300 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200301 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700302 closeOutput(output);
303 }
Eric Laurente552edb2014-03-10 17:42:56 -0700304 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700305 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
306 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700307 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700308 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800309 };
310
311 if (doCheckForDeviceAndOutputChanges) {
312 checkForDeviceAndOutputChanges(checkCloseOutputs);
313 } else {
314 checkCloseOutputs();
315 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100316 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100317 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700318 const DeviceVector activeMediaDevices =
319 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000320 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700321 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700322 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530323 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
324 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100325 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700326 // do not force device change on duplicated output because if device is 0, it will
327 // also force a device 0 for the two outputs it is duplicated to which may override
328 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100329 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100330 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700331 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700332 // always force when disconnecting (a non-duplicated device)
333 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000334 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
335 // If the device is using preferred mixer attributes, the output need to reopen
336 // with default configuration when the new selected devices are different from
337 // current routing devices
338 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
339 continue;
340 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530341 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700342 }
jiabinbce0c1d2020-10-05 11:20:18 -0700343 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000344 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700345 desc->supportsDevicesForPlayback(activeMediaDevices)) {
346 // Reopen the output to query the dynamic profiles when there is not active
347 // clients or all active clients will be rerouted. Otherwise, set the flag
348 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
349 // can be reopened to query dynamic profiles when all clients are inactive.
350 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000351 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700352 } else {
353 desc->mPendingReopenToQueryProfiles = true;
354 }
355 }
356 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
357 // Clear the flag that previously set for re-querying profiles.
358 desc->mPendingReopenToQueryProfiles = false;
359 }
360 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000361 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700362
Eric Laurentd60560a2015-04-10 11:31:20 -0700363 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100364 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700365 }
366
Eric Laurent96d1dda2022-03-14 17:14:19 +0100367 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
368
Eric Laurent72aa32f2014-05-30 18:51:48 -0700369 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700370 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700371 } // end if is output device
372
Eric Laurente552edb2014-03-10 17:42:56 -0700373 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700374 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100375 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700376 switch (state)
377 {
378 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700379 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700380 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100381 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700382 return INVALID_OPERATION;
383 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700384
385 if (mAvailableInputDevices.add(device) < 0) {
386 return NO_MEMORY;
387 }
388
François Gaffie44481e72016-04-20 07:49:57 +0200389 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
390 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000391 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200392
Eric Laurent0dd51852019-04-19 18:18:58 -0700393 if (checkInputsForDevice(device, state) != NO_ERROR) {
394 mAvailableInputDevices.remove(device);
395
jiabinc0048632023-04-27 22:04:31 +0000396 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100397
398 mHwModules.cleanUpForDevice(device);
399
Eric Laurentd4692962014-05-05 18:13:44 -0700400 return INVALID_OPERATION;
401 }
402
Eric Laurentd4692962014-05-05 18:13:44 -0700403 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700404
405 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700406 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700407 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100408 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700409 return INVALID_OPERATION;
410 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700411
François Gaffie11d30102018-11-02 16:09:09 +0100412 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700413
jiabinc0048632023-04-27 22:04:31 +0000414 // Notify the HAL to prepare to disconnect device
415 broadcastDeviceConnectionState(
416 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700417
François Gaffie11d30102018-11-02 16:09:09 +0100418 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700419
420 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100421
jiabinc0048632023-04-27 22:04:31 +0000422 // Set Disconnect to HALs
423 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
424
Kriti Dangef6be8f2020-11-05 11:58:19 +0100425 // remove device from mReportedFormatsMap cache
426 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700427 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700428
429 default:
François Gaffie11d30102018-11-02 16:09:09 +0100430 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700431 return BAD_VALUE;
432 }
433
Eric Laurent736a1022019-03-27 18:28:46 -0700434 // Propagate device availability to Engine
435 setEngineDeviceConnectionState(device, state);
436
Eric Laurent0dd51852019-04-19 18:18:58 -0700437 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700438 // As the input device list can impact the output device selection, update
439 // getDeviceForStrategy() cache
440 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700441
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100442 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200443 // Reconnect Audio Source
444 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
445 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
446 checkAudioSourceForAttributes(attributes);
447 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700448 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100449 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700450 }
451
Eric Laurentb52c1522014-05-20 11:27:36 -0700452 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700453 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700454 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700455
François Gaffie11d30102018-11-02 16:09:09 +0100456 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700457 return BAD_VALUE;
458}
459
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100460status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
461 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800462 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700463 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
464 devDescr->setName(device_name);
465 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100466}
467
Eric Laurent736a1022019-03-27 18:28:46 -0700468void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
469 audio_policy_dev_state_t state) {
470
471 // the Engine does not have to know about remote submix devices used by dynamic audio policies
472 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
473 return;
474 }
475 mEngine->setDeviceConnectionState(device, state);
476}
477
478
Eric Laurente0720872014-03-11 09:30:41 -0700479audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100480 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700481{
Eric Laurent634b7142016-04-20 13:48:02 -0700482 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800483 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
484 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700485 (strlen(device_address) != 0)/*matchAddress*/);
486
487 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100488 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700489 device, device_address);
490 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
491 }
François Gaffie53615e22015-03-19 09:24:12 +0100492
Eric Laurent3a4311c2014-03-17 12:00:47 -0700493 DeviceVector *deviceVector;
494
Eric Laurente552edb2014-03-10 17:42:56 -0700495 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700496 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700497 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700498 deviceVector = &mAvailableInputDevices;
499 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100500 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700501 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700502 }
Eric Laurent634b7142016-04-20 13:48:02 -0700503
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800504 return (deviceVector->getDevice(
505 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700506 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800507}
508
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800509status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
510 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 const char *device_name,
512 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800513{
514 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700515 String8 reply;
516 AudioParameter param;
517 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800518
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800519 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
520 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800521
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800522 // connect/disconnect only 1 device at a time
523 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
524
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700526 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528 // Nothing to do: device is not connected
529 return NO_ERROR;
530 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800531 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700533 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 // configure codecs.
535 // Handle two specific cases by sending a set parameter to
536 // configure A2DP codecs. No need to toggle device state.
537 // Case 1: A2DP active device switches from primary to primary
538 // module
539 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200540 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700541 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
543 if (availablePrimaryOutputDevices().contains(devDesc) &&
544 (module != 0 && module->getHandle() == primaryHandle)) {
545 reply = mpClientInterface->getParameters(
546 AUDIO_IO_HANDLE_NONE,
547 String8(AudioParameter::keyReconfigA2dpSupported));
548 AudioParameter repliedParameters(reply);
549 repliedParameters.getInt(
550 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
551 if (isReconfigA2dpSupported) {
552 const String8 key(AudioParameter::keyReconfigA2dp);
553 param.add(key, String8("true"));
554 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
555 devDesc->setEncodedFormat(encodedFormat);
556 return NO_ERROR;
557 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700558 }
559 }
cnx421bd2dcc42020-07-11 14:58:44 +0800560 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
561 for (size_t i = 0; i < mOutputs.size(); i++) {
562 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
563 // mute media strategies and delay device switch by the largest
564 // This avoid sending the music tail into the earpiece or headset.
565 setStrategyMute(musicStrategy, true, desc);
566 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
567 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
568 nullptr, true /*fromCache*/).types());
569 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800570 // Toggle the device state: UNAVAILABLE -> AVAILABLE
571 // This will force reading again the device configuration
572 status = setDeviceConnectionState(device,
573 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800574 device_address, device_name,
575 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800576 if (status != NO_ERROR) {
577 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
578 status);
579 return status;
580 }
581
582 status = setDeviceConnectionState(device,
583 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800584 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800585 if (status != NO_ERROR) {
586 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
587 status);
588 return status;
589 }
590
591 return NO_ERROR;
592}
593
Pattydd807582021-11-04 21:01:03 +0800594status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
595 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800596{
Pattydd807582021-11-04 21:01:03 +0800597 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800598 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800599 std::unordered_set<audio_format_t> formatSet;
600 sp<HwModule> primaryModule =
601 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700602 if (primaryModule == nullptr) {
603 ALOGE("%s() unable to get primary module", __func__);
604 return NO_INIT;
605 }
Pattydd807582021-11-04 21:01:03 +0800606
607 DeviceTypeSet audioDeviceSet;
608
609 switch(device) {
610 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
611 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
612 break;
613 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800614 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
615 break;
616 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
617 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800618 break;
619 default:
620 ALOGE("%s() device type 0x%08x not supported", __func__, device);
621 return BAD_VALUE;
622 }
623
jiabin9a3361e2019-10-01 09:38:30 -0700624 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800625 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800626 for (const auto& device : declaredDevices) {
627 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800629 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800630 return status;
631}
632
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100633DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
634{
635 DeviceVector rxSinkdevices{};
636 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
637 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
638 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
639 auto rxSinkDevice = rxSinkdevices.itemAt(0);
640 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
641 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
642 // retrieve Rx Source device descriptor
643 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
644 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
645
646 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
647 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
648 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
649 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
650 return DeviceVector(rxSinkDevice);
651 }
652 }
653 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
654 // the device returned is not necessarily reachable via this output
655 // (filter later by setOutputDevices())
656 return getNewOutputDevices(mPrimaryOutput, fromCache);
657}
658
659status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
660{
661 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
662 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
663 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
664 }
665 return INVALID_OPERATION;
666}
667
668status_t AudioPolicyManager::updateCallRoutingInternal(
669 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670{
671 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100672 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700673 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700674 if(!hasPrimaryOutput() ||
675 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700677 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100678 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100679
Francois Gaffie716e1432019-01-14 16:58:59 +0100680 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100681 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Eric Laurentcedd5b52023-03-22 00:03:31 +0000682 if (txSourceDevice == nullptr) {
683 ALOGE("%s() selected input device not available", __func__);
684 return INVALID_OPERATION;
685 }
François Gaffiec005e562018-11-06 15:04:49 +0100686
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100687 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100688 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700689
Francois Gaffie601801d2021-06-22 13:27:39 +0200690 disconnectTelephonyAudioSource(mCallRxSourceClient);
691 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700692
François Gaffie9eb18552018-11-05 10:33:26 +0100693 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700694 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100695 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700696 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100697 // retrieve Rx Source and Tx Sink device descriptors
698 sp<DeviceDescriptor> rxSourceDevice =
699 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
700 String8(),
701 AUDIO_FORMAT_DEFAULT);
702 sp<DeviceDescriptor> txSinkDevice =
703 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
704 String8(),
705 AUDIO_FORMAT_DEFAULT);
706
707 // RX and TX Telephony device are declared by Primary Audio HAL
708 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
709 (telephonyRxModule->getHalVersionMajor() >= 3)) {
710 if (rxSourceDevice == 0 || txSinkDevice == 0) {
711 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100712 ALOGE("%s() no telephony Tx and/or RX device", __func__);
713 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100714 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100715 // createAudioPatchInternal now supports both HW / SW bridging
716 createRxPatch = true;
717 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100718 } else {
719 // If the RX device is on the primary HW module, then use legacy routing method for
720 // voice calls via setOutputDevice() on primary output.
721 // Otherwise, create two audio patches for TX and RX path.
722 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
723 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700724 // If the TX device is also on the primary HW module, setOutputDevice() will take care
725 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100726 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
727 (txSinkDevice != 0);
728 }
729 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
730 // Otherwise, create two audio patches for TX and RX path.
731 if (!createRxPatch) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530732 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700733 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200734 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800735 // If the TX device is on the primary HW module but RX device is
736 // on other HW module, SinkMetaData of telephony input should handle it
737 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700738 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700739 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100740 // terminate active capture if on the same HW module as the call TX source device
741 // FIXME: would be better to refine to only inputs whose profile connects to the
742 // call TX device but this information is not in the audio patch and logic here must be
743 // symmetric to the one in startInput()
744 for (const auto& activeDesc : mInputs.getActiveInputs()) {
745 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
746 closeActiveClients(activeDesc);
747 }
748 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200749 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800750 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100751 if (waitMs != nullptr) {
752 *waitMs = muteWaitMs;
753 }
754 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800755}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700756
Mikhail Naganov100f0122018-11-29 11:22:16 -0800757bool AudioPolicyManager::isDeviceOfModule(
758 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
759 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
760 if (module != 0) {
761 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
762 .indexOf(devDesc) != NAME_NOT_FOUND
763 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
764 .indexOf(devDesc) != NAME_NOT_FOUND;
765 }
766 return false;
767}
768
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200769void AudioPolicyManager::connectTelephonyRxAudioSource()
770{
Francois Gaffie601801d2021-06-22 13:27:39 +0200771 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200772 const struct audio_port_config source = {
773 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
774 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
775 };
776 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200777 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
778 ALOGE_IF(mCallRxSourceClient == nullptr,
779 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200780}
781
Francois Gaffie601801d2021-06-22 13:27:39 +0200782void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200783{
Francois Gaffie601801d2021-06-22 13:27:39 +0200784 if (clientDesc == nullptr) {
785 return;
786 }
787 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
788 "%s error stopping audio source", __func__);
789 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200790}
791
792void AudioPolicyManager::connectTelephonyTxAudioSource(
793 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
794 uint32_t delayMs)
795{
Francois Gaffie601801d2021-06-22 13:27:39 +0200796 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200797 if (srcDevice == nullptr || sinkDevice == nullptr) {
798 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
799 return;
800 }
801 PatchBuilder patchBuilder;
802 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
803 ALOGV("%s between source %s and sink %s", __func__,
804 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200805 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200806 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
807
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200808 struct audio_port_config source = {};
809 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200810 mCallTxSourceClient = new InternalSourceClientDescriptor(
811 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200812 mCommunnicationStrategy, toVolumeSource(aa));
813 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
814 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200815 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
816 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200817 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
818 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200819 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200820 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200821}
822
Eric Laurente0720872014-03-11 09:30:41 -0700823void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700824{
825 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100826 // store previous phone state for management of sonification strategy below
827 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100828 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100829
830 if (mEngine->setPhoneState(state) != NO_ERROR) {
831 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700832 return;
833 }
François Gaffie2110e042015-03-24 08:41:51 +0100834 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700835 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700836 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700837 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800838 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700839 }
840
François Gaffie2110e042015-03-24 08:41:51 +0100841 /**
842 * Switching to or from incall state or switching between telephony and VoIP lead to force
843 * routing command.
844 */
Eric Laurent74b71512019-11-06 17:21:57 -0800845 bool force = ((isStateInCall(oldState) != isStateInCall(state))
846 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700847
848 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700849 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700850
Eric Laurente552edb2014-03-10 17:42:56 -0700851 int delayMs = 0;
852 if (isStateInCall(state)) {
853 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100854 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
855 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700856 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700857 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700858 // mute media and sonification strategies and delay device switch by the largest
859 // latency of any output where either strategy is active.
860 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100861 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
862 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
863 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700864 (delayMs < (int)desc->latency()*2)) {
865 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700866 }
François Gaffiec005e562018-11-06 15:04:49 +0100867 setStrategyMute(musicStrategy, true, desc);
868 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
869 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
870 nullptr, true /*fromCache*/).types());
871 setStrategyMute(sonificationStrategy, true, desc);
872 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
873 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
874 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700875 }
876 }
877
Eric Laurent87ffa392015-05-22 10:32:38 -0700878 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700879 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100880 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700881 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100882 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
883 // force routing command to audio hardware when ending call
884 // even if no device change is needed
885 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
886 rxDevices = mPrimaryOutput->devices();
887 }
888 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200889 disconnectTelephonyAudioSource(mCallRxSourceClient);
890 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100891 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530892 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700893 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700894 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700895
jiabin3ff8d7d2022-12-13 06:27:44 +0000896 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700897 // reevaluate routing on all outputs in case tracks have been started during the call
898 for (size_t i = 0; i < mOutputs.size(); i++) {
899 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100900 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200901 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
902 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000903 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
904 // If the device is using preferred mixer attributes, the output need to reopen
905 // with default configuration when the new selected devices are different from
906 // current routing devices.
907 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
908 continue;
909 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530910 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200911 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700912 }
913 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000914 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700915
Eric Laurent96d1dda2022-03-14 17:14:19 +0100916 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
917
Eric Laurente552edb2014-03-10 17:42:56 -0700918 if (isStateInCall(state)) {
919 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700920 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800921 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700922 }
923
924 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100925 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
926 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700927}
928
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700929audio_mode_t AudioPolicyManager::getPhoneState() {
930 return mEngine->getPhoneState();
931}
932
Eric Laurente0720872014-03-11 09:30:41 -0700933void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100934 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700935{
François Gaffie2110e042015-03-24 08:41:51 +0100936 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700937 if (config == mEngine->getForceUse(usage)) {
938 return;
939 }
Eric Laurente552edb2014-03-10 17:42:56 -0700940
François Gaffie2110e042015-03-24 08:41:51 +0100941 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
942 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
943 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700944 }
François Gaffie2110e042015-03-24 08:41:51 +0100945 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
946 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
947 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700948
949 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700950 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800951
Eric Laurent22fcda22019-05-17 16:28:47 -0700952 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
953 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800954 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700955 }
956
Eric Laurentdc462862016-07-19 12:29:53 -0700957 //FIXME: workaround for truncated touch sounds
958 // to be removed when the problem is handled by system UI
959 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700960 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
961 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
962 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700963
964 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100965 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700966}
967
Eric Laurente0720872014-03-11 09:30:41 -0700968void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700969{
970 ALOGV("setSystemProperty() property %s, value %s", property, value);
971}
972
Dorin Drimusecc9f422022-03-09 17:57:40 +0100973// Find an MSD output profile compatible with the parameters passed.
974// When "directOnly" is set, restrict search to profiles for direct outputs.
975sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
976 const DeviceVector& devices,
977 uint32_t samplingRate,
978 audio_format_t format,
979 audio_channel_mask_t channelMask,
980 audio_output_flags_t flags,
981 bool directOnly)
982{
983 flags = getRelevantFlags(flags, directOnly);
984
985 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
986 if (msdModule != nullptr) {
987 // for the msd module check if there are patches to the output devices
988 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
989 HwModuleCollection modules;
990 modules.add(msdModule);
991 return searchCompatibleProfileHwModules(
992 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
993 flags, directOnly);
994 }
995 }
996 return nullptr;
997}
998
Michael Chana94fbb22018-04-24 14:31:19 +1000999// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1000// search to profiles for direct outputs.
1001sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001002 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001003 uint32_t samplingRate,
1004 audio_format_t format,
1005 audio_channel_mask_t channelMask,
1006 audio_output_flags_t flags,
1007 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001008{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001009 flags = getRelevantFlags(flags, directOnly);
1010
1011 return searchCompatibleProfileHwModules(
1012 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1013}
1014
1015audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1016 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001017 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001018 // only retain flags that will drive the direct output profile selection
1019 // if explicitly requested
1020 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001021 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001022 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1023 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001024 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001025 return flags;
1026}
Eric Laurent861a6282015-05-18 15:40:16 -07001027
Dorin Drimusecc9f422022-03-09 17:57:40 +01001028sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1029 const HwModuleCollection& hwModules,
1030 const DeviceVector& devices,
1031 uint32_t samplingRate,
1032 audio_format_t format,
1033 audio_channel_mask_t channelMask,
1034 audio_output_flags_t flags,
1035 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001036 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001037 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001038 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001039 if (!curProfile->isCompatibleProfile(devices,
1040 samplingRate, NULL /*updatedSamplingRate*/,
1041 format, NULL /*updatedFormat*/,
1042 channelMask, NULL /*updatedChannelMask*/,
1043 flags)) {
1044 continue;
1045 }
1046 // reject profiles not corresponding to a device currently available
1047 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1048 continue;
1049 }
1050 // reject profiles if connected device does not support codec
1051 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1052 continue;
1053 }
1054 if (!directOnly) {
1055 return curProfile;
1056 }
1057
1058 // when searching for direct outputs, if several profiles are compatible, give priority
1059 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001060 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001061 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001062 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001063 }
1064 profile = curProfile;
1065 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1066 break;
1067 }
Eric Laurente552edb2014-03-10 17:42:56 -07001068 }
1069 }
Eric Laurent861a6282015-05-18 15:40:16 -07001070 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001071}
1072
Eric Laurentfa0f6742021-08-17 18:39:44 +02001073sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001074 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001075{
1076 for (const auto& hwModule : mHwModules) {
1077 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001078 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001079 continue;
1080 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001081 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001082 // reject profiles not corresponding to a device currently available
1083 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1084 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1085 continue;
1086 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001087 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1088 != devices.size()) {
1089 continue;
1090 }
1091 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001092 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1093 return curProfile;
1094 }
1095 }
1096 return nullptr;
1097}
1098
Eric Laurentf4e63452017-11-06 19:31:46 +00001099audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001100{
François Gaffiec005e562018-11-06 15:04:49 +01001101 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001102
1103 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1104 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1105 // format, flags, etc. This may result in some discrepancy for functions that utilize
1106 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1107 // and AudioSystem::getOutputSamplingRate().
1108
François Gaffie11d30102018-11-02 16:09:09 +01001109 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001110 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1111 if (stream == AUDIO_STREAM_MUSIC &&
1112 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1113 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1114 }
1115 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001116
François Gaffie11d30102018-11-02 16:09:09 +01001117 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1118 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001119 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001120}
1121
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001122status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1123 const audio_attributes_t *srcAttr,
1124 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001125{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001126 if (srcAttr != NULL) {
1127 if (!isValidAttributes(srcAttr)) {
1128 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1129 __func__,
1130 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1131 srcAttr->tags);
1132 return BAD_VALUE;
1133 }
1134 *dstAttr = *srcAttr;
1135 } else {
1136 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1137 ALOGE("%s: invalid stream type", __func__);
1138 return BAD_VALUE;
1139 }
François Gaffiec005e562018-11-06 15:04:49 +01001140 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001141 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001142
1143 // Only honor audibility enforced when required. The client will be
1144 // forced to reconnect if the forced usage changes.
1145 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001146 dstAttr->flags = static_cast<audio_flags_mask_t>(
1147 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001148 }
1149
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001150 return NO_ERROR;
1151}
1152
Kevin Rocard153f92d2018-12-18 18:33:28 -08001153status_t AudioPolicyManager::getOutputForAttrInt(
1154 audio_attributes_t *resultAttr,
1155 audio_io_handle_t *output,
1156 audio_session_t session,
1157 const audio_attributes_t *attr,
1158 audio_stream_type_t *stream,
1159 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001160 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001161 audio_output_flags_t *flags,
1162 audio_port_handle_t *selectedDeviceId,
1163 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001164 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001165 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001166 bool *isSpatialized,
1167 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001168{
François Gaffiec005e562018-11-06 15:04:49 +01001169 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001170 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001171 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001172 const sp<DeviceDescriptor> requestedDevice =
1173 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1174
Eric Laurent8a1095a2019-11-08 14:44:16 -08001175 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001176 *isSpatialized = false;
1177
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001178 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1179 if (status != NO_ERROR) {
1180 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001181 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001182 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001183 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001184 }
François Gaffiec005e562018-11-06 15:04:49 +01001185 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001186
François Gaffiec005e562018-11-06 15:04:49 +01001187 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1188 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001189
Oscar Azucena873d10f2023-01-12 18:34:42 -08001190 bool usePrimaryOutputFromPolicyMixes = false;
1191
Kevin Rocard153f92d2018-12-18 18:33:28 -08001192 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1193 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1194 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001195 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001196 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1197 .channel_mask = config->channel_mask,
1198 .format = config->format,
1199 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001200 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001201 mAvailableOutputDevices, requestedDevice, primaryMix,
1202 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001203 if (status != OK) {
1204 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001205 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001206
Kevin Rocard153f92d2018-12-18 18:33:28 -08001207 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001208 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1209 && !audio_is_linear_pcm(config->format)) {
1210 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001211 return BAD_VALUE;
1212 }
1213 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001214 sp<DeviceDescriptor> deviceDesc =
1215 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1216 primaryMix->mDeviceAddress,
1217 AUDIO_FORMAT_DEFAULT);
1218 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001219 bool tryDirectForFlags = policyDesc == nullptr ||
1220 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1221 // if a direct output can be opened to deliver the track's multi-channel content to the
1222 // output rather than being downmixed by the primary output, then use this direct
1223 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1224 // mix.
1225 bool tryDirectForChannelMask = policyDesc != nullptr
1226 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1227 audio_channel_count_from_out_mask(config->channel_mask));
1228 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001229 audio_io_handle_t newOutput;
1230 status = openDirectOutput(
1231 *stream, session, config,
1232 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1233 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001234 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001235 policyDesc = mOutputs.valueFor(newOutput);
1236 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001237 } else if (tryDirectForFlags) {
1238 policyDesc = nullptr;
1239 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001240 }
1241 if (policyDesc != nullptr) {
1242 policyDesc->mPolicyMix = primaryMix;
1243 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001244 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001245
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001246 ALOGV("getOutputForAttr() returns output %d", *output);
1247 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1248 *outputType = API_OUT_MIX_PLAYBACK;
1249 } else {
1250 *outputType = API_OUTPUT_LEGACY;
1251 }
1252 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001253 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001254 }
François Gaffiec005e562018-11-06 15:04:49 +01001255 // Virtual sources must always be dynamicaly or explicitly routed
1256 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1257 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1258 return BAD_VALUE;
1259 }
1260 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1261 // in order to let the choice of the order to future vendor engine
1262 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001263
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001264 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001265 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001266 }
1267
Nadav Barb2f18162018-07-18 13:01:53 +03001268 // Set incall music only if device was explicitly set, and fallback to the device which is
1269 // chosen by the engine if not.
1270 // FIXME: provide a more generic approach which is not device specific and move this back
1271 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001272 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001273 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001274 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001275 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001276 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001277 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001278 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001279 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001280 }
1281 }
1282
François Gaffiec005e562018-11-06 15:04:49 +01001283 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1284 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1285 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001286
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001287 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001288 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001289 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001290 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001291 ALOGV("%s() Using MSD devices %s instead of devices %s",
1292 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001293 } else {
1294 *output = AUDIO_IO_HANDLE_NONE;
1295 }
1296 }
1297 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001298 sp<PreferredMixerAttributesInfo> info = nullptr;
1299 if (outputDevices.size() == 1) {
1300 info = getPreferredMixerAttributesInfo(
1301 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001302 mEngine->getProductStrategyForAttributes(*resultAttr),
1303 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001304 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1305 // and it is currently active.
1306 if (info != nullptr && info->getUid() != uid &&
1307 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1308 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001309 info = nullptr;
1310 }
1311 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001312 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001313 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001314 // The client will be active if the client is currently preferred mixer owner and the
1315 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001316 *isBitPerfect = (info != nullptr
1317 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001318 && info->getUid() == uid
1319 && *output != AUDIO_IO_HANDLE_NONE
1320 // When bit-perfect output is selected for the preferred mixer attributes owner,
1321 // only need to consider the config matches.
1322 && mOutputs.valueFor(*output)->isConfigurationMatched(
1323 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001324 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001325 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001326 AudioProfileVector profiles;
1327 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1328 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001329 const auto channels = profiles[0]->getChannels();
1330 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1331 config->channel_mask = *channels.begin();
1332 }
1333 const auto sampleRates = profiles[0]->getSampleRates();
1334 if (!sampleRates.empty() &&
1335 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1336 config->sample_rate = *sampleRates.begin();
1337 }
jiabinf1c73972022-04-14 16:28:52 -07001338 config->format = profiles[0]->getFormat();
1339 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001340 return INVALID_OPERATION;
1341 }
Paul McLeanaa981192015-03-21 09:55:15 -07001342
François Gaffiec005e562018-11-06 15:04:49 +01001343 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001344 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001345 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001346 *selectedDeviceId = outputDevice->getId();
1347 break;
1348 }
1349 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001350
Eric Laurent8a1095a2019-11-08 14:44:16 -08001351 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1352 *outputType = API_OUTPUT_TELEPHONY_TX;
1353 } else {
1354 *outputType = API_OUTPUT_LEGACY;
1355 }
1356
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001357 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1358
1359 return NO_ERROR;
1360}
1361
1362status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1363 audio_io_handle_t *output,
1364 audio_session_t session,
1365 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001366 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001367 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001368 audio_output_flags_t *flags,
1369 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001370 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001371 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001372 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001373 bool *isSpatialized,
1374 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001375{
1376 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1377 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1378 return INVALID_OPERATION;
1379 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001380 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001381 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001382 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001383 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001384 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001385 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001386 const sp<DeviceDescriptor> requestedDevice =
1387 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1388
1389 // Prevent from storing invalid requested device id in clients
1390 const audio_port_handle_t sanitizedRequestedPortId =
1391 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1392 *selectedDeviceId = sanitizedRequestedPortId;
1393
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001394 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001395 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001396 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1397 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001398 if (status != NO_ERROR) {
1399 return status;
1400 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001401 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001402 if (secondaryOutputs != nullptr) {
1403 for (auto &secondaryMix : secondaryMixes) {
1404 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1405 if (outputDesc != nullptr &&
1406 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1407 secondaryOutputs->push_back(outputDesc->mIoHandle);
1408 weakSecondaryOutputDescs.push_back(outputDesc);
1409 }
1410 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001411 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001412
Eric Laurent8fc147b2018-07-22 19:13:55 -07001413 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001414 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001415 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001416 };
jiabin4ef93452019-09-10 14:29:54 -07001417 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001418
Eric Laurentc209fe42020-06-05 18:11:23 -07001419 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001420 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001421 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001422 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001423 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001424 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001425 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001426 std::move(weakSecondaryOutputDescs),
1427 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001428 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001429
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001430 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1431 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001432
Eric Laurente83b55d2014-11-14 10:06:21 -08001433 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001434}
1435
Eric Laurentc529cf62020-04-17 18:19:10 -07001436status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1437 audio_session_t session,
1438 const audio_config_t *config,
1439 audio_output_flags_t flags,
1440 const DeviceVector &devices,
1441 audio_io_handle_t *output) {
1442
1443 *output = AUDIO_IO_HANDLE_NONE;
1444
1445 // skip direct output selection if the request can obviously be attached to a mixed output
1446 // and not explicitly requested
1447 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1448 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1449 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1450 return NAME_NOT_FOUND;
1451 }
1452
1453 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1454 // This prevents creating an offloaded track and tearing it down immediately after start
1455 // when audioflinger detects there is an active non offloadable effect.
1456 // FIXME: We should check the audio session here but we do not have it in this context.
1457 // This may prevent offloading in rare situations where effects are left active by apps
1458 // in the background.
1459 sp<IOProfile> profile;
1460 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1461 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1462 profile = getProfileForOutput(
1463 devices, config->sample_rate, config->format, config->channel_mask,
1464 flags, true /* directOnly */);
1465 }
1466
1467 if (profile == nullptr) {
1468 return NAME_NOT_FOUND;
1469 }
1470
1471 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1472 for (size_t i = 0; i < mOutputs.size(); i++) {
1473 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1474 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1475 // reuse direct output if currently open by the same client
1476 // and configured with same parameters
1477 if ((config->sample_rate == desc->getSamplingRate()) &&
1478 (config->format == desc->getFormat()) &&
1479 (config->channel_mask == desc->getChannelMask()) &&
1480 (session == desc->mDirectClientSession)) {
1481 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001482 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001483 mOutputs.keyAt(i), session);
1484 *output = mOutputs.keyAt(i);
1485 return NO_ERROR;
1486 }
1487 }
1488 }
1489
1490 if (!profile->canOpenNewIo()) {
1491 return NAME_NOT_FOUND;
1492 }
1493
1494 sp<SwAudioOutputDescriptor> outputDesc =
1495 new SwAudioOutputDescriptor(profile, mpClientInterface);
1496
Michael Chan6fb34492020-12-08 15:44:49 +11001497 // An MSD patch may be using the only output stream that can service this request. Release
1498 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001499 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001500
Eric Laurentf1f22e72021-07-13 14:04:14 +02001501 status_t status =
1502 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001503
1504 // only accept an output with the requested parameters
1505 if (status != NO_ERROR ||
1506 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1507 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1508 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1509 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1510 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1511 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1512 config->channel_mask, outputDesc->getChannelMask());
1513 if (*output != AUDIO_IO_HANDLE_NONE) {
1514 outputDesc->close();
1515 }
1516 // fall back to mixer output if possible when the direct output could not be open
1517 if (audio_is_linear_pcm(config->format) &&
1518 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1519 return NAME_NOT_FOUND;
1520 }
1521 *output = AUDIO_IO_HANDLE_NONE;
1522 return BAD_VALUE;
1523 }
1524 outputDesc->mDirectOpenCount = 1;
1525 outputDesc->mDirectClientSession = session;
1526
1527 addOutput(*output, outputDesc);
1528 mPreviousOutputs = mOutputs;
1529 ALOGV("%s returns new direct output %d", __func__, *output);
1530 mpClientInterface->onAudioPortListUpdate();
1531 return NO_ERROR;
1532}
1533
François Gaffie11d30102018-11-02 16:09:09 +01001534audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1535 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001536 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001537 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001538 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001539 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001540 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001541 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001542 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001543{
Andy Hungc88b0642018-04-27 15:42:35 -07001544 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001545
jiabine375d412019-02-26 12:54:53 -08001546 // Discard haptic channel mask when forcing muting haptic channels.
1547 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001548 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1549 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001550
Eric Laurente552edb2014-03-10 17:42:56 -07001551 // open a direct output if required by specified parameters
1552 //force direct flag if offload flag is set: offloading implies a direct output stream
1553 // and all common behaviors are driven by checking only the direct flag
1554 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001555 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1556 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001557 }
Nadav Bar766fb022018-01-07 12:18:03 +02001558 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1559 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001560 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001561
1562 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1563
Eric Laurente83b55d2014-11-14 10:06:21 -08001564 // only allow deep buffering for music stream type
1565 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001566 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001567 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001568 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001569 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1570 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001571 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001572 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001573 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001574 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001575 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001576 audio_is_linear_pcm(config->format) &&
1577 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001578 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001579 AUDIO_OUTPUT_FLAG_DIRECT);
1580 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001581 }
Eric Laurente552edb2014-03-10 17:42:56 -07001582
Carter Hsua3abb402021-10-26 11:11:20 +08001583 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1584 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1585 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1586 }
1587
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001588 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001589 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001590 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001591 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001592 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001593 }
1594
Eric Laurentc529cf62020-04-17 18:19:10 -07001595 audio_config_t directConfig = *config;
1596 directConfig.channel_mask = channelMask;
1597 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1598 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001599 return output;
1600 }
1601
Eric Laurent14cbfca2016-03-17 09:42:16 -07001602 // A request for HW A/V sync cannot fallback to a mixed output because time
1603 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001604 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001605 return AUDIO_IO_HANDLE_NONE;
1606 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001607 // A request for Tuner cannot fallback to a mixed output
1608 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1609 return AUDIO_IO_HANDLE_NONE;
1610 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001611
Eric Laurente552edb2014-03-10 17:42:56 -07001612 // ignoring channel mask due to downmix capability in mixer
1613
1614 // open a non direct output
1615
1616 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001617 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001618 // get which output is suitable for the specified stream. The actual
1619 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001620 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001621 if (prefMixerConfigInfo != nullptr) {
1622 for (audio_io_handle_t outputHandle : outputs) {
1623 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1624 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1625 output = outputHandle;
1626 break;
1627 }
1628 }
1629 if (output == AUDIO_IO_HANDLE_NONE) {
1630 // No output open with the preferred profile. Open a new one.
1631 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1632 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1633 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1634 config.format = prefMixerConfigInfo->getConfigBase().format;
1635 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1636 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1637 &config, prefMixerConfigInfo->getFlags());
1638 if (preferredOutput == nullptr) {
1639 ALOGE("%s failed to open output with preferred mixer config", __func__);
1640 } else {
1641 output = preferredOutput->mIoHandle;
1642 }
1643 }
1644 } else {
1645 // at this stage we should ignore the DIRECT flag as no direct output could be
1646 // found earlier
1647 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1648 output = selectOutput(
1649 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1650 }
Eric Laurente552edb2014-03-10 17:42:56 -07001651 }
François Gaffie11d30102018-11-02 16:09:09 +01001652 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001653 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001654 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001655
Eric Laurente552edb2014-03-10 17:42:56 -07001656 return output;
1657}
1658
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001659sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001660 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1661 mAvailableInputDevices);
1662 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1663}
1664
1665DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1666 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1667 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001668}
1669
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001670const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001671 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001672 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1673 if (msdModule != 0) {
1674 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1675 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1676 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1677 const struct audio_port_config *source = &patch->mPatch.sources[j];
1678 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1679 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001680 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001681 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001682 }
1683 }
1684 }
1685 return msdPatches;
1686}
1687
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001688bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1689 ssize_t index = mAudioPatches.indexOfKey(handle);
1690 if (index < 0) {
1691 return false;
1692 }
1693 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1694 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1695 if (msdModule == nullptr) {
1696 return false;
1697 }
1698 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1699 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1700 return true;
1701 }
1702 index = getMsdOutputPatches().indexOfKey(handle);
1703 if (index < 0) {
1704 return false;
1705 }
1706 return true;
1707}
1708
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001709status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1710 const InputProfileCollection &inputProfiles,
1711 const OutputProfileCollection &outputProfiles,
1712 const sp<DeviceDescriptor> &sourceDevice,
1713 const sp<DeviceDescriptor> &sinkDevice,
1714 AudioProfileVector& sourceProfiles,
1715 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001716 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001717 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001718 return NO_INIT;
1719 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001720 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001721 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001722 return NO_INIT;
1723 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001725 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1726 inProfile->supportsDevice(sourceDevice)) {
1727 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001728 }
1729 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001730 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001731 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001732 outProfile->supportsDevice(sinkDevice)) {
1733 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001734 }
1735 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001736 return NO_ERROR;
1737}
1738
1739status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1740 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1741 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1742{
Dean Wheatley16809da2022-12-09 14:55:46 +11001743 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1744 static const std::vector<audio_format_t> formatsOrder = {{
1745 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
1746 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
1747 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1748 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1749 // preferred).
1750 std::vector<audio_channel_mask_t> masks = {{
1751 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1752 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1753 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1754 // insert index masks (higher counts most preferred) as preferred over position masks
1755 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1756 masks.insert(
1757 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1758 }
1759 return masks;
1760 }();
1761
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001762 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001763 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1764 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001765 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001766 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1767 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001768 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001769 }
1770 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1771 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1772 sinkConfig->format = bestSinkConfig.format;
1773 // For encoded streams force direct flag to prevent downstream mixing.
1774 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1775 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001776 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1777 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001778 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001779 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1780 // raw and IEC61937 framed streams.
1781 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1782 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1783 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001784 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1785 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001786 sourceConfig->channel_mask =
1787 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1788 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1789 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001790 sourceConfig->format = bestSinkConfig.format;
1791 // Copy input stream directly without any processing (e.g. resampling).
1792 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1793 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1794 if (hwAvSync) {
1795 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1796 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1797 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1798 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1799 }
1800 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1801 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1802 sinkConfig->config_mask |= config_mask;
1803 sourceConfig->config_mask |= config_mask;
1804 return NO_ERROR;
1805}
1806
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001807PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1808 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001809{
1810 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001811 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1812 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1813 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1814 if (deviceModule == nullptr) {
1815 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1816 return patchBuilder;
1817 }
1818 const InputProfileCollection inputProfiles = msdIsSource ?
1819 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1820 const OutputProfileCollection outputProfiles = msdIsSource ?
1821 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1822
1823 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1824 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1825 device : getMsdAudioOutDevices().itemAt(0);
1826 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1827
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001828 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1829 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001830 AudioProfileVector sourceProfiles;
1831 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1833 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001834 for (auto hwAvSync : { true, false }) {
1835 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1836 sourceProfiles, sinkProfiles) != NO_ERROR) {
1837 continue;
1838 }
1839 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1840 &sinkConfig) == NO_ERROR) {
1841 // Found a matching config. Re-create PatchBuilder with this config.
1842 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1843 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001844 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001845 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001846 " supporting PCM format conversion.", __func__);
1847 return patchBuilder;
1848}
1849
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001850status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001851 DeviceVector devices;
1852 if (outputDevices != nullptr && outputDevices->size() > 0) {
1853 devices.add(*outputDevices);
1854 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001855 // Use media strategy for unspecified output device. This should only
1856 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1857 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001858 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001859 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001860 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001861 }
Michael Chan6fb34492020-12-08 15:44:49 +11001862 std::vector<PatchBuilder> patchesToCreate;
1863 for (auto i = 0u; i < devices.size(); ++i) {
1864 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001865 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001866 }
1867 // Retain only the MSD patches associated with outputDevices request.
1868 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001869 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001870 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1871 auto retainedPatch = false;
1872 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1873 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1874 patchesToRemove.removeItemsAt(i);
1875 retainedPatch = true;
1876 break;
1877 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001878 }
Michael Chan6fb34492020-12-08 15:44:49 +11001879 if (retainedPatch) {
1880 it = patchesToCreate.erase(it);
1881 continue;
1882 }
1883 ++it;
1884 }
1885 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1886 return NO_ERROR;
1887 }
1888 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1889 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001890 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001891 }
Michael Chan6fb34492020-12-08 15:44:49 +11001892 status_t status = NO_ERROR;
1893 for (const auto &p : patchesToCreate) {
1894 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1895 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1896 char message[256];
1897 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1898 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1899 currStatus == NO_ERROR ? "Success" : "Error",
1900 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1901 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1902 if (currStatus == NO_ERROR) {
1903 ALOGD("%s", message);
1904 } else {
1905 ALOGE("%s", message);
1906 if (status == NO_ERROR) {
1907 status = currStatus;
1908 }
1909 }
1910 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001911 return status;
1912}
1913
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001914void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1915 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001916 for (size_t i = 0; i < msdPatches.size(); i++) {
1917 const auto& patch = msdPatches[i];
1918 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1919 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1920 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1921 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1922 releaseAudioPatch(patch->getHandle(), mUidCached);
1923 break;
1924 }
1925 }
1926 }
1927}
1928
Dorin Drimus94d94412022-02-02 09:05:02 +01001929bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001930 DeviceVector devicesToCheck =
1931 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001932 AudioPatchCollection msdPatches = getMsdOutputPatches();
1933 for (size_t i = 0; i < msdPatches.size(); i++) {
1934 const auto& patch = msdPatches[i];
1935 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1936 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1937 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1938 const auto& foundDevice = devicesToCheck.getDevice(
1939 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1940 if (foundDevice != nullptr) {
1941 devicesToCheck.remove(foundDevice);
1942 if (devicesToCheck.isEmpty()) {
1943 return true;
1944 }
1945 }
1946 }
1947 }
1948 }
1949 return false;
1950}
1951
Eric Laurente0720872014-03-11 09:30:41 -07001952audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001953 audio_output_flags_t flags,
1954 audio_format_t format,
1955 audio_channel_mask_t channelMask,
1956 uint32_t samplingRate,
1957 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001958{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001959 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1960 "%s called with format %#x", __func__, format);
1961
jiabinebb6af42020-06-09 17:31:17 -07001962 // Return the output that haptic-generating attached to when 1) session id is specified,
1963 // 2) haptic-generating effect exists for given session id and 3) the output that
1964 // haptic-generating effect attached to is in given outputs.
1965 if (sessionId != AUDIO_SESSION_NONE) {
1966 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1967 sessionId, FX_IID_HAPTICGENERATOR);
1968 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1969 return hapticGeneratingOutput;
1970 }
1971 }
1972
Eric Laurent16c66dd2019-05-01 17:54:10 -07001973 // Flags disqualifying an output: the match must happen before calling selectOutput()
1974 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1975 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1976
1977 // Flags expressing a functional request: must be honored in priority over
1978 // other criteria
1979 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1980 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001981 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1982 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001983 // Flags expressing a performance request: have lower priority than serving
1984 // requested sampling rate or channel mask
1985 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1986 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1987 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1988
1989 const audio_output_flags_t functionalFlags =
1990 (audio_output_flags_t)(flags & kFunctionalFlags);
1991 const audio_output_flags_t performanceFlags =
1992 (audio_output_flags_t)(flags & kPerformanceFlags);
1993
1994 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1995
Eric Laurente552edb2014-03-10 17:42:56 -07001996 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001997 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001998 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001999 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002000 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002001 // with tiebreak preferring the minimum number of extra functional flags
2002 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002003 // 3: the output supporting the exact channel mask
2004 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002005 // 5: the output with the highest sampling rate if the requested sample rate is
2006 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002007 // 6: the output with the highest number of requested performance flags
2008 // 7: the output with the bit depth the closest to the requested one
2009 // 8: the primary output
2010 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002011
Eric Laurent16c66dd2019-05-01 17:54:10 -07002012 // matching criteria values in priority order for best matching output so far
2013 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002014
Eric Laurent16c66dd2019-05-01 17:54:10 -07002015 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2016 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2017 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002018
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002019 for (audio_io_handle_t output : outputs) {
2020 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002021 // matching criteria values in priority order for current output
2022 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002023
Eric Laurent16c66dd2019-05-01 17:54:10 -07002024 if (outputDesc->isDuplicated()) {
2025 continue;
2026 }
2027 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2028 continue;
2029 }
Eric Laurent8838a382014-09-08 16:44:28 -07002030
Eric Laurent16c66dd2019-05-01 17:54:10 -07002031 // If haptic channel is specified, use the haptic output if present.
2032 // When using haptic output, same audio format and sample rate are required.
2033 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002034 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002035 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2036 continue;
2037 }
2038 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002039 && format == outputDesc->getFormat()
2040 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002041 currentMatchCriteria[0] = outputHapticChannelCount;
2042 }
2043
2044 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002045 const int matchingFunctionalFlags =
2046 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2047 const int totalFunctionalFlags =
2048 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2049 // Prefer matching functional flags, but subtract unnecessary functional flags.
2050 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002051
2052 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002053 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2054 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002055 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2056 channelCount <= outputChannelCount) {
2057 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002058 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2059 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002060 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002061 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002062 currentMatchCriteria[3] = outputChannelCount;
2063 }
2064
2065 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002066 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002067 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002068 }
2069
2070 // performance flags match
2071 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2072
2073 // format match
2074 if (format != AUDIO_FORMAT_INVALID) {
2075 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002076 PolicyAudioPort::kFormatDistanceMax -
2077 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002078 }
2079
2080 // primary output match
2081 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2082
2083 // compare match criteria by priority then value
2084 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2085 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2086 bestMatchCriteria = currentMatchCriteria;
2087 bestOutput = output;
2088
2089 std::stringstream result;
2090 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2091 std::ostream_iterator<int>(result, " "));
2092 ALOGV("%s new bestOutput %d criteria %s",
2093 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002094 }
2095 }
2096
Eric Laurent16c66dd2019-05-01 17:54:10 -07002097 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002098}
2099
Eric Laurent8fc147b2018-07-22 19:13:55 -07002100status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002101{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002102 ALOGV("%s portId %d", __FUNCTION__, portId);
2103
2104 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2105 if (outputDesc == 0) {
2106 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002107 return BAD_VALUE;
2108 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002109 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002110
Eric Laurent8fc147b2018-07-22 19:13:55 -07002111 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002112 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002113
Eric Laurent733ce942017-12-07 12:18:25 -08002114 status_t status = outputDesc->start();
2115 if (status != NO_ERROR) {
2116 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002117 }
2118
Eric Laurent97ac8712018-07-27 18:59:02 -07002119 uint32_t delayMs;
2120 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002121
2122 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002123 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002124 if (status == DEAD_OBJECT) {
2125 sp<SwAudioOutputDescriptor> desc =
2126 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2127 if (desc == nullptr) {
2128 // This is not common, it may indicate something wrong with the HAL.
2129 ALOGE("%s unable to open output with default config", __func__);
2130 return status;
2131 }
2132 desc->mUsePreferredMixerAttributes = true;
2133 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002134 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002135 }
jiabina84c3d32022-12-02 18:59:55 +00002136
2137 // If the client is the first one active on preferred mixer parameters, reopen the output
2138 // if the current mixer parameters doesn't match the preferred one.
2139 if (outputDesc->devices().size() == 1) {
2140 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2141 outputDesc->devices()[0]->getId(), client->strategy());
2142 if (info != nullptr && info->getUid() == client->uid()) {
2143 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2144 info->getConfigBase(), info->getFlags())) {
2145 stopSource(outputDesc, client);
2146 outputDesc->stop();
2147 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2148 config.channel_mask = info->getConfigBase().channel_mask;
2149 config.sample_rate = info->getConfigBase().sample_rate;
2150 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002151 sp<SwAudioOutputDescriptor> desc =
2152 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2153 if (desc == nullptr) {
2154 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002155 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002156 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002157 // Intentionally return error to let the client side resending request for
2158 // creating and starting.
2159 return DEAD_OBJECT;
2160 }
2161 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002162 if (info->getActiveClientCount() == 1 &&
2163 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2164 // If it is first bit-perfect client, reroute all clients that will be routed to
2165 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2166 PortHandleVector clientsToInvalidate;
2167 for (size_t i = 0; i < mOutputs.size(); i++) {
2168 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002169 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002170 continue;
2171 }
2172 for (const auto& c : mOutputs[i]->getClientIterable()) {
2173 clientsToInvalidate.push_back(c->portId());
2174 }
2175 }
2176 if (!clientsToInvalidate.empty()) {
2177 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2178 __func__);
2179 mpClientInterface->invalidateTracks(clientsToInvalidate);
2180 }
2181 }
jiabina84c3d32022-12-02 18:59:55 +00002182 }
2183 }
2184
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002185 if (client->hasPreferredDevice()) {
2186 // playback activity with preferred device impacts routing occurred, inform upper layers
2187 mpClientInterface->onRoutingUpdated();
2188 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002189 if (delayMs != 0) {
2190 usleep(delayMs * 1000);
2191 }
2192
2193 return status;
2194}
2195
Eric Laurent96d1dda2022-03-14 17:14:19 +01002196bool AudioPolicyManager::isLeUnicastActive() const {
2197 if (isInCall()) {
2198 return true;
2199 }
2200 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2201}
2202
2203bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2204 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2205 return false;
2206 }
2207 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2208 ALOGV("%s active %d", __func__, active);
2209 return active;
2210}
2211
Eric Laurent97ac8712018-07-27 18:59:02 -07002212status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2213 const sp<TrackClientDescriptor>& client,
2214 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002215{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002216 // cannot start playback of STREAM_TTS if any other output is being used
2217 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002218
2219 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002220 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002221 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002222 auto clientStrategy = client->strategy();
2223 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002224 if (stream == AUDIO_STREAM_TTS) {
2225 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002226 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002227 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002228 return INVALID_OPERATION;
2229 } else {
2230 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2231 }
2232 } else {
2233 // some playback other than beacon starts
2234 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2235 }
2236
Eric Laurent77305a62016-07-25 16:39:22 -07002237 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002238 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002239 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002240
François Gaffie11d30102018-11-02 16:09:09 +01002241 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002242 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002243 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002244 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002245 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002246 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002247 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002248 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002249 } else {
2250 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002251 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002252 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2253 AUDIO_FORMAT_DEFAULT);
2254 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2255 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002256 }
2257
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002258 // requiresMuteCheck is false when we can bypass mute strategy.
2259 // It covers a common case when there is no materially active audio
2260 // and muting would result in unnecessary delay and dropped audio.
2261 const uint32_t outputLatencyMs = outputDesc->latency();
2262 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002263 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002264
Eric Laurente552edb2014-03-10 17:42:56 -07002265 // increment usage count for this stream on the requested output:
2266 // NOTE that the usage count is the same for duplicated output and hardware output which is
2267 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002268 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002269
2270 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002271 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002272 // Preferred device may be exclusive, use only if no other active clients on this output
2273 devices = DeviceVector(
2274 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2275 } else {
2276 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2277 }
François Gaffie11d30102018-11-02 16:09:09 +01002278 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002279 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002280 }
2281 }
Eric Laurente552edb2014-03-10 17:42:56 -07002282
François Gaffiec005e562018-11-06 15:04:49 +01002283 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002284 selectOutputForMusicEffects();
2285 }
2286
François Gaffie1c878552018-11-22 16:53:21 +01002287 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002288 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002289 if (devices.isEmpty()) {
2290 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002291 }
François Gaffiec005e562018-11-06 15:04:49 +01002292 bool shouldWait =
2293 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2294 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2295 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002296 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002297 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002298 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002299 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002300 // An output has a shared device if
2301 // - managed by the same hw module
2302 // - supports the currently selected device
2303 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002304 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002305
Eric Laurent77305a62016-07-25 16:39:22 -07002306 // force a device change if any other output is:
2307 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002308 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002309 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002310 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002311 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002312 // change the device currently selected by the other output.
2313 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002314 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002315 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002316 force = true;
2317 }
2318 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002319 // a notification so that audio focus effect can propagate, or that a mute/unmute
2320 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002321 const uint32_t latencyMs = desc->latency();
2322 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2323
2324 if (shouldWait && isActive && (waitMs < latencyMs)) {
2325 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002326 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002327
2328 // Require mute check if another output is on a shared device
2329 // and currently active to have proper drain and avoid pops.
2330 // Note restoring AudioTracks onto this output needs to invoke
2331 // a volume ramp if there is no mute.
2332 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002333 }
2334 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002335
jiabin3ff8d7d2022-12-13 06:27:44 +00002336 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2337 // If the output is open with preferred mixer attributes, but the routed device is
2338 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2339 // changed.
2340 return DEAD_OBJECT;
2341 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002342 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302343 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2344 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002345
Eric Laurente552edb2014-03-10 17:42:56 -07002346 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002347 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002348 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002349 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002350 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002351 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002352 outputDesc->useHwGain() /*force*/)) {
2353 // request AudioService to reinitialize the volume curves asynchronously
2354 ALOGE("checkAndSetVolume failed, requesting volume range init");
2355 mpClientInterface->onVolumeRangeInitRequest();
2356 };
Eric Laurente552edb2014-03-10 17:42:56 -07002357
2358 // update the outputs if starting an output with a stream that can affect notification
2359 // routing
2360 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002361
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002362 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002363 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002364 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002365 }
Eric Laurentdc462862016-07-19 12:29:53 -07002366
2367 if (waitMs > muteWaitMs) {
2368 *delayMs = waitMs - muteWaitMs;
2369 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002370
2371 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2372 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2373 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2374 // change occurs after the MixerThread starts and causes a stream volume
2375 // glitch.
2376 //
2377 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002378 }
Eric Laurentdc462862016-07-19 12:29:53 -07002379
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002380 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002381 mEngine->getForceUse(
2382 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002383 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002384 }
2385
Eric Laurent97ac8712018-07-27 18:59:02 -07002386 // Automatically enable the remote submix input when output is started on a re routing mix
2387 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002388 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2389 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002390 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2391 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2392 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002393 "remote-submix",
2394 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002395 }
2396
Eric Laurent96d1dda2022-03-14 17:14:19 +01002397 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2398
Eric Laurente552edb2014-03-10 17:42:56 -07002399 return NO_ERROR;
2400}
2401
Eric Laurent96d1dda2022-03-14 17:14:19 +01002402void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2403 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2404 bool isUnicastActive = isLeUnicastActive();
2405
2406 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002407 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002408 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2409 for (size_t i = 0; i < mOutputs.size(); i++) {
2410 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2411 if (desc != ignoredOutput && desc->isActive()
2412 && ((isUnicastActive &&
2413 !desc->devices().
2414 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2415 || (wasUnicastActive &&
2416 !desc->devices().getDevicesFromTypes(
2417 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2418 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2419 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002420 if (desc->mUsePreferredMixerAttributes && force) {
2421 // If the device is using preferred mixer attributes, the output need to reopen
2422 // with default configuration when the new selected devices are different from
2423 // current routing devices.
2424 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2425 continue;
2426 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302427 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002428 // re-apply device specific volume if not done by setOutputDevice()
2429 if (!force) {
2430 applyStreamVolumes(desc, newDevices.types(), delayMs);
2431 }
2432 }
2433 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002434 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002435 }
2436}
2437
Eric Laurent8fc147b2018-07-22 19:13:55 -07002438status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002439{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002440 ALOGV("%s portId %d", __FUNCTION__, portId);
2441
2442 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2443 if (outputDesc == 0) {
2444 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002445 return BAD_VALUE;
2446 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002447 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002448
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002449 if (client->hasPreferredDevice(true)) {
2450 // playback activity with preferred device impacts routing occurred, inform upper layers
2451 mpClientInterface->onRoutingUpdated();
2452 }
2453
Eric Laurent97ac8712018-07-27 18:59:02 -07002454 ALOGV("stopOutput() output %d, stream %d, session %d",
2455 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002456
Eric Laurent97ac8712018-07-27 18:59:02 -07002457 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002458
Eric Laurent733ce942017-12-07 12:18:25 -08002459 if (status == NO_ERROR ) {
2460 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002461 } else {
2462 return status;
2463 }
2464
2465 if (outputDesc->devices().size() == 1) {
2466 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2467 outputDesc->devices()[0]->getId(), client->strategy());
2468 if (info != nullptr && info->getUid() == client->uid()) {
2469 info->decreaseActiveClient();
2470 if (info->getActiveClientCount() == 0) {
2471 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2472 }
2473 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002474 }
2475 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002476}
2477
Eric Laurent97ac8712018-07-27 18:59:02 -07002478status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2479 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002480{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002481 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002482 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002483 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002484 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002485
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002486 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2487
François Gaffie1c878552018-11-22 16:53:21 +01002488 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2489 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002490 // Automatically disable the remote submix input when output is stopped on a
2491 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002492 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002493 if (isSingleDeviceType(
2494 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002495 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002496 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002497 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2498 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002499 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002500 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002501 }
2502 }
2503 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002504 if (client->hasPreferredDevice(true) &&
2505 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002506 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002507 forceDeviceUpdate = true;
2508 }
2509
Eric Laurente552edb2014-03-10 17:42:56 -07002510 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002511 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002512
Eric Laurente552edb2014-03-10 17:42:56 -07002513 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002514 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002515 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002516 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002517
2518 // If the routing does not change, if an output is routed on a device using HwGain
2519 // (aka setAudioPortConfig) and there are still active clients following different
2520 // volume group(s), force reapply volume
2521 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2522 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2523
Eric Laurente552edb2014-03-10 17:42:56 -07002524 // delay the device switch by twice the latency because stopOutput() is executed when
2525 // the track stop() command is received and at that time the audio track buffer can
2526 // still contain data that needs to be drained. The latency only covers the audio HAL
2527 // and kernel buffers. Also the latency does not always include additional delay in the
2528 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302529 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002530 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002531
2532 // force restoring the device selection on other active outputs if it differs from the
2533 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002534 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002535 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002536 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002537 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002538 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002539 desc->isActive() &&
2540 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002541 (newDevices != desc->devices())) {
2542 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2543 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002544
jiabin3ff8d7d2022-12-13 06:27:44 +00002545 if (desc->mUsePreferredMixerAttributes && force) {
2546 // If the device is using preferred mixer attributes, the output need to
2547 // reopen with default configuration when the new selected devices are
2548 // different from current routing devices.
2549 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2550 continue;
2551 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302552 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002553
Eric Laurent57de36c2016-09-28 16:59:11 -07002554 // re-apply device specific volume if not done by setOutputDevice()
2555 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002556 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002557 }
Eric Laurente552edb2014-03-10 17:42:56 -07002558 }
2559 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002560 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002561 // update the outputs if stopping one with a stream that can affect notification routing
2562 handleNotificationRoutingForStream(stream);
2563 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002564
2565 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2566 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002567 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002568 }
2569
François Gaffiec005e562018-11-06 15:04:49 +01002570 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002571 selectOutputForMusicEffects();
2572 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002573
2574 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2575
Eric Laurente552edb2014-03-10 17:42:56 -07002576 return NO_ERROR;
2577 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002578 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002579 return INVALID_OPERATION;
2580 }
2581}
2582
jiabinbce0c1d2020-10-05 11:20:18 -07002583bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002584{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002585 ALOGV("%s portId %d", __FUNCTION__, portId);
2586
2587 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2588 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002589 // If an output descriptor is closed due to a device routing change,
2590 // then there are race conditions with releaseOutput from tracks
2591 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2592 // destroyed shortly thereafter.
2593 //
2594 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002595 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002596 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002597 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002598
2599 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002600
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302601 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2602 if (outputDesc->isClientActive(client)) {
2603 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2604 stopOutput(portId);
2605 }
2606
Eric Laurent8fc147b2018-07-22 19:13:55 -07002607 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2608 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002609 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002610 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002611 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002612 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002613 if (--outputDesc->mDirectOpenCount == 0) {
2614 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002615 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002616 }
2617 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302618
Andy Hung39efb7a2018-09-26 15:39:28 -07002619 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002620 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2621 // The output is pending reopened to query dynamic profiles and
2622 // there is no active clients
2623 closeOutput(outputDesc->mIoHandle);
2624 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2625 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2626 if (newOutputDesc == nullptr) {
2627 ALOGE("%s failed to open output", __func__);
2628 }
2629 return true;
2630 }
2631 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002632}
2633
Eric Laurentcaf7f482014-11-25 17:50:47 -08002634status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2635 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002636 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002637 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002638 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002639 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002640 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002641 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002642 input_type_t *inputType,
2643 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002644{
François Gaffiec005e562018-11-06 15:04:49 +01002645 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002646 "flags %#x attributes=%s requested device ID %d",
2647 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2648 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002649
Eric Laurentad2e7b92017-09-14 20:06:42 -07002650 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002651 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002652 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002653 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002654 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002655 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002656 sp<RecordClientDescriptor> clientDesc;
2657 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002658 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002659 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002660
2661 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2662 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2663 return INVALID_OPERATION;
2664 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002665
Francois Gaffie716e1432019-01-14 16:58:59 +01002666 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2667 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002668 }
2669
Paul McLean466dc8e2015-04-17 13:15:36 -06002670 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002671 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002672 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002673
Eric Laurentad2e7b92017-09-14 20:06:42 -07002674 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2675 // possible
2676 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2677 *input != AUDIO_IO_HANDLE_NONE) {
2678 ssize_t index = mInputs.indexOfKey(*input);
2679 if (index < 0) {
2680 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2681 status = BAD_VALUE;
2682 goto error;
2683 }
2684 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002685 RecordClientVector clients = inputDesc->getClientsForSession(session);
2686 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002687 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2688 status = BAD_VALUE;
2689 goto error;
2690 }
2691 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2692 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002693 // corresponds to a new client and is only permitted from the same UID.
2694 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002695 if (clients.size() > 1) {
2696 for (const auto& client : clients) {
2697 // The client map is ordered by key values (portId) and portIds are allocated
2698 // incrementaly. So the first client in this list is the one opened by audio flinger
2699 // when the mmap stream is created and should be ignored as it does not correspond
2700 // to an actual client
2701 if (client == *clients.cbegin()) {
2702 continue;
2703 }
2704 if (uid != client->uid() && !client->isSilenced()) {
2705 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2706 uid, client->portId(), client->uid());
2707 status = INVALID_OPERATION;
2708 goto error;
2709 }
Eric Laurent331679c2018-04-16 17:03:16 -07002710 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002711 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002712 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002713 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002714
Eric Laurentfecbceb2021-02-09 14:46:43 +01002715 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002716 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002717 }
2718
2719 *input = AUDIO_IO_HANDLE_NONE;
2720 *inputType = API_INPUT_INVALID;
2721
Francois Gaffie716e1432019-01-14 16:58:59 +01002722 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002723 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002724 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002725 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002726 ALOGW("%s could not find input mix for attr %s",
2727 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002728 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002729 }
jiabinc1de2df2019-05-07 14:26:40 -07002730 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2731 String8(attr->tags + strlen("addr=")),
2732 AUDIO_FORMAT_DEFAULT);
2733 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002734 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002735 __func__, attributes.source, attributes.tags);
2736 status = BAD_VALUE;
2737 goto error;
2738 }
2739
Kevin Rocard25f9b052019-02-27 15:08:54 -08002740 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2741 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2742 } else {
2743 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2744 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002745 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002746 if (explicitRoutingDevice != nullptr) {
2747 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002748 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002749 // Prevent from storing invalid requested device id in clients
2750 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002751 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002752 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2753 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002754 }
François Gaffie11d30102018-11-02 16:09:09 +01002755 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002756 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002757 status = BAD_VALUE;
2758 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002759 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002760 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2761 *inputType = API_INPUT_MIX_CAPTURE;
2762 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002763 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2764 // there is an external policy, but this input is attached to a mix of recorders,
2765 // meaning it receives audio injected into the framework, so the recorder doesn't
2766 // know about it and is therefore considered "legacy"
2767 *inputType = API_INPUT_LEGACY;
2768 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002769 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002770 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002771 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002772 } else {
2773 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002774 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002775
Eric Laurent599c7582015-12-07 18:05:55 -08002776 }
2777
François Gaffiec005e562018-11-06 15:04:49 +01002778 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002779 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002780 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002781 AudioProfileVector profiles;
2782 status_t ret = getProfilesForDevices(
2783 DeviceVector(device), profiles, flags, true /*isInput*/);
2784 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002785 const auto channels = profiles[0]->getChannels();
2786 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2787 config->channel_mask = *channels.begin();
2788 }
2789 const auto sampleRates = profiles[0]->getSampleRates();
2790 if (!sampleRates.empty() &&
2791 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2792 config->sample_rate = *sampleRates.begin();
2793 }
jiabinf1c73972022-04-14 16:28:52 -07002794 config->format = profiles[0]->getFormat();
2795 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002796 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002797 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002798
Eric Laurent8f42ea12018-08-08 09:08:25 -07002799exit:
2800
François Gaffiec005e562018-11-06 15:04:49 +01002801 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2802 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002803
Francois Gaffie716e1432019-01-14 16:58:59 +01002804 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002805 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002806 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002807
Mikhail Naganov2996f672019-04-18 12:29:59 -07002808 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002809 requestedDeviceId, attributes.source, flags,
2810 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002811 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002812 // Move (if found) effect for the client session to its input
2813 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002814 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002815
2816 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2817 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002818
Eric Laurent599c7582015-12-07 18:05:55 -08002819 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002820
2821error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002822 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002823}
2824
2825
François Gaffie11d30102018-11-02 16:09:09 +01002826audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002827 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002828 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002829 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002830 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002831 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002832{
2833 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002834 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002835 bool isSoundTrigger = false;
2836
François Gaffiec005e562018-11-06 15:04:49 +01002837 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002838 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2839 if (index >= 0) {
2840 input = mSoundTriggerSessions.valueFor(session);
2841 isSoundTrigger = true;
2842 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2843 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2844 } else {
2845 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002846 }
François Gaffiec005e562018-11-06 15:04:49 +01002847 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002848 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002849 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002850 }
2851
Carter Hsua3abb402021-10-26 11:11:20 +08002852 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2853 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2854 }
2855
Eric Laurentfe231122017-11-17 17:48:06 -08002856 // sampling rate and flags may be updated by getInputProfile
2857 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2858 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002859 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002860 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002861 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002862 // find a compatible input profile (not necessarily identical in parameters)
2863 sp<IOProfile> profile = getInputProfile(
2864 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2865 if (profile == nullptr) {
2866 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002867 }
jiabin2fd710d2022-05-02 23:20:22 +00002868
Glenn Kasten05ddca52016-02-11 08:17:12 -08002869 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002870 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002871 if (samplingRate == 0) {
2872 samplingRate = profileSamplingRate;
2873 }
Eric Laurente552edb2014-03-10 17:42:56 -07002874
Eric Laurent322b4d22015-04-03 15:57:54 -07002875 if (profile->getModuleHandle() == 0) {
2876 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002877 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002878 }
2879
Eric Laurentec376dc2021-04-08 20:41:22 +02002880 // Reuse an already opened input if a client with the same session ID already exists
2881 // on that input
2882 for (size_t i = 0; i < mInputs.size(); i++) {
2883 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2884 if (desc->mProfile != profile) {
2885 continue;
2886 }
2887 RecordClientVector clients = desc->clientsList();
2888 for (const auto &client : clients) {
2889 if (session == client->session()) {
2890 return desc->mIoHandle;
2891 }
2892 }
2893 }
2894
Eric Laurent3974e3b2017-12-07 17:58:43 -08002895 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002896 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002897 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002898 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002899 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002900 continue;
2901 }
2902 // if sound trigger, reuse input if used by other sound trigger on same session
2903 // else
2904 // reuse input if active client app is not in IDLE state
2905 //
2906 RecordClientVector clients = desc->clientsList();
2907 bool doClose = false;
2908 for (const auto& client : clients) {
2909 if (isSoundTrigger != client->isSoundTrigger()) {
2910 continue;
2911 }
2912 if (client->isSoundTrigger()) {
2913 if (session == client->session()) {
2914 return desc->mIoHandle;
2915 }
2916 continue;
2917 }
2918 if (client->active() && client->appState() != APP_STATE_IDLE) {
2919 return desc->mIoHandle;
2920 }
2921 doClose = true;
2922 }
2923 if (doClose) {
2924 closeInput(desc->mIoHandle);
2925 } else {
2926 i++;
2927 }
2928 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002929 }
2930
Eric Laurentfe231122017-11-17 17:48:06 -08002931 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002932
Eric Laurentfe231122017-11-17 17:48:06 -08002933 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2934 lConfig.sample_rate = profileSamplingRate;
2935 lConfig.channel_mask = profileChannelMask;
2936 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002937
François Gaffie11d30102018-11-02 16:09:09 +01002938 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002939
2940 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002941 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002942 (profileSamplingRate != lConfig.sample_rate) ||
2943 !audio_formats_match(profileFormat, lConfig.format) ||
2944 (profileChannelMask != lConfig.channel_mask)) {
2945 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002946 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002947 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002948 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002949 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002950 }
Eric Laurent599c7582015-12-07 18:05:55 -08002951 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002952 }
2953
Eric Laurentc722f302014-12-10 11:21:49 -08002954 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002955
Eric Laurent599c7582015-12-07 18:05:55 -08002956 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002957 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002958
Eric Laurent599c7582015-12-07 18:05:55 -08002959 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002960}
2961
Eric Laurent4eb58f12018-12-07 16:41:02 -08002962status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002963{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002964 ALOGV("%s portId %d", __FUNCTION__, portId);
2965
2966 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2967 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002968 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002969 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002970 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002971 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002972 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002973 if (client->active()) {
2974 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2975 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002976 }
2977
Eric Laurent8f42ea12018-08-08 09:08:25 -07002978 audio_session_t session = client->session();
2979
Eric Laurent4eb58f12018-12-07 16:41:02 -08002980 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002981
Eric Laurent4eb58f12018-12-07 16:41:02 -08002982 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002983
Eric Laurent4eb58f12018-12-07 16:41:02 -08002984 status_t status = inputDesc->start();
2985 if (status != NO_ERROR) {
2986 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002987 }
Eric Laurente552edb2014-03-10 17:42:56 -07002988
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002989 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002990 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002991 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002992
Eric Laurent8f42ea12018-08-08 09:08:25 -07002993 // indicate active capture to sound trigger service if starting capture from a mic on
2994 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002995 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002996 if (device != nullptr) {
2997 status = setInputDevice(input, device, true /* force */);
2998 } else {
2999 ALOGW("%s no new input device can be found for descriptor %d",
3000 __FUNCTION__, inputDesc->getId());
3001 status = BAD_VALUE;
3002 }
Eric Laurente552edb2014-03-10 17:42:56 -07003003
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003004 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003005 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003006 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003007 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003008 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3009 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003010 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003011 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003012
François Gaffie11d30102018-11-02 16:09:09 +01003013 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3014 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003015 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003016 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003017 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003018
Eric Laurent8f42ea12018-08-08 09:08:25 -07003019 // automatically enable the remote submix output when input is started if not
3020 // used by a policy mix of type MIX_TYPE_RECORDERS
3021 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003022 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003023 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003024 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003025 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003026 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3027 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003028 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003029 if (address != "") {
3030 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3031 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003032 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003033 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003034 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003035 } else if (status != NO_ERROR) {
3036 // Restore client activity state.
3037 inputDesc->setClientActive(client, false);
3038 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003039 }
3040
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003041 ALOGV("%s input %d source = %d status = %d exit",
3042 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003043
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003044 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003045}
3046
Eric Laurent8fc147b2018-07-22 19:13:55 -07003047status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003048{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003049 ALOGV("%s portId %d", __FUNCTION__, portId);
3050
3051 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3052 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003053 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003054 return BAD_VALUE;
3055 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003056 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003057 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003058 if (!client->active()) {
3059 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003060 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003061 }
Carter Hsue6139d52021-07-08 10:30:20 +08003062 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003063 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003064
Eric Laurent8f42ea12018-08-08 09:08:25 -07003065 inputDesc->stop();
3066 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003067 auto current_source = inputDesc->source();
3068 setInputDevice(input, getNewInputDevice(inputDesc),
3069 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003070 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003071 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003073 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003074 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3075 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003076 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003077 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003078
3079 // automatically disable the remote submix output when input is stopped if not
3080 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003081 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003082 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003083 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003084 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003085 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3086 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003087 }
3088 if (address != "") {
3089 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3090 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003091 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003092 }
3093 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003094 resetInputDevice(input);
3095
3096 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3097 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003098 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3099 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003100 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003101 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003102 }
3103 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003104 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003105 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003106}
3107
Eric Laurent8fc147b2018-07-22 19:13:55 -07003108void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003109{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003110 ALOGV("%s portId %d", __FUNCTION__, portId);
3111
3112 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3113 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003114 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003115 return;
3116 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003117 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003118 audio_io_handle_t input = inputDesc->mIoHandle;
3119
Eric Laurent8f42ea12018-08-08 09:08:25 -07003120 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003121
Andy Hung39efb7a2018-09-26 15:39:28 -07003122 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003123 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003124 if (inputDesc->getClientCount() > 0) {
3125 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003126 return;
3127 }
3128
Eric Laurent05b90f82014-08-27 15:32:29 -07003129 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003130 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003131 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003132}
3133
Eric Laurent8f42ea12018-08-08 09:08:25 -07003134void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003135{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003136 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003137
3138 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003139 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003140 }
3141}
3142
Eric Laurent8f42ea12018-08-08 09:08:25 -07003143void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3144{
3145 stopInput(portId);
3146 releaseInput(portId);
3147}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003148
Eric Laurent0dd51852019-04-19 18:18:58 -07003149void AudioPolicyManager::checkCloseInputs() {
3150 // After connecting or disconnecting an input device, close input if:
3151 // - it has no client (was just opened to check profile) OR
3152 // - none of its supported devices are connected anymore OR
3153 // - one of its clients cannot be routed to one of its supported
3154 // devices anymore. Otherwise update device selection
3155 std::vector<audio_io_handle_t> inputsToClose;
3156 for (size_t i = 0; i < mInputs.size(); i++) {
3157 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3158 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003159 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003160 inputsToClose.push_back(mInputs.keyAt(i));
3161 } else {
3162 bool close = false;
3163 for (const auto& client : input->clientsList()) {
3164 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003165 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3166 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003167 if (!input->supportedDevices().contains(device)) {
3168 close = true;
3169 break;
3170 }
3171 }
3172 if (close) {
3173 inputsToClose.push_back(mInputs.keyAt(i));
3174 } else {
3175 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3176 }
3177 }
3178 }
3179
3180 for (const audio_io_handle_t handle : inputsToClose) {
3181 ALOGV("%s closing input %d", __func__, handle);
3182 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003183 }
Eric Laurentd4692962014-05-05 18:13:44 -07003184}
3185
François Gaffie251c7f02018-11-07 10:41:08 +01003186void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003187{
3188 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003189 if (indexMin < 0 || indexMax < 0) {
3190 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3191 return;
3192 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003193 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003194
3195 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003196 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3197 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003198 continue;
3199 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003200 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003201 }
Eric Laurente552edb2014-03-10 17:42:56 -07003202}
3203
Eric Laurente0720872014-03-11 09:30:41 -07003204status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003205 int index,
3206 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003207{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003208 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003209 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3210 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3211 return NO_ERROR;
3212 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003213 ALOGV("%s: stream %s attributes=%s", __func__,
3214 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003215 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003216}
3217
Eric Laurente0720872014-03-11 09:30:41 -07003218status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003219 int *index,
3220 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003221{
François Gaffiec005e562018-11-06 15:04:49 +01003222 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3223 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003224 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003225 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003226 deviceTypes = mEngine->getOutputDevicesForStream(
3227 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003228 }
jiabin9a3361e2019-10-01 09:38:30 -07003229 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003230}
3231
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003232status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003233 int index,
3234 audio_devices_t device)
3235{
3236 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003237 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3238 if (group == VOLUME_GROUP_NONE) {
3239 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003240 return BAD_VALUE;
3241 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003242 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003243 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003244 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003245 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003246 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3247 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3248 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3249 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003250 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3251
3252 status = setVolumeCurveIndex(index, device, curves);
3253 if (status != NO_ERROR) {
3254 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3255 return status;
3256 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003257
jiabin9a3361e2019-10-01 09:38:30 -07003258 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003259 auto curCurvAttrs = curves.getAttributes();
3260 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3261 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003262 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003263 } else if (!curves.getStreamTypes().empty()) {
3264 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003265 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003266 } else {
3267 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3268 return BAD_VALUE;
3269 }
jiabin9a3361e2019-10-01 09:38:30 -07003270 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3271 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003272
François Gaffiecfe17322018-11-07 13:41:29 +01003273 // update volume on all outputs and streams matching the following:
3274 // - The requested stream (or a stream matching for volume control) is active on the output
3275 // - The device (or devices) selected by the engine for this stream includes
3276 // the requested device
3277 // - For non default requested device, currently selected device on the output is either the
3278 // requested device or one of the devices selected by the engine for this stream
3279 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3280 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003281 for (size_t i = 0; i < mOutputs.size(); i++) {
3282 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003283 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003284
jiabin9a3361e2019-10-01 09:38:30 -07003285 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3286 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003287 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003288
3289 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003290 continue;
3291 }
3292 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3293 curDevices.find(device) == curDevices.end()) {
3294 continue;
3295 }
3296 bool applyVolume = false;
3297 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3298 curSrcDevices.insert(device);
3299 applyVolume = (curSrcDevices.find(
3300 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3301 } else {
3302 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3303 }
3304 if (!applyVolume) {
3305 continue; // next output
3306 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003307 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3308 // If a higher priority strategy is active, and the output is routed to a device with a
3309 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003310 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003311 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003312 // If the volume source is active with higher priority source, ensure at least Sw Muted
3313 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003314 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3315 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3316 false /*preferredDevice*/);
3317 if (activeClients.empty()) {
3318 continue;
3319 }
3320 bool isPreempted = false;
3321 bool isHigherPriority = productStrategy < strategy;
3322 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003323 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003324 ALOGV("%s: Strategy=%d (\nrequester:\n"
3325 " group %d, volumeGroup=%d attributes=%s)\n"
3326 " higher priority source active:\n"
3327 " volumeGroup=%d attributes=%s) \n"
3328 " on output %zu, bailing out", __func__, productStrategy,
3329 group, group, toString(attributes).c_str(),
3330 client->volumeSource(), toString(client->attributes()).c_str(), i);
3331 applyVolume = false;
3332 isPreempted = true;
3333 break;
3334 }
3335 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003336 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003337 applyVolume = true;
3338 }
3339 }
3340 if (isPreempted || applyVolume) {
3341 break;
3342 }
3343 }
3344 if (!applyVolume) {
3345 continue; // next output
3346 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003347 }
François Gaffieed91f582020-01-31 10:35:37 +01003348 //FIXME: workaround for truncated touch sounds
3349 // delayed volume change for system stream to be removed when the problem is
3350 // handled by system UI
3351 status_t volStatus = checkAndSetVolume(
3352 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003353 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003354 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3355 if (volStatus != NO_ERROR) {
3356 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003357 }
3358 }
François Gaffiecfe17322018-11-07 13:41:29 +01003359 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3360 return status;
3361}
3362
François Gaffieaaac0fd2018-11-22 17:56:39 +01003363status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003364 audio_devices_t device,
3365 IVolumeCurves &volumeCurves)
3366{
3367 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3368 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003369 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3370 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003371 (index > volumeCurves.getVolumeIndexMax())) {
3372 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3373 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3374 return BAD_VALUE;
3375 }
3376 if (!audio_is_output_device(device)) {
3377 return BAD_VALUE;
3378 }
3379
3380 // Force max volume if stream cannot be muted
3381 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3382
François Gaffieaaac0fd2018-11-22 17:56:39 +01003383 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003384 volumeCurves.addCurrentVolumeIndex(device, index);
3385 return NO_ERROR;
3386}
3387
3388status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3389 int &index,
3390 audio_devices_t device)
3391{
3392 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3393 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003394 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003395 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003396 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003397 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003398 }
jiabin9a3361e2019-10-01 09:38:30 -07003399 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003400}
3401
3402status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3403 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003404 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003405{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003406 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003407 return BAD_VALUE;
3408 }
jiabin9a3361e2019-10-01 09:38:30 -07003409 index = curves.getVolumeIndex(deviceTypes);
3410 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003411 return NO_ERROR;
3412}
3413
3414status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3415 int &index)
3416{
3417 index = getVolumeCurves(attr).getVolumeIndexMin();
3418 return NO_ERROR;
3419}
3420
3421status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3422 int &index)
3423{
3424 index = getVolumeCurves(attr).getVolumeIndexMax();
3425 return NO_ERROR;
3426}
3427
Eric Laurent36829f92017-04-07 19:04:42 -07003428audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003429{
3430 // select one output among several suitable for global effects.
3431 // The priority is as follows:
3432 // 1: An offloaded output. If the effect ends up not being offloadable,
3433 // AudioFlinger will invalidate the track and the offloaded output
3434 // will be closed causing the effect to be moved to a PCM output.
3435 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003436 // 3: The primary output
3437 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003438
François Gaffiec005e562018-11-06 15:04:49 +01003439 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3440 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003441 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003442
Eric Laurent36829f92017-04-07 19:04:42 -07003443 if (outputs.size() == 0) {
3444 return AUDIO_IO_HANDLE_NONE;
3445 }
Eric Laurente552edb2014-03-10 17:42:56 -07003446
Eric Laurent36829f92017-04-07 19:04:42 -07003447 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3448 bool activeOnly = true;
3449
3450 while (output == AUDIO_IO_HANDLE_NONE) {
3451 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3452 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3453 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3454
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003455 for (audio_io_handle_t output : outputs) {
3456 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003457 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003458 continue;
3459 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003460 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3461 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003462 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003463 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003464 }
3465 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003466 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003467 }
3468 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003469 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003470 }
3471 }
3472 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3473 output = outputOffloaded;
3474 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3475 output = outputDeepBuffer;
3476 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3477 output = outputPrimary;
3478 } else {
3479 output = outputs[0];
3480 }
3481 activeOnly = false;
3482 }
3483
3484 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003485 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3486 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003487 mMusicEffectOutput = output;
3488 }
3489
3490 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003491 return output;
3492}
3493
Eric Laurent36829f92017-04-07 19:04:42 -07003494audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3495{
3496 return selectOutputForMusicEffects();
3497}
3498
Eric Laurente0720872014-03-11 09:30:41 -07003499status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003500 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003501 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003502 int session,
3503 int id)
3504{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003505 if (session != AUDIO_SESSION_DEVICE) {
3506 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003507 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003508 index = mInputs.indexOfKey(io);
3509 if (index < 0) {
3510 ALOGW("registerEffect() unknown io %d", io);
3511 return INVALID_OPERATION;
3512 }
Eric Laurente552edb2014-03-10 17:42:56 -07003513 }
3514 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003515 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3516 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3517 || strategy == PRODUCT_STRATEGY_NONE));
3518 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003519}
3520
Eric Laurentc241b0d2018-11-28 09:08:49 -08003521status_t AudioPolicyManager::unregisterEffect(int id)
3522{
3523 if (mEffects.getEffect(id) == nullptr) {
3524 return INVALID_OPERATION;
3525 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003526 if (mEffects.isEffectEnabled(id)) {
3527 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3528 setEffectEnabled(id, false);
3529 }
3530 return mEffects.unregisterEffect(id);
3531}
3532
3533status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3534{
3535 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3536 if (effect == nullptr) {
3537 return INVALID_OPERATION;
3538 }
3539
3540 status_t status = mEffects.setEffectEnabled(id, enabled);
3541 if (status == NO_ERROR) {
3542 mInputs.trackEffectEnabled(effect, enabled);
3543 }
3544 return status;
3545}
3546
Eric Laurent6c796322019-04-09 14:13:17 -07003547
3548status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3549{
3550 mEffects.moveEffects(ids, io);
3551 return NO_ERROR;
3552}
3553
Eric Laurentc75307b2015-03-17 15:29:32 -07003554bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3555{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003556 auto vs = toVolumeSource(stream, false);
3557 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003558}
3559
3560bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3561{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003562 auto vs = toVolumeSource(stream, false);
3563 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003564}
3565
Eric Laurente0720872014-03-11 09:30:41 -07003566bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003567{
3568 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003569 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003570 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003571 return true;
3572 }
3573 }
3574 return false;
3575}
3576
Eric Laurent275e8e92014-11-30 15:14:47 -08003577// Register a list of custom mixes with their attributes and format.
3578// When a mix is registered, corresponding input and output profiles are
3579// added to the remote submix hw module. The profile contains only the
3580// parameters (sampling rate, format...) specified by the mix.
3581// The corresponding input remote submix device is also connected.
3582//
3583// When a remote submix device is connected, the address is checked to select the
3584// appropriate profile and the corresponding input or output stream is opened.
3585//
3586// When capture starts, getInputForAttr() will:
3587// - 1 look for a mix matching the address passed in attribtutes tags if any
3588// - 2 if none found, getDeviceForInputSource() will:
3589// - 2.1 look for a mix matching the attributes source
3590// - 2.2 if none found, default to device selection by policy rules
3591// At this time, the corresponding output remote submix device is also connected
3592// and active playback use cases can be transferred to this mix if needed when reconnecting
3593// after AudioTracks are invalidated
3594//
3595// When playback starts, getOutputForAttr() will:
3596// - 1 look for a mix matching the address passed in attribtutes tags if any
3597// - 2 if none found, look for a mix matching the attributes usage
3598// - 3 if none found, default to device and output selection by policy rules.
3599
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003600status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003601{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003602 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3603 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003604 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003605 sp<HwModule> rSubmixModule;
3606 // examine each mix's route type
3607 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003608 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003609 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3610 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3611 ALOGE("Unsupported Policy Mix %zu of %zu: "
3612 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3613 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003614 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003615 break;
3616 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003617 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3618 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003619 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003620 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3621 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003622 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003623 rSubmixModule = mHwModules.getModuleFromName(
3624 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3625 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003626 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003627 i);
3628 res = INVALID_OPERATION;
3629 break;
3630 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003631 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003632
Eric Laurent97ac8712018-07-27 18:59:02 -07003633 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003634 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003635 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003636 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003637 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3638 } else {
3639 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3640 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003641 }
François Gaffie036e1e92015-03-19 10:16:24 +01003642
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003643 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003644 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003645 res = INVALID_OPERATION;
3646 break;
3647 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003648 audio_config_t outputConfig = mix.mFormat;
3649 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003650 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3651 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003652 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3653 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003654 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003655 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003656 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003657 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003658
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003659 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003660 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003661 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003662 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003663 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003664 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003665 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003666 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3667 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003668 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003669 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003670 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003671
3672 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3673 mix.mDeviceType, mix.mDeviceAddress,
3674 String8(), AUDIO_FORMAT_DEFAULT);
3675 if (device == nullptr) {
3676 res = INVALID_OPERATION;
3677 break;
3678 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003679
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003680 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003681 // First try to find an already opened output supporting the device
3682 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003683 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003684
Eric Laurentc529cf62020-04-17 18:19:10 -07003685 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003686 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003687 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003688 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003689 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003690 } else {
3691 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003692 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003693 }
3694 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003695 // If no output found, try to find a direct output profile supporting the device
3696 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3697 sp<HwModule> module = mHwModules[i];
3698 for (size_t j = 0;
3699 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3700 j++) {
3701 sp<IOProfile> profile = module->getOutputProfiles()[j];
3702 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3703 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3704 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003705 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003706 res = INVALID_OPERATION;
3707 } else {
3708 foundOutput = true;
3709 }
3710 }
3711 }
3712 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003713 if (res != NO_ERROR) {
3714 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003715 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003716 res = INVALID_OPERATION;
3717 break;
3718 } else if (!foundOutput) {
3719 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003720 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003721 res = INVALID_OPERATION;
3722 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003723 } else {
3724 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003725 }
Eric Laurentc722f302014-12-10 11:21:49 -08003726 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003727 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003728 if (res != NO_ERROR) {
3729 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003730 } else if (checkOutputs) {
3731 checkForDeviceAndOutputChanges();
3732 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003733 }
3734 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003735}
3736
3737status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3738{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003739 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003740 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003741 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003742 sp<HwModule> rSubmixModule;
3743 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003744 for (const auto& mix : mixes) {
3745 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003746
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003747 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003748 rSubmixModule = mHwModules.getModuleFromName(
3749 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3750 if (rSubmixModule == 0) {
3751 res = INVALID_OPERATION;
3752 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003753 }
3754 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003755
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003756 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003757
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003758 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003759 res = INVALID_OPERATION;
3760 continue;
3761 }
3762
Kevin Rocard04ed0462019-05-02 17:53:24 -07003763 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003764 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003765 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3766 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003767 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003768 AUDIO_FORMAT_DEFAULT);
3769 if (res != OK) {
3770 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003771 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003772 }
3773 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003774 }
jiabin5740f082019-08-19 15:08:30 -07003775 rSubmixModule->removeOutputProfile(address.c_str());
3776 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003777
Kevin Rocard153f92d2018-12-18 18:33:28 -08003778 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003779 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003780 res = INVALID_OPERATION;
3781 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003782 } else {
3783 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003784 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003785 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003786 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003787 if (res == NO_ERROR && checkOutputs) {
3788 checkForDeviceAndOutputChanges();
3789 updateCallAndOutputRouting();
3790 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003791 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003792}
3793
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003794status_t AudioPolicyManager::updatePolicyMix(
3795 const AudioMix& mix,
3796 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3797 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3798 if (res == NO_ERROR) {
3799 checkForDeviceAndOutputChanges();
3800 updateCallAndOutputRouting();
3801 }
3802 return res;
3803}
3804
Mikhail Naganov100f0122018-11-29 11:22:16 -08003805void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3806{
3807 size_t i = 0;
3808 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3809 for (const auto& fmt : mManualSurroundFormats) {
3810 if (i++ != 0) dst->append(", ");
3811 std::string sfmt;
3812 FormatConverter::toString(fmt, sfmt);
3813 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3814 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3815 }
3816}
3817
Eric Laurentc529cf62020-04-17 18:19:10 -07003818// Returns true if all devices types match the predicate and are supported by one HW module
3819bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003820 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003821 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003822 const char *context,
3823 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003824 for (size_t i = 0; i < devices.size(); i++) {
3825 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003826 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003827 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003828 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003829 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003830 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003831 return false;
3832 }
3833 }
3834 return true;
3835}
3836
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003837void AudioPolicyManager::changeOutputDevicesMuteState(
3838 const AudioDeviceTypeAddrVector& devices) {
3839 ALOGVV("%s() num devices %zu", __func__, devices.size());
3840
3841 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3842 getSoftwareOutputsForDevices(devices);
3843
3844 for (size_t i = 0; i < outputs.size(); i++) {
3845 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3846 DeviceVector prevDevices = outputDesc->devices();
3847 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3848 }
3849}
3850
3851std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3852 const AudioDeviceTypeAddrVector& devices) const
3853{
3854 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3855 DeviceVector deviceDescriptors;
3856 for (size_t j = 0; j < devices.size(); j++) {
3857 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3858 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3859 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3860 ALOGE("%s: device type %#x address %s not supported or not an output device",
3861 __func__, devices[j].mType, devices[j].getAddress());
3862 continue;
3863 }
3864 deviceDescriptors.add(desc);
3865 }
3866 for (size_t i = 0; i < mOutputs.size(); i++) {
3867 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3868 continue;
3869 }
3870 outputs.push_back(mOutputs.valueAt(i));
3871 }
3872 return outputs;
3873}
3874
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003875status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003876 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003877 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003878 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3879 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003880 }
3881 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003882 if (res != NO_ERROR) {
3883 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3884 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003885 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003886
3887 checkForDeviceAndOutputChanges();
3888 updateCallAndOutputRouting();
3889
3890 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003891}
3892
3893status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3894 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003895 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3896 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003897 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003898 __FUNCTION__, uid);
3899 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003900 }
3901
Eric Laurentc529cf62020-04-17 18:19:10 -07003902 checkForDeviceAndOutputChanges();
3903 updateCallAndOutputRouting();
3904
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003905 return res;
3906}
3907
Eric Laurent2517af32020-11-25 15:31:27 +01003908
jiabin0a488932020-08-07 17:32:40 -07003909status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3910 device_role_t role,
3911 const AudioDeviceTypeAddrVector &devices) {
3912 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3913 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003914
Eric Laurentc529cf62020-04-17 18:19:10 -07003915 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003916 return BAD_VALUE;
3917 }
jiabin0a488932020-08-07 17:32:40 -07003918 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003919 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003920 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3921 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003922 return status;
3923 }
3924
3925 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003926
3927 bool forceVolumeReeval = false;
3928 // FIXME: workaround for truncated touch sounds
3929 // to be removed when the problem is handled by system UI
3930 uint32_t delayMs = 0;
3931 if (strategy == mCommunnicationStrategy) {
3932 forceVolumeReeval = true;
3933 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3934 updateInputRouting();
3935 }
3936 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003937
3938 return NO_ERROR;
3939}
3940
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003941void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3942 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003943{
3944 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003945 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003946 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003947 // Only apply special touch sound delay once
3948 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003949 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003950 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003951 for (size_t i = 0; i < mOutputs.size(); i++) {
3952 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3953 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003954 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3955 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003956 // As done in setDeviceConnectionState, we could also fix default device issue by
3957 // preventing the force re-routing in case of default dev that distinguishes on address.
3958 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003959 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003960 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3961 // If the device is using preferred mixer attributes, the output need to reopen
3962 // with default configuration when the new selected devices are different from
3963 // current routing devices.
3964 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3965 continue;
3966 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05303967
3968 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
3969 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003970 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003971 // Only apply special touch sound delay once
3972 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003973 }
3974 if (forceVolumeReeval && !newDevices.isEmpty()) {
3975 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3976 }
3977 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003978 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003979 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003980}
3981
Eric Laurent2517af32020-11-25 15:31:27 +01003982void AudioPolicyManager::updateInputRouting() {
3983 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303984 // Skip for hotword recording as the input device switch
3985 // is handled within sound trigger HAL
3986 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3987 continue;
3988 }
Eric Laurent2517af32020-11-25 15:31:27 +01003989 auto newDevice = getNewInputDevice(activeDesc);
3990 // Force new input selection if the new device can not be reached via current input
3991 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3992 setInputDevice(activeDesc->mIoHandle, newDevice);
3993 } else {
3994 closeInput(activeDesc->mIoHandle);
3995 }
3996 }
3997}
3998
Paul Wang5d7cdb52022-11-22 09:45:06 +00003999status_t
4000AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4001 device_role_t role,
4002 const AudioDeviceTypeAddrVector &devices) {
4003 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4004 dumpAudioDeviceTypeAddrVector(devices).c_str());
4005
Eric Laurent78fedbf2023-03-09 14:40:44 +01004006 if (!areAllDevicesSupported(
4007 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004008 return BAD_VALUE;
4009 }
4010 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4011 if (status != NO_ERROR) {
4012 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4013 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4014 return status;
4015 }
4016
4017 checkForDeviceAndOutputChanges();
4018
4019 bool forceVolumeReeval = false;
4020 // TODO(b/263479999): workaround for truncated touch sounds
4021 // to be removed when the problem is handled by system UI
4022 uint32_t delayMs = 0;
4023 if (strategy == mCommunnicationStrategy) {
4024 forceVolumeReeval = true;
4025 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4026 updateInputRouting();
4027 }
4028 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4029
4030 return NO_ERROR;
4031}
4032
4033status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4034 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004035{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004036 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004037
Paul Wang5d7cdb52022-11-22 09:45:06 +00004038 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004039 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004040 ALOGW_IF(status != NAME_NOT_FOUND,
4041 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004042 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004043 return status;
4044 }
4045
4046 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004047
4048 bool forceVolumeReeval = false;
4049 // FIXME: workaround for truncated touch sounds
4050 // to be removed when the problem is handled by system UI
4051 uint32_t delayMs = 0;
4052 if (strategy == mCommunnicationStrategy) {
4053 forceVolumeReeval = true;
4054 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4055 updateInputRouting();
4056 }
4057 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004058
4059 return NO_ERROR;
4060}
4061
jiabin0a488932020-08-07 17:32:40 -07004062status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4063 device_role_t role,
4064 AudioDeviceTypeAddrVector &devices) {
4065 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004066}
4067
Jiabin Huang3b98d322020-09-03 17:54:16 +00004068status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4069 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4070 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4071 dumpAudioDeviceTypeAddrVector(devices).c_str());
4072
Mikhail Naganov55773032020-10-01 15:08:13 -07004073 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004074 return BAD_VALUE;
4075 }
4076 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4077 ALOGW_IF(status != NO_ERROR,
4078 "Engine could not set preferred devices %s for audio source %d role %d",
4079 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4080
4081 return status;
4082}
4083
4084status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4085 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4086 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4087 dumpAudioDeviceTypeAddrVector(devices).c_str());
4088
Mikhail Naganov55773032020-10-01 15:08:13 -07004089 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004090 return BAD_VALUE;
4091 }
4092 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4093 ALOGW_IF(status != NO_ERROR,
4094 "Engine could not add preferred devices %s for audio source %d role %d",
4095 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4096
Eric Laurent2517af32020-11-25 15:31:27 +01004097 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004098 return status;
4099}
4100
4101status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4102 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4103{
4104 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4105 dumpAudioDeviceTypeAddrVector(devices).c_str());
4106
Eric Laurent78fedbf2023-03-09 14:40:44 +01004107 if (!areAllDevicesSupported(
4108 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004109 return BAD_VALUE;
4110 }
4111
4112 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4113 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004114 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004115 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004116 if (status == NO_ERROR) {
4117 updateInputRouting();
4118 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004119 return status;
4120}
4121
4122status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4123 device_role_t role) {
4124 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4125
4126 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004127 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004128 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004129 if (status == NO_ERROR) {
4130 updateInputRouting();
4131 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004132 return status;
4133}
4134
4135status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4136 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4137 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4138}
4139
Oscar Azucena90e77632019-11-27 17:12:28 -08004140status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004141 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004142 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004143 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4144 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004145 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004146 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4147 if (status != NO_ERROR) {
4148 ALOGE("%s() could not set device affinity for userId %d",
4149 __FUNCTION__, userId);
4150 return status;
4151 }
4152
4153 // reevaluate outputs for all devices
4154 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004155 changeOutputDevicesMuteState(devices);
4156 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4157 true /* skipDelays */);
4158 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004159
4160 return NO_ERROR;
4161}
4162
4163status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004164 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004165 AudioDeviceTypeAddrVector devices;
4166 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004167 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4168 if (status != NO_ERROR) {
4169 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4170 __FUNCTION__, userId);
4171 return status;
4172 }
4173
4174 // reevaluate outputs for all devices
4175 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004176 changeOutputDevicesMuteState(devices);
4177 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4178 true /* skipDelays */);
4179 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004180
4181 return NO_ERROR;
4182}
4183
Andy Hungc29d82b2018-10-05 12:23:17 -07004184void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004185{
Andy Hungc29d82b2018-10-05 12:23:17 -07004186 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004187 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004188 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004189 std::string stateLiteral;
4190 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004191 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004192 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4193 "communications", "media", "record", "dock", "system",
4194 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4195 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4196 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004197 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4198 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4199 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4200 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4201 dst->append(" (MANUAL: ");
4202 dumpManualSurroundFormats(dst);
4203 dst->append(")");
4204 }
4205 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004206 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004207 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4208 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004209 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004210 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004211
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004212 dst->append("\n");
4213 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4214 dst->append("\n");
4215 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004216 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004217 mOutputs.dump(dst);
4218 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004219 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004220 mAudioPatches.dump(dst);
4221 mPolicyMixes.dump(dst);
4222 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004223
Kevin Rocardb99cc752019-03-21 20:52:24 -07004224 dst->appendFormat(" AllowedCapturePolicies:\n");
4225 for (auto& policy : mAllowedCapturePolicies) {
4226 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4227 }
4228
jiabina84c3d32022-12-02 18:59:55 +00004229 dst->appendFormat(" Preferred mixer audio configuration:\n");
4230 for (const auto it : mPreferredMixerAttrInfos) {
4231 dst->appendFormat(" - device port id: %d\n", it.first);
4232 for (const auto preferredMixerInfoIt : it.second) {
4233 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4234 preferredMixerInfoIt.second->dump(dst);
4235 }
4236 }
4237
François Gaffiec005e562018-11-06 15:04:49 +01004238 dst->appendFormat("\nPolicy Engine dump:\n");
4239 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004240}
4241
4242status_t AudioPolicyManager::dump(int fd)
4243{
4244 String8 result;
4245 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004246 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004247 return NO_ERROR;
4248}
4249
Kevin Rocardb99cc752019-03-21 20:52:24 -07004250status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4251{
4252 mAllowedCapturePolicies[uid] = capturePolicy;
4253 return NO_ERROR;
4254}
4255
Eric Laurente552edb2014-03-10 17:42:56 -07004256// This function checks for the parameters which can be offloaded.
4257// This can be enhanced depending on the capability of the DSP and policy
4258// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004259audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004260{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004261 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004262 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004263 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004264 offloadInfo.format,
4265 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4266 offloadInfo.has_video);
4267
jiabin2b9d5a12021-12-10 01:06:29 +00004268 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004269 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004270 }
4271
4272 // See if there is a profile to support this.
4273 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004274 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004275 offloadInfo.sample_rate,
4276 offloadInfo.format,
4277 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004278 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4279 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004280 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4281 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4282 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004283 if (profile == nullptr) {
4284 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4285 }
4286 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4287 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4288 }
4289 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004290}
4291
Michael Chana94fbb22018-04-24 14:31:19 +10004292bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4293 const audio_attributes_t& attributes) {
4294 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004295 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004296 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4297 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004298 config.sample_rate,
4299 config.format,
4300 config.channel_mask,
4301 output_flags,
4302 true /* directOnly */);
4303 ALOGV("%s() profile %sfound with name: %s, "
4304 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4305 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004306 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004307 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004308
4309 // also try the MSD module if compatible profile not found
4310 if (profile == nullptr) {
4311 profile = getMsdProfileForOutput(outputDevices,
4312 config.sample_rate,
4313 config.format,
4314 config.channel_mask,
4315 output_flags,
4316 true /* directOnly */);
4317 ALOGV("%s() MSD profile %sfound with name: %s, "
4318 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4319 __FUNCTION__, profile != 0 ? "" : "NOT ",
4320 (profile != 0 ? profile->getTagName().c_str() : "null"),
4321 config.sample_rate, config.format, config.channel_mask, output_flags);
4322 }
4323 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004324}
4325
jiabin2b9d5a12021-12-10 01:06:29 +00004326bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4327 bool durationIgnored) {
4328 if (mMasterMono) {
4329 return false; // no offloading if mono is set.
4330 }
4331
4332 // Check if offload has been disabled
4333 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4334 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4335 return false;
4336 }
4337
4338 // Check if stream type is music, then only allow offload as of now.
4339 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4340 {
4341 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4342 return false;
4343 }
4344
4345 //TODO: enable audio offloading with video when ready
4346 const bool allowOffloadWithVideo =
4347 property_get_bool("audio.offload.video", false /* default_value */);
4348 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4349 ALOGV("%s: has_video == true, returning false", __func__);
4350 return false;
4351 }
4352
4353 //If duration is less than minimum value defined in property, return false
4354 const int min_duration_secs = property_get_int32(
4355 "audio.offload.min.duration.secs", -1 /* default_value */);
4356 if (!durationIgnored) {
4357 if (min_duration_secs >= 0) {
4358 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4359 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4360 __func__, min_duration_secs);
4361 return false;
4362 }
4363 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4364 ALOGV("%s: Offload denied by duration < default min(=%u)",
4365 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4366 return false;
4367 }
4368 }
4369
4370 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4371 // creating an offloaded track and tearing it down immediately after start when audioflinger
4372 // detects there is an active non offloadable effect.
4373 // FIXME: We should check the audio session here but we do not have it in this context.
4374 // This may prevent offloading in rare situations where effects are left active by apps
4375 // in the background.
4376 if (mEffects.isNonOffloadableEffectEnabled()) {
4377 return false;
4378 }
4379
4380 return true;
4381}
4382
4383audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4384 const audio_config_t *config) {
4385 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4386 offloadInfo.format = config->format;
4387 offloadInfo.sample_rate = config->sample_rate;
4388 offloadInfo.channel_mask = config->channel_mask;
4389 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4390 offloadInfo.has_video = false;
4391 offloadInfo.is_streaming = false;
4392 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4393
4394 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4395 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4396 audio_flags_to_audio_output_flags(attr->flags, &flags);
4397 // only retain flags that will drive compressed offload or passthrough
4398 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4399 if (offloadPossible) {
4400 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4401 }
4402 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4403
Dorin Drimusfae3c642022-03-17 18:36:30 +01004404 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004405 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004406 DeviceVector outputDevices = engineOutputDevices;
4407 // the MSD module checks for different conditions and output devices
4408 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4409 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4410 continue;
4411 }
4412 outputDevices = getMsdAudioOutDevices();
4413 }
jiabin2b9d5a12021-12-10 01:06:29 +00004414 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004415 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004416 config->sample_rate, nullptr /*updatedSamplingRate*/,
4417 config->format, nullptr /*updatedFormat*/,
4418 config->channel_mask, nullptr /*updatedChannelMask*/,
4419 flags)) {
4420 continue;
4421 }
4422 // reject profiles not corresponding to a device currently available
4423 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4424 continue;
4425 }
4426 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4427 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004428 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004429 != AUDIO_DIRECT_NOT_SUPPORTED) {
4430 // Already reports offload gapless supported. No need to report offload support.
4431 continue;
4432 }
4433 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4434 != AUDIO_OUTPUT_FLAG_NONE) {
4435 // If offload gapless is reported, no need to report offload support.
4436 directMode = (audio_direct_mode_t) ((directMode &
4437 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4438 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4439 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004440 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004441 }
4442 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004443 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004444 }
4445 }
4446 }
4447 return directMode;
4448}
4449
Dorin Drimusf2196d82022-01-03 12:11:18 +01004450status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4451 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004452 if (mEffects.isNonOffloadableEffectEnabled()) {
4453 return OK;
4454 }
jiabinf1c73972022-04-14 16:28:52 -07004455 DeviceVector devices;
4456 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004457 if (status != OK) {
4458 return status;
4459 }
4460 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4461 if (devices.empty()) {
4462 return OK; // no output devices for the attributes
4463 }
jiabinf1c73972022-04-14 16:28:52 -07004464 return getProfilesForDevices(devices, audioProfilesVector,
4465 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004466}
4467
jiabina84c3d32022-12-02 18:59:55 +00004468status_t AudioPolicyManager::getSupportedMixerAttributes(
4469 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4470 ALOGV("%s, portId=%d", __func__, portId);
4471 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4472 if (deviceDescriptor == nullptr) {
4473 ALOGE("%s the requested device is currently unavailable", __func__);
4474 return BAD_VALUE;
4475 }
jiabin96daffc2023-05-11 17:51:55 +00004476 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4477 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4478 deviceDescriptor->type());
4479 return BAD_VALUE;
4480 }
jiabina84c3d32022-12-02 18:59:55 +00004481 for (const auto& hwModule : mHwModules) {
4482 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4483 if (curProfile->supportsDevice(deviceDescriptor)) {
4484 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4485 }
4486 }
4487 }
4488 return NO_ERROR;
4489}
4490
4491status_t AudioPolicyManager::setPreferredMixerAttributes(
4492 const audio_attributes_t *attr,
4493 audio_port_handle_t portId,
4494 uid_t uid,
4495 const audio_mixer_attributes_t *mixerAttributes) {
4496 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4497 "mixerBehavior=%d}, uid=%d, portId=%u",
4498 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4499 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4500 mixerAttributes->mixer_behavior, uid, portId);
4501 if (attr->usage != AUDIO_USAGE_MEDIA) {
4502 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4503 return BAD_VALUE;
4504 }
4505 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4506 if (deviceDescriptor == nullptr) {
4507 ALOGE("%s the requested device is currently unavailable", __func__);
4508 return BAD_VALUE;
4509 }
4510 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4511 ALOGE("%s(%d), type=%d, is not a usb output device",
4512 __func__, portId, deviceDescriptor->type());
4513 return BAD_VALUE;
4514 }
4515
4516 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4517 audio_flags_to_audio_output_flags(attr->flags, &flags);
4518 flags = (audio_output_flags_t) (flags |
4519 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4520 sp<IOProfile> profile = nullptr;
4521 DeviceVector devices(deviceDescriptor);
4522 for (const auto& hwModule : mHwModules) {
4523 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4524 if (curProfile->hasDynamicAudioProfile()
4525 && curProfile->isCompatibleProfile(devices,
4526 mixerAttributes->config.sample_rate,
4527 nullptr /*updatedSamplingRate*/,
4528 mixerAttributes->config.format,
4529 nullptr /*updatedFormat*/,
4530 mixerAttributes->config.channel_mask,
4531 nullptr /*updatedChannelMask*/,
4532 flags,
4533 false /*exactMatchRequiredForInputFlags*/)) {
4534 profile = curProfile;
4535 break;
4536 }
4537 }
4538 }
4539 if (profile == nullptr) {
4540 ALOGE("%s, there is no compatible profile found", __func__);
4541 return BAD_VALUE;
4542 }
4543
4544 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4545 sp<PreferredMixerAttributesInfo>::make(
4546 uid, portId, profile, flags, *mixerAttributes);
4547 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4548 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4549
4550 // If 1) there is any client from the preferred mixer configuration owner that is currently
4551 // active and matches the strategy and 2) current output is on the preferred device and the
4552 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4553 // configuration.
4554 std::vector<audio_io_handle_t> outputsToReopen;
4555 for (size_t i = 0; i < mOutputs.size(); i++) {
4556 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004557 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4558 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4559 output->mUsePreferredMixerAttributes = true;
4560 } else {
4561 for (const auto &client: output->getActiveClients()) {
4562 if (client->uid() == uid && client->strategy() == strategy) {
4563 client->setIsInvalid();
4564 outputsToReopen.push_back(output->mIoHandle);
4565 }
jiabina84c3d32022-12-02 18:59:55 +00004566 }
4567 }
4568 }
4569 }
4570 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4571 config.sample_rate = mixerAttributes->config.sample_rate;
4572 config.channel_mask = mixerAttributes->config.channel_mask;
4573 config.format = mixerAttributes->config.format;
4574 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004575 sp<SwAudioOutputDescriptor> desc =
4576 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4577 if (desc == nullptr) {
4578 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4579 continue;
4580 }
4581 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004582 }
4583
4584 return NO_ERROR;
4585}
4586
4587sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004588 audio_port_handle_t devicePortId,
4589 product_strategy_t strategy,
4590 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004591 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4592 if (it == mPreferredMixerAttrInfos.end()) {
4593 return nullptr;
4594 }
jiabind9a58d32023-06-01 17:57:30 +00004595 if (activeBitPerfectPreferred) {
4596 for (auto [strategy, info] : it->second) {
4597 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4598 && info->getActiveClientCount() != 0) {
4599 return info;
4600 }
4601 }
jiabina84c3d32022-12-02 18:59:55 +00004602 }
jiabind9a58d32023-06-01 17:57:30 +00004603 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4604 return strategyMatchedMixerAttrInfoIt == it->second.end()
4605 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004606}
4607
4608status_t AudioPolicyManager::getPreferredMixerAttributes(
4609 const audio_attributes_t *attr,
4610 audio_port_handle_t portId,
4611 audio_mixer_attributes_t* mixerAttributes) {
4612 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4613 portId, mEngine->getProductStrategyForAttributes(*attr));
4614 if (info == nullptr) {
4615 return NAME_NOT_FOUND;
4616 }
4617 *mixerAttributes = info->getMixerAttributes();
4618 return NO_ERROR;
4619}
4620
4621status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4622 audio_port_handle_t portId,
4623 uid_t uid) {
4624 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4625 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4626 if (preferredMixerAttrInfo == nullptr) {
4627 return NAME_NOT_FOUND;
4628 }
4629 if (preferredMixerAttrInfo->getUid() != uid) {
4630 ALOGE("%s, requested uid=%d, owned uid=%d",
4631 __func__, uid, preferredMixerAttrInfo->getUid());
4632 return PERMISSION_DENIED;
4633 }
4634 mPreferredMixerAttrInfos[portId].erase(strategy);
4635 if (mPreferredMixerAttrInfos[portId].empty()) {
4636 mPreferredMixerAttrInfos.erase(portId);
4637 }
4638
4639 // Reconfig existing output
4640 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4641 for (size_t i = 0; i < mOutputs.size(); i++) {
4642 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4643 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4644 }
4645 }
4646 for (const auto output : potentialOutputsToReopen) {
4647 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4648 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4649 preferredMixerAttrInfo->getFlags())) {
4650 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4651 }
4652 }
4653 return NO_ERROR;
4654}
4655
Eric Laurent6a94d692014-05-20 11:18:06 -07004656status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4657 audio_port_type_t type,
4658 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004659 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004660 unsigned int *generation)
4661{
jiabin19cdba52020-11-24 11:28:58 -08004662 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4663 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004664 return BAD_VALUE;
4665 }
4666 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004667 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004668 *num_ports = 0;
4669 }
4670
4671 size_t portsWritten = 0;
4672 size_t portsMax = *num_ports;
4673 *num_ports = 0;
4674 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004675 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4676 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004677 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004678 for (const auto& dev : mAvailableOutputDevices) {
4679 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004680 continue;
4681 }
4682 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004683 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004684 }
4685 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004686 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004687 }
4688 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004689 for (const auto& dev : mAvailableInputDevices) {
4690 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004691 continue;
4692 }
4693 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004694 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004695 }
4696 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004697 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004698 }
4699 }
4700 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4701 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4702 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4703 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4704 }
4705 *num_ports += mInputs.size();
4706 }
4707 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004708 size_t numOutputs = 0;
4709 for (size_t i = 0; i < mOutputs.size(); i++) {
4710 if (!mOutputs[i]->isDuplicated()) {
4711 numOutputs++;
4712 if (portsWritten < portsMax) {
4713 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4714 }
4715 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004716 }
Eric Laurent84c70242014-06-23 08:46:27 -07004717 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004718 }
4719 }
jiabina84c3d32022-12-02 18:59:55 +00004720
Eric Laurent6a94d692014-05-20 11:18:06 -07004721 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004722 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004723 return NO_ERROR;
4724}
4725
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004726status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4727 std::vector<media::AudioPortFw>* _aidl_return) {
4728 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4729 audio_port_v7 port;
4730 dev->toAudioPort(&port);
4731 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4732 _aidl_return->push_back(std::move(aidlPort));
4733 return OK;
4734 };
4735
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004736 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004737 for (const auto& dev : module->getDeclaredDevices()) {
4738 if (role == media::AudioPortRole::NONE ||
4739 ((role == media::AudioPortRole::SOURCE)
4740 == audio_is_input_device(dev->type()))) {
4741 RETURN_STATUS_IF_ERROR(pushPort(dev));
4742 }
4743 }
4744 }
4745 return OK;
4746}
4747
jiabin19cdba52020-11-24 11:28:58 -08004748status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004749{
Eric Laurent99fcae42018-05-17 16:59:18 -07004750 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4751 return BAD_VALUE;
4752 }
4753 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4754 if (dev != 0) {
4755 dev->toAudioPort(port);
4756 return NO_ERROR;
4757 }
4758 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4759 if (dev != 0) {
4760 dev->toAudioPort(port);
4761 return NO_ERROR;
4762 }
4763 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4764 if (out != 0) {
4765 out->toAudioPort(port);
4766 return NO_ERROR;
4767 }
4768 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4769 if (in != 0) {
4770 in->toAudioPort(port);
4771 return NO_ERROR;
4772 }
4773 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004774}
4775
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004776status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4777 audio_patch_handle_t *handle,
4778 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004779{
François Gaffieafd4cea2019-11-18 15:50:22 +01004780 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004781 if (handle == NULL || patch == NULL) {
4782 return BAD_VALUE;
4783 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004784 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004785 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004786 return BAD_VALUE;
4787 }
4788 // only one source per audio patch supported for now
4789 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 return INVALID_OPERATION;
4791 }
Eric Laurent874c42872014-08-08 15:13:39 -07004792 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004793 return INVALID_OPERATION;
4794 }
Eric Laurent874c42872014-08-08 15:13:39 -07004795 for (size_t i = 0; i < patch->num_sinks; i++) {
4796 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4797 return INVALID_OPERATION;
4798 }
4799 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004800
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004801 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4802 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4803 if (srcDevice == nullptr || sinkDevice == nullptr) {
4804 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4805 return BAD_VALUE;
4806 }
4807 ALOGV("%s between source %s and sink %s", __func__,
4808 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4809 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4810 // Default attributes, default volume priority, not to infer with non raw audio patches.
4811 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4812 const struct audio_port_config *source = &patch->sources[0];
4813 sp<SourceClientDescriptor> sourceDesc =
4814 new InternalSourceClientDescriptor(
4815 portId, uid, attributes, *source, srcDevice, sinkDevice,
4816 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4817
4818 status_t status =
4819 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4820
4821 if (status != NO_ERROR) {
4822 return INVALID_OPERATION;
4823 }
4824 mAudioSources.add(portId, sourceDesc);
4825 return NO_ERROR;
4826}
4827
4828status_t AudioPolicyManager::connectAudioSourceToSink(
4829 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4830 const struct audio_patch *patch,
4831 audio_patch_handle_t &handle,
4832 uid_t uid, uint32_t delayMs)
4833{
4834 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4835 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4836 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4837 return INVALID_OPERATION;
4838 }
4839 sourceDesc->connect(handle, sinkDevice);
4840 if (isMsdPatch(handle)) {
4841 return NO_ERROR;
4842 }
4843 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4844 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4845 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4846 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4847 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4848 goto FailurePatchAdded;
4849 }
4850 status = swOutput->start();
4851 if (status != NO_ERROR) {
4852 goto FailureSourceAdded;
4853 }
4854 swOutput->addClient(sourceDesc);
4855 status = startSource(swOutput, sourceDesc, &delayMs);
4856 if (status != NO_ERROR) {
4857 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4858 goto FailureSourceActive;
4859 }
4860 if (delayMs != 0) {
4861 usleep(delayMs * 1000);
4862 }
4863 return NO_ERROR;
4864
4865FailureSourceActive:
4866 swOutput->stop();
4867 releaseOutput(sourceDesc->portId());
4868FailureSourceAdded:
4869 sourceDesc->setSwOutput(nullptr);
4870FailurePatchAdded:
4871 releaseAudioPatchInternal(handle);
4872 return INVALID_OPERATION;
4873}
4874
4875status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4876 audio_patch_handle_t *handle,
4877 uid_t uid, uint32_t delayMs,
4878 const sp<SourceClientDescriptor>& sourceDesc)
4879{
4880 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004881 sp<AudioPatch> patchDesc;
4882 ssize_t index = mAudioPatches.indexOfKey(*handle);
4883
François Gaffieafd4cea2019-11-18 15:50:22 +01004884 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4885 patch->sources[0].role,
4886 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004887#if LOG_NDEBUG == 0
4888 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004889 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4890 patch->sinks[i].role,
4891 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004892 }
4893#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004894
4895 if (index >= 0) {
4896 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004897 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4898 __func__, mUidCached, patchDesc->getUid(), uid);
4899 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004900 return INVALID_OPERATION;
4901 }
4902 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004903 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004904 }
4905
4906 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004907 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004908 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004909 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004910 return BAD_VALUE;
4911 }
Eric Laurent84c70242014-06-23 08:46:27 -07004912 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4913 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004914 if (patchDesc != 0) {
4915 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004916 ALOGV("%s source id differs for patch current id %d new id %d",
4917 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004918 return BAD_VALUE;
4919 }
4920 }
Eric Laurent874c42872014-08-08 15:13:39 -07004921 DeviceVector devices;
4922 for (size_t i = 0; i < patch->num_sinks; i++) {
4923 // Only support mix to devices connection
4924 // TODO add support for mix to mix connection
4925 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004926 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004927 return INVALID_OPERATION;
4928 }
4929 sp<DeviceDescriptor> devDesc =
4930 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4931 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004932 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004933 return BAD_VALUE;
4934 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004935
François Gaffie11d30102018-11-02 16:09:09 +01004936 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004937 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004938 NULL, // updatedSamplingRate
4939 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004940 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004941 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004942 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004943 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004944 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004945 return INVALID_OPERATION;
4946 }
4947 devices.add(devDesc);
4948 }
4949 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 return INVALID_OPERATION;
4951 }
Eric Laurent874c42872014-08-08 15:13:39 -07004952
Eric Laurent6a94d692014-05-20 11:18:06 -07004953 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004954 ALOGV("%s setting device %s on output %d",
4955 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304956 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004957 index = mAudioPatches.indexOfKey(*handle);
4958 if (index >= 0) {
4959 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004960 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 }
4962 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004963 patchDesc->setUid(uid);
4964 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004965 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004966 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004967 return INVALID_OPERATION;
4968 }
4969 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4970 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4971 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004972 // only one sink supported when connecting an input device to a mix
4973 if (patch->num_sinks > 1) {
4974 return INVALID_OPERATION;
4975 }
François Gaffie53615e22015-03-19 09:24:12 +01004976 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004977 if (inputDesc == NULL) {
4978 return BAD_VALUE;
4979 }
4980 if (patchDesc != 0) {
4981 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4982 return BAD_VALUE;
4983 }
4984 }
François Gaffie11d30102018-11-02 16:09:09 +01004985 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004987 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 return BAD_VALUE;
4989 }
4990
François Gaffie11d30102018-11-02 16:09:09 +01004991 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004992 patch->sinks[0].sample_rate,
4993 NULL, /*updatedSampleRate*/
4994 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004995 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004996 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004997 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004998 // FIXME for the parameter type,
4999 // and the NONE
5000 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005001 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005002 return INVALID_OPERATION;
5003 }
5004 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005005 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005006 device->toString().c_str(), inputDesc->mIoHandle);
5007 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005008 index = mAudioPatches.indexOfKey(*handle);
5009 if (index >= 0) {
5010 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005011 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005012 }
5013 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005014 patchDesc->setUid(uid);
5015 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005017 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005018 return INVALID_OPERATION;
5019 }
5020 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5021 // device to device connection
5022 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005023 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 return BAD_VALUE;
5025 }
5026 }
François Gaffie11d30102018-11-02 16:09:09 +01005027 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005028 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005029 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005030 return BAD_VALUE;
5031 }
Eric Laurent874c42872014-08-08 15:13:39 -07005032
Eric Laurent6a94d692014-05-20 11:18:06 -07005033 //update source and sink with our own data as the data passed in the patch may
5034 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005035 PatchBuilder patchBuilder;
5036 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005037
5038 // if first sink is to MSD, establish single MSD patch
5039 if (getMsdAudioOutDevices().contains(
5040 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5041 ALOGV("%s patching to MSD", __FUNCTION__);
5042 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5043 goto installPatch;
5044 }
5045
François Gaffieafd4cea2019-11-18 15:50:22 +01005046 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5047 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005048
Eric Laurent874c42872014-08-08 15:13:39 -07005049 for (size_t i = 0; i < patch->num_sinks; i++) {
5050 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005051 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005052 return INVALID_OPERATION;
5053 }
François Gaffie11d30102018-11-02 16:09:09 +01005054 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005055 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005056 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005057 return BAD_VALUE;
5058 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005059 audio_port_config sinkPortConfig = {};
5060 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5061 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005062
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005063 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5064 // volume management purpose (tracking activity)
5065 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5066 // in config XML to reach the sink so that is can be declared as available.
5067 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005068 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005069 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005070 // take care of dynamic routing for SwOutput selection,
5071 audio_attributes_t attributes = sourceDesc->attributes();
5072 audio_stream_type_t stream = sourceDesc->stream();
5073 audio_attributes_t resultAttr;
5074 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5075 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005076 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5077 config.channel_mask =
5078 (audio_channel_mask_get_representation(sourceMask)
5079 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5080 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005081 config.format = sourceDesc->config().format;
5082 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5083 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5084 bool isRequestedDeviceForExclusiveUse = false;
5085 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005086 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005087 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005088 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5089 &stream, sourceDesc->uid(), &config, &flags,
5090 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005091 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005092 if (output == AUDIO_IO_HANDLE_NONE) {
5093 ALOGV("%s no output for device %s",
5094 __FUNCTION__, sinkDevice->toString().c_str());
5095 return INVALID_OPERATION;
5096 }
5097 outputDesc = mOutputs.valueFor(output);
5098 if (outputDesc->isDuplicated()) {
5099 ALOGE("%s output is duplicated", __func__);
5100 return INVALID_OPERATION;
5101 }
François Gaffie7e39df22022-04-26 12:48:49 +02005102 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5103 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005104 } else {
5105 // Same for "raw patches" aka created from createAudioPatch API
5106 SortedVector<audio_io_handle_t> outputs =
5107 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5108 // if the sink device is reachable via an opened output stream, request to
5109 // go via this output stream by adding a second source to the patch
5110 // description
5111 output = selectOutput(outputs);
5112 if (output == AUDIO_IO_HANDLE_NONE) {
5113 ALOGE("%s no output available for internal patch sink", __func__);
5114 return INVALID_OPERATION;
5115 }
5116 outputDesc = mOutputs.valueFor(output);
5117 if (outputDesc->isDuplicated()) {
5118 ALOGV("%s output for device %s is duplicated",
5119 __func__, sinkDevice->toString().c_str());
5120 return INVALID_OPERATION;
5121 }
François Gaffie7e39df22022-04-26 12:48:49 +02005122 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005123 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005124 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005125 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005126 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005127 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005128 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5129 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005130 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5131 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005132 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005133 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005134 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005135 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005136 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005137 return INVALID_OPERATION;
5138 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005139 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005140 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005141 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005142 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005143 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005144 srcMixPortConfig.ext.mix.usecase.stream =
5145 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005146 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5147 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005148 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005149 }
Eric Laurent83b88082014-06-20 18:31:16 -07005150 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005151 }
5152 // TODO: check from routing capabilities in config file and other conflicting patches
5153
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005154installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005155 status_t status = installPatch(
5156 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005157 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005158 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005159 return INVALID_OPERATION;
5160 }
5161 } else {
5162 return BAD_VALUE;
5163 }
5164 } else {
5165 return BAD_VALUE;
5166 }
5167 return NO_ERROR;
5168}
5169
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005170status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005171{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005172 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005173 ssize_t index = mAudioPatches.indexOfKey(handle);
5174
5175 if (index < 0) {
5176 return BAD_VALUE;
5177 }
5178 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005179 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5180 __func__, mUidCached, patchDesc->getUid(), uid);
5181 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005182 return INVALID_OPERATION;
5183 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005184 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5185 for (size_t i = 0; i < mAudioSources.size(); i++) {
5186 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5187 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5188 portId = sourceDesc->portId();
5189 break;
5190 }
5191 }
5192 return portId != AUDIO_PORT_HANDLE_NONE ?
5193 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005194}
Eric Laurent6a94d692014-05-20 11:18:06 -07005195
François Gaffieafd4cea2019-11-18 15:50:22 +01005196status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005197 uint32_t delayMs,
5198 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005199{
5200 ALOGV("%s patch %d", __func__, handle);
5201 if (mAudioPatches.indexOfKey(handle) < 0) {
5202 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5203 return BAD_VALUE;
5204 }
5205 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005206 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005207 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005208 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005209 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005210 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005211 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005212 return BAD_VALUE;
5213 }
5214
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305215 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005216 getNewOutputDevices(outputDesc, true /*fromCache*/),
5217 true,
5218 0,
5219 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005220 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5221 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005222 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005223 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005224 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005225 return BAD_VALUE;
5226 }
5227 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005228 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005229 true,
5230 NULL);
5231 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005232 status_t status =
5233 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5234 ALOGV("%s patch panel returned %d patchHandle %d",
5235 __func__, status, patchDesc->getAfHandle());
5236 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005237 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005238 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005239 // SW or HW Bridge
5240 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5241 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005242 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005243 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5244 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5245 outputDesc = sourceDesc->swOutput().promote();
5246 }
5247 if (outputDesc == nullptr) {
5248 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5249 // releaseOutput has already called closeOutput in case of direct output
5250 return NO_ERROR;
5251 }
François Gaffie7e39df22022-04-26 12:48:49 +02005252 patchHandle = outputDesc->getPatchHandle();
5253 // When a Sw bridge is released, the mixer used by this bridge will release its
5254 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
5255 // Reuse patch handle to force audio flinger removing initial mixer patch removal
5256 // updating hal patch handle (prevent leaks).
5257 // While using a HwBridge, force reconsidering device only if not reusing an existing
5258 // output and no more activity on output (will force to close).
5259 bool force = sourceDesc->useSwBridge() ||
5260 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
5261 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5262 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5263 // Reconsider device only for cases:
5264 // 1 / Active Output
5265 // 2 / Inactive Output previously hosting HwBridge
5266 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5267 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5268 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305269 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005270 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5271 outputDesc->devices(),
5272 force,
5273 0,
5274 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 } else {
5276 return BAD_VALUE;
5277 }
5278 } else {
5279 return BAD_VALUE;
5280 }
5281 return NO_ERROR;
5282}
5283
5284status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5285 struct audio_patch *patches,
5286 unsigned int *generation)
5287{
François Gaffie53615e22015-03-19 09:24:12 +01005288 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005289 return BAD_VALUE;
5290 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005291 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005292 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005293}
5294
Eric Laurente1715a42014-05-20 11:30:42 -07005295status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005296{
Eric Laurente1715a42014-05-20 11:30:42 -07005297 ALOGV("setAudioPortConfig()");
5298
5299 if (config == NULL) {
5300 return BAD_VALUE;
5301 }
5302 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5303 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005304 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5305 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005306 }
5307
Eric Laurenta121f902014-06-03 13:32:54 -07005308 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005309 if (config->type == AUDIO_PORT_TYPE_MIX) {
5310 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005311 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005312 if (outputDesc == NULL) {
5313 return BAD_VALUE;
5314 }
Eric Laurent84c70242014-06-23 08:46:27 -07005315 ALOG_ASSERT(!outputDesc->isDuplicated(),
5316 "setAudioPortConfig() called on duplicated output %d",
5317 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005318 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005319 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005320 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005321 if (inputDesc == NULL) {
5322 return BAD_VALUE;
5323 }
Eric Laurenta121f902014-06-03 13:32:54 -07005324 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005325 } else {
5326 return BAD_VALUE;
5327 }
5328 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5329 sp<DeviceDescriptor> deviceDesc;
5330 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5331 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5332 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5333 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5334 } else {
5335 return BAD_VALUE;
5336 }
5337 if (deviceDesc == NULL) {
5338 return BAD_VALUE;
5339 }
Eric Laurenta121f902014-06-03 13:32:54 -07005340 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005341 } else {
5342 return BAD_VALUE;
5343 }
5344
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005345 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005346 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5347 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005348 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005349 audioPortConfig->toAudioPortConfig(&newConfig, config);
5350 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005351 }
Eric Laurenta121f902014-06-03 13:32:54 -07005352 if (status != NO_ERROR) {
5353 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005354 }
Eric Laurente1715a42014-05-20 11:30:42 -07005355
5356 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005357}
5358
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005359void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5360{
Eric Laurentd60560a2015-04-10 11:31:20 -07005361 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005362 clearAudioPatches(uid);
5363 clearSessionRoutes(uid);
5364}
5365
Eric Laurent6a94d692014-05-20 11:18:06 -07005366void AudioPolicyManager::clearAudioPatches(uid_t uid)
5367{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005368 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005369 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005370 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005371 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005372 }
5373 }
5374}
5375
François Gaffiec005e562018-11-06 15:04:49 +01005376void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005377{
François Gaffiec005e562018-11-06 15:04:49 +01005378 // Take the first attributes following the product strategy as it is used to retrieve the routed
5379 // device. All attributes wihin a strategy follows the same "routing strategy"
5380 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5381 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005382 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005383 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005384 for (size_t j = 0; j < mOutputs.size(); j++) {
5385 if (mOutputs.keyAt(j) == ouptutToSkip) {
5386 continue;
5387 }
5388 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005389 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005390 continue;
5391 }
5392 // If the default device for this strategy is on another output mix,
5393 // invalidate all tracks in this strategy to force re connection.
5394 // Otherwise select new device on the output mix.
5395 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005396 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005397 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005398 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5399 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5400 // If the device is using preferred mixer attributes, the output need to reopen
5401 // with default configuration when the new selected devices are different from
5402 // current routing devices.
5403 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5404 continue;
5405 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305406 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005407 }
5408 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005409 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005410}
5411
5412void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5413{
5414 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005415 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005416 for (size_t i = 0; i < mOutputs.size(); i++) {
5417 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005418 for (const auto& client : outputDesc->getClientIterable()) {
5419 if (client->hasPreferredDevice() && client->uid() == uid) {
5420 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005421 auto clientStrategy = client->strategy();
5422 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5423 end(affectedStrategies)) {
5424 continue;
5425 }
5426 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005427 }
5428 }
5429 }
5430 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005431 for (const auto& strategy : affectedStrategies) {
5432 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005433 }
5434
5435 // remove input routes associated with this uid
5436 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005437 for (size_t i = 0; i < mInputs.size(); i++) {
5438 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005439 for (const auto& client : inputDesc->getClientIterable()) {
5440 if (client->hasPreferredDevice() && client->uid() == uid) {
5441 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5442 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005443 }
5444 }
5445 }
5446 // reroute inputs if necessary
5447 SortedVector<audio_io_handle_t> inputsToClose;
5448 for (size_t i = 0; i < mInputs.size(); i++) {
5449 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005450 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005451 inputsToClose.add(inputDesc->mIoHandle);
5452 }
5453 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005454 for (const auto& input : inputsToClose) {
5455 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005456 }
5457}
5458
Eric Laurentd60560a2015-04-10 11:31:20 -07005459void AudioPolicyManager::clearAudioSources(uid_t uid)
5460{
5461 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005462 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5463 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005464 stopAudioSource(mAudioSources.keyAt(i));
5465 }
5466 }
5467}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005468
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005469status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5470 audio_io_handle_t *ioHandle,
5471 audio_devices_t *device)
5472{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005473 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5474 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005475 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005476 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5477 if (deviceDesc == nullptr) {
5478 return INVALID_OPERATION;
5479 }
5480 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005481
François Gaffiedf372692015-03-19 10:43:27 +01005482 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005483}
5484
Eric Laurentd60560a2015-04-10 11:31:20 -07005485status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005486 const audio_attributes_t *attributes,
5487 audio_port_handle_t *portId,
5488 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005489{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005490 ALOGV("%s", __FUNCTION__);
5491 *portId = AUDIO_PORT_HANDLE_NONE;
5492
5493 if (source == NULL || attributes == NULL || portId == NULL) {
5494 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5495 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005496 return BAD_VALUE;
5497 }
5498
Eric Laurentd60560a2015-04-10 11:31:20 -07005499 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5500 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005501 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5502 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005503 return INVALID_OPERATION;
5504 }
5505
François Gaffie11d30102018-11-02 16:09:09 +01005506 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005507 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005508 String8(source->ext.device.address),
5509 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005510 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005511 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005512 return BAD_VALUE;
5513 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005514
jiabin4ef93452019-09-10 14:29:54 -07005515 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005516
François Gaffieaaac0fd2018-11-22 17:56:39 +01005517 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005518 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005519 mEngine->getStreamTypeForAttributes(*attributes),
5520 mEngine->getProductStrategyForAttributes(*attributes),
5521 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005522
5523 status_t status = connectAudioSource(sourceDesc);
5524 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005525 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005526 }
5527 return status;
5528}
5529
Francois Gaffie601801d2021-06-22 13:27:39 +02005530sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5531 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5532{
5533 ALOGV("%s", __FUNCTION__);
5534 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5535
5536 status_t status = startAudioSource(source, attributes, &portId, uid);
5537 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5538 return mAudioSources.valueFor(portId);
5539}
5540
5541
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005542status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005543{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005544 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005545
5546 // make sure we only have one patch per source.
5547 disconnectAudioSource(sourceDesc);
5548
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005549 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005550 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5551 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5552 sourceDesc->srcDevice()->type(),
5553 String8(sourceDesc->srcDevice()->address().c_str()),
5554 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005555 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005556 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005557 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005558 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005559 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5560 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5561 return INVALID_OPERATION;
5562 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005563 PatchBuilder patchBuilder;
5564 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5565 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005566
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005567 return connectAudioSourceToSink(
5568 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005569}
5570
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005571status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005572{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005573 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5574 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005575 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005576 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005577 return BAD_VALUE;
5578 }
5579 status_t status = disconnectAudioSource(sourceDesc);
5580
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005581 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005582 return status;
5583}
5584
Andy Hung2ddee192015-12-18 17:34:44 -08005585status_t AudioPolicyManager::setMasterMono(bool mono)
5586{
5587 if (mMasterMono == mono) {
5588 return NO_ERROR;
5589 }
5590 mMasterMono = mono;
5591 // if enabling mono we close all offloaded devices, which will invalidate the
5592 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5593 // for recreating the new AudioTrack as non-offloaded PCM.
5594 //
5595 // If disabling mono, we leave all tracks as is: we don't know which clients
5596 // and tracks are able to be recreated as offloaded. The next "song" should
5597 // play back offloaded.
5598 if (mMasterMono) {
5599 Vector<audio_io_handle_t> offloaded;
5600 for (size_t i = 0; i < mOutputs.size(); ++i) {
5601 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5602 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5603 offloaded.push(desc->mIoHandle);
5604 }
5605 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005606 for (const auto& handle : offloaded) {
5607 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005608 }
5609 }
5610 // update master mono for all remaining outputs
5611 for (size_t i = 0; i < mOutputs.size(); ++i) {
5612 updateMono(mOutputs.keyAt(i));
5613 }
5614 return NO_ERROR;
5615}
5616
5617status_t AudioPolicyManager::getMasterMono(bool *mono)
5618{
5619 *mono = mMasterMono;
5620 return NO_ERROR;
5621}
5622
Eric Laurentac9cef52017-06-09 15:46:26 -07005623float AudioPolicyManager::getStreamVolumeDB(
5624 audio_stream_type_t stream, int index, audio_devices_t device)
5625{
jiabin9a3361e2019-10-01 09:38:30 -07005626 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005627}
5628
jiabin81772902018-04-02 17:52:27 -07005629status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5630 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005631 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005632{
Kriti Dang6537def2021-03-02 13:46:59 +01005633 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5634 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005635 return BAD_VALUE;
5636 }
Kriti Dang6537def2021-03-02 13:46:59 +01005637 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5638 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005639
5640 size_t formatsWritten = 0;
5641 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005642
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005643 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005644 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5645 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005646 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005647 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005648 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005649 bool formatEnabled = true;
5650 switch (forceUse) {
5651 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005652 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005653 break;
5654 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5655 formatEnabled = false;
5656 break;
5657 default: // AUTO or ALWAYS => true
5658 break;
jiabin81772902018-04-02 17:52:27 -07005659 }
5660 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5661 }
jiabin81772902018-04-02 17:52:27 -07005662 }
5663 return NO_ERROR;
5664}
5665
Kriti Dang6537def2021-03-02 13:46:59 +01005666status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5667 audio_format_t *surroundFormats) {
5668 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5669 return BAD_VALUE;
5670 }
5671 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5672 __func__, *numSurroundFormats, surroundFormats);
5673
5674 size_t formatsWritten = 0;
5675 size_t formatsMax = *numSurroundFormats;
5676 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5677
5678 // Return formats from all device profiles that have already been resolved by
5679 // checkOutputsForDevice().
5680 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5681 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5682 audio_devices_t deviceType = device->type();
5683 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5684 // returns formats reported by HDMI devices.
5685 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5686 continue;
5687 }
5688 // Formats reported by sink devices
5689 std::unordered_set<audio_format_t> formatset;
5690 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5691 formatset.insert(it->second.begin(), it->second.end());
5692 }
5693
5694 // Formats hard-coded in the in policy configuration file (if any).
5695 FormatVector encodedFormats = device->encodedFormats();
5696 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5697 // Filter the formats which are supported by the vendor hardware.
5698 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005699 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005700 formats.insert(*it);
5701 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005702 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005703 if (pair.second.count(*it) != 0) {
5704 formats.insert(pair.first);
5705 break;
5706 }
5707 }
5708 }
5709 }
5710 }
5711 *numSurroundFormats = formats.size();
5712 for (const auto& format: formats) {
5713 if (formatsWritten < formatsMax) {
5714 surroundFormats[formatsWritten++] = format;
5715 }
5716 }
5717 return NO_ERROR;
5718}
5719
jiabin81772902018-04-02 17:52:27 -07005720status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5721{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005722 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005723 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5724 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005725 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005726 return BAD_VALUE;
5727 }
5728
Mikhail Naganov100f0122018-11-29 11:22:16 -08005729 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5730 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005731 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005732 return INVALID_OPERATION;
5733 }
5734
Mikhail Naganov100f0122018-11-29 11:22:16 -08005735 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005736 return NO_ERROR;
5737 }
5738
Mikhail Naganov100f0122018-11-29 11:22:16 -08005739 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005740 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005741 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005742 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005743 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005744 }
5745 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005746 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005747 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005748 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005749 }
5750 }
5751
5752 sp<SwAudioOutputDescriptor> outputDesc;
5753 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005754 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5755 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005756 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5757 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005758 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005759 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005760 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5761 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5762 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005763 name.c_str(),
5764 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005765 if (status != NO_ERROR) {
5766 continue;
5767 }
5768 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5769 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5770 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005771 name.c_str(),
5772 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005773 profileUpdated |= (status == NO_ERROR);
5774 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005775 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005776 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005777 AUDIO_DEVICE_IN_HDMI);
5778 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5779 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005780 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005781 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005782 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5783 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5784 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005785 name.c_str(),
5786 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005787 if (status != NO_ERROR) {
5788 continue;
5789 }
5790 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5791 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5792 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005793 name.c_str(),
5794 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005795 profileUpdated |= (status == NO_ERROR);
5796 }
5797
jiabin81772902018-04-02 17:52:27 -07005798 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005799 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005800 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005801 }
5802
5803 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5804}
5805
Eric Laurent5ada82e2019-08-29 17:53:54 -07005806void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005807{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005808 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005809 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005810 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005811 }
5812}
5813
jiabin6012f912018-11-02 17:06:30 -07005814bool AudioPolicyManager::isHapticPlaybackSupported()
5815{
5816 for (const auto& hwModule : mHwModules) {
5817 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5818 for (const auto &outProfile : outputProfiles) {
5819 struct audio_port audioPort;
5820 outProfile->toAudioPort(&audioPort);
5821 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5822 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5823 return true;
5824 }
5825 }
5826 }
5827 }
5828 return false;
5829}
5830
Carter Hsu325a8eb2022-01-19 19:56:51 +08005831bool AudioPolicyManager::isUltrasoundSupported()
5832{
5833 bool hasUltrasoundOutput = false;
5834 bool hasUltrasoundInput = false;
5835 for (const auto& hwModule : mHwModules) {
5836 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5837 if (!hasUltrasoundOutput) {
5838 for (const auto &outProfile : outputProfiles) {
5839 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5840 hasUltrasoundOutput = true;
5841 break;
5842 }
5843 }
5844 }
5845
5846 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5847 if (!hasUltrasoundInput) {
5848 for (const auto &inputProfile : inputProfiles) {
5849 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5850 hasUltrasoundInput = true;
5851 break;
5852 }
5853 }
5854 }
5855
5856 if (hasUltrasoundOutput && hasUltrasoundInput)
5857 return true;
5858 }
5859 return false;
5860}
5861
Atneya Nair698f5ef2022-12-15 16:15:09 -08005862bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5863{
5864 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5865 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5866 for (const auto& hwModule : mHwModules) {
5867 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5868 for (const auto &inputProfile : inputProfiles) {
5869 if ((inputProfile->getFlags() & mask) == mask) {
5870 return true;
5871 }
5872 }
5873 }
5874 return false;
5875}
5876
Eric Laurent8340e672019-11-06 11:01:08 -08005877bool AudioPolicyManager::isCallScreenModeSupported()
5878{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005879 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005880}
5881
5882
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005883status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005884{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005885 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005886 if (!sourceDesc->isConnected()) {
5887 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5888 return NO_ERROR;
5889 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005890 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5891 if (swOutput != 0) {
5892 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005893 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005894 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005895 }
jiabinbce0c1d2020-10-05 11:20:18 -07005896 if (releaseOutput(sourceDesc->portId())) {
5897 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5898 // no need to release audio patch here but just return NO_ERROR.
5899 return NO_ERROR;
5900 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005901 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005902 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005903 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005904 // close Hwoutput and remove from mHwOutputs
5905 } else {
5906 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5907 }
5908 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005909 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005910 sourceDesc->disconnect();
5911 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005912}
5913
François Gaffiec005e562018-11-06 15:04:49 +01005914sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5915 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005916{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005917 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005918 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005919 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005920 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005921 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5922 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005923 source = sourceDesc;
5924 break;
5925 }
5926 }
5927 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005928}
5929
Eric Laurentb4f42a92022-01-17 17:37:31 +01005930bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005931 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005932 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005933{
5934 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5935 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005936 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005937 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005938 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5939 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5940 return false;
5941 }
5942 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5943 return false;
5944 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005945 }
5946
Eric Laurentd332bc82023-08-04 11:45:23 +02005947 // The caller can have the audio config criteria ignored by either passing a null ptr or
5948 // the AUDIO_CONFIG_INITIALIZER value.
5949 // If an audio config is specified, current policy is to only allow spatialization for
5950 // some positional channel masks and PCM format
5951
5952 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5953 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
5954 return false;
5955 }
5956 if (!audio_is_linear_pcm(config->format)) {
5957 return false;
5958 }
5959 }
5960
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005961 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005962 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005963 if (profile == nullptr) {
5964 return false;
5965 }
5966
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005967 return true;
5968}
5969
5970void AudioPolicyManager::checkVirtualizerClientRoutes() {
5971 std::set<audio_stream_type_t> streamsToInvalidate;
5972 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005973 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5974 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005975 audio_attributes_t attr = client->attributes();
5976 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5977 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5978 audio_config_base_t clientConfig = client->config();
5979 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005980 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005981 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005982 streamsToInvalidate.insert(client->stream());
5983 }
5984 }
5985 }
5986
jiabinc44b3462022-12-08 12:52:31 -08005987 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005988}
5989
Eric Laurente191d1b2022-04-15 11:59:25 +02005990
5991bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5992 const sp<SwAudioOutputDescriptor>& outputDesc) {
5993 if (outputDesc->isDuplicated()) {
5994 return false;
5995 }
5996 DeviceVector devices = outputDesc->supportedDevices();
5997 for (size_t i = 0; i < mOutputs.size(); i++) {
5998 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5999 if (desc == outputDesc || desc->isDuplicated()) {
6000 continue;
6001 }
6002 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6003 if (!sharedDevices.isEmpty()
6004 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6005 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6006 return false;
6007 }
6008 }
6009 return true;
6010}
6011
6012
Eric Laurentfa0f6742021-08-17 18:39:44 +02006013status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006014 const audio_attributes_t *attr,
6015 audio_io_handle_t *output) {
6016 *output = AUDIO_IO_HANDLE_NONE;
6017
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006018 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6019 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6020 audio_config_t *configPtr = nullptr;
6021 audio_config_t config;
6022 if (mixerConfig != nullptr) {
6023 config = audio_config_initializer(mixerConfig);
6024 configPtr = &config;
6025 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006026 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006027 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006028 return BAD_VALUE;
6029 }
6030
6031 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006032 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006033 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006034 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006035 return BAD_VALUE;
6036 }
6037
Eric Laurente191d1b2022-04-15 11:59:25 +02006038 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006039 for (size_t i = 0; i < mOutputs.size(); i++) {
6040 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006041 if (!desc->isDuplicated()
6042 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6043 spatializerOutputs.push_back(desc);
6044 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006045 }
6046 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006047 mSpatializerOutput.clear();
6048 bool outputsChanged = false;
6049 for (const auto& desc : spatializerOutputs) {
6050 if (desc->mProfile == profile
6051 && (configPtr == nullptr
6052 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6053 mSpatializerOutput = desc;
6054 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6055 } else {
6056 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6057 " and devices %s", __func__, desc->mIoHandle,
6058 configPtr != nullptr ? configPtr->channel_mask : 0,
6059 devices.toString().c_str());
6060 closeOutput(desc->mIoHandle);
6061 outputsChanged = true;
6062 }
Eric Laurent39095982021-08-24 18:29:27 +02006063 }
6064
Eric Laurente191d1b2022-04-15 11:59:25 +02006065 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006066 sp<SwAudioOutputDescriptor> desc =
6067 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006068 if (desc != nullptr) {
6069 mSpatializerOutput = desc;
6070 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006071 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006072 }
6073
6074 checkVirtualizerClientRoutes();
6075
Eric Laurente191d1b2022-04-15 11:59:25 +02006076 if (outputsChanged) {
6077 mPreviousOutputs = mOutputs;
6078 mpClientInterface->onAudioPortListUpdate();
6079 }
6080
6081 if (mSpatializerOutput == nullptr) {
6082 ALOGV("%s could not open spatializer output with requested config", __func__);
6083 return BAD_VALUE;
6084 }
Eric Laurent39095982021-08-24 18:29:27 +02006085 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006086 ALOGV("%s returning new spatializer output %d", __func__, *output);
6087 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006088}
6089
Eric Laurentfa0f6742021-08-17 18:39:44 +02006090status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6091 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006092 return INVALID_OPERATION;
6093 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006094 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006095 return BAD_VALUE;
6096 }
Eric Laurent39095982021-08-24 18:29:27 +02006097
Eric Laurente191d1b2022-04-15 11:59:25 +02006098 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6099 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6100 closeOutput(mSpatializerOutput->mIoHandle);
6101 //from now on mSpatializerOutput is null
6102 checkVirtualizerClientRoutes();
6103 }
Eric Laurent39095982021-08-24 18:29:27 +02006104
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006105 return NO_ERROR;
6106}
6107
Eric Laurente552edb2014-03-10 17:42:56 -07006108// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006109// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006110// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006111uint32_t AudioPolicyManager::nextAudioPortGeneration()
6112{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006113 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006114}
6115
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006116AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006117 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006118 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006119 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006120 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006121 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006122 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006123 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006124 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006125 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006126 mAudioPortGeneration(1),
6127 mBeaconMuteRefCount(0),
6128 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006129 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006130 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006131 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006132 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006133{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006134}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006135
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006136status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006137 if (mEngine == nullptr) {
6138 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006139 }
6140 mEngine->setObserver(this);
6141 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006142 if (status != NO_ERROR) {
6143 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6144 return status;
6145 }
François Gaffie2110e042015-03-24 08:41:51 +01006146
jiabin29230182023-04-04 21:02:36 +00006147 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6148 // at the end of this function.
6149 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006150 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6151 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6152
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006153 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006154 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006155 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006156
Eric Laurent3a4311c2014-03-17 12:00:47 -07006157 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006158 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6159 defaultOutputDevice == nullptr ||
6160 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6161 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6162 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006163 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006164 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006165 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006166
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006167 // Silence ALOGV statements
6168 property_set("log.tag." LOG_TAG, "D");
6169
Eric Laurente552edb2014-03-10 17:42:56 -07006170 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006171 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006172}
6173
Eric Laurente0720872014-03-11 09:30:41 -07006174AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006175{
Eric Laurente552edb2014-03-10 17:42:56 -07006176 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006177 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006178 }
6179 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006180 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006181 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006182 mAvailableOutputDevices.clear();
6183 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006184 mOutputs.clear();
6185 mInputs.clear();
6186 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006187 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006188 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006189}
6190
Eric Laurente0720872014-03-11 09:30:41 -07006191status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006192{
Eric Laurent87ffa392015-05-22 10:32:38 -07006193 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006194}
6195
Eric Laurente552edb2014-03-10 17:42:56 -07006196// ---
6197
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006198void AudioPolicyManager::onNewAudioModulesAvailable()
6199{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006200 DeviceVector newDevices;
6201 onNewAudioModulesAvailableInt(&newDevices);
6202 if (!newDevices.empty()) {
6203 nextAudioPortGeneration();
6204 mpClientInterface->onAudioPortListUpdate();
6205 }
6206}
6207
6208void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6209{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006210 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006211 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6212 continue;
6213 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006214 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006215 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6216 handle != AUDIO_MODULE_HANDLE_NONE) {
6217 hwModule->setHandle(handle);
6218 } else {
6219 ALOGW("could not load HW module %s", hwModule->getName());
6220 continue;
6221 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006222 }
6223 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006224 // open all output streams needed to access attached devices.
6225 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006226 // This also validates mAvailableOutputDevices list
6227 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6228 if (!outProfile->canOpenNewIo()) {
6229 ALOGE("Invalid Output profile max open count %u for profile %s",
6230 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6231 continue;
6232 }
6233 if (!outProfile->hasSupportedDevices()) {
6234 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6235 continue;
6236 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006237 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6238 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006239 mTtsOutputAvailable = true;
6240 }
6241
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006242 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006243 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006244 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006245 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6246 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006247 } else {
6248 // choose first device present in profile's SupportedDevices also part of
6249 // mAvailableOutputDevices.
6250 if (availProfileDevices.isEmpty()) {
6251 continue;
6252 }
6253 supportedDevice = availProfileDevices.itemAt(0);
6254 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006255 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006256 continue;
6257 }
6258 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6259 mpClientInterface);
6260 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006261 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6262 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006263 AUDIO_STREAM_DEFAULT,
6264 AUDIO_OUTPUT_FLAG_NONE, &output);
6265 if (status != NO_ERROR) {
6266 ALOGW("Cannot open output stream for devices %s on hw module %s",
6267 supportedDevice->toString().c_str(), hwModule->getName());
6268 continue;
6269 }
6270 for (const auto &device : availProfileDevices) {
6271 // give a valid ID to an attached device once confirmed it is reachable
6272 if (!device->isAttached()) {
6273 device->attach(hwModule);
6274 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006275 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006276 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006277 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6278 }
6279 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006280 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006281 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6282 mPrimaryOutput = outputDesc;
6283 }
Eric Laurent39095982021-08-24 18:29:27 +02006284 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006285 outputDesc->close();
6286 } else {
6287 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306288 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006289 DeviceVector(supportedDevice),
6290 true,
6291 0,
6292 NULL);
6293 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006294 }
6295 // open input streams needed to access attached devices to validate
6296 // mAvailableInputDevices list
6297 for (const auto& inProfile : hwModule->getInputProfiles()) {
6298 if (!inProfile->canOpenNewIo()) {
6299 ALOGE("Invalid Input profile max open count %u for profile %s",
6300 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6301 continue;
6302 }
6303 if (!inProfile->hasSupportedDevices()) {
6304 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6305 continue;
6306 }
6307 // chose first device present in profile's SupportedDevices also part of
6308 // available input devices
6309 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006310 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006311 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006312 ALOGV("%s: Input device list is empty! for profile %s",
6313 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006314 continue;
6315 }
6316 sp<AudioInputDescriptor> inputDesc =
6317 new AudioInputDescriptor(inProfile, mpClientInterface);
6318
6319 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6320 status_t status = inputDesc->open(nullptr,
6321 availProfileDevices.itemAt(0),
6322 AUDIO_SOURCE_MIC,
6323 AUDIO_INPUT_FLAG_NONE,
6324 &input);
6325 if (status != NO_ERROR) {
6326 ALOGW("Cannot open input stream for device %s on hw module %s",
6327 availProfileDevices.toString().c_str(),
6328 hwModule->getName());
6329 continue;
6330 }
6331 for (const auto &device : availProfileDevices) {
6332 // give a valid ID to an attached device once confirmed it is reachable
6333 if (!device->isAttached()) {
6334 device->attach(hwModule);
6335 device->importAudioPortAndPickAudioProfile(inProfile, true);
6336 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006337 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006338 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6339 }
6340 }
6341 inputDesc->close();
6342 }
6343 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006344
6345 // Check if spatializer outputs can be closed until used.
6346 // mOutputs vector never contains duplicated outputs at this point.
6347 std::vector<audio_io_handle_t> outputsClosed;
6348 for (size_t i = 0; i < mOutputs.size(); i++) {
6349 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6350 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6351 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6352 outputsClosed.push_back(desc->mIoHandle);
6353 desc->close();
6354 }
6355 }
6356 for (auto output : outputsClosed) {
6357 removeOutput(output);
6358 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006359}
6360
Eric Laurent98e38192018-02-15 18:31:53 -08006361void AudioPolicyManager::addOutput(audio_io_handle_t output,
6362 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006363{
Eric Laurent1c333e22014-05-20 10:48:17 -07006364 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006365 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006366 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006367 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006368 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006369}
6370
François Gaffie53615e22015-03-19 09:24:12 +01006371void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6372{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006373 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6374 ALOGV("%s: removing primary output", __func__);
6375 mPrimaryOutput = nullptr;
6376 }
François Gaffie53615e22015-03-19 09:24:12 +01006377 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006378 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006379}
6380
Eric Laurent98e38192018-02-15 18:31:53 -08006381void AudioPolicyManager::addInput(audio_io_handle_t input,
6382 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006383{
Eric Laurent1c333e22014-05-20 10:48:17 -07006384 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006385 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006386}
Eric Laurente552edb2014-03-10 17:42:56 -07006387
François Gaffie11d30102018-11-02 16:09:09 +01006388status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006389 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006390 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006391{
François Gaffie11d30102018-11-02 16:09:09 +01006392 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006393 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006394 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006395
François Gaffie11d30102018-11-02 16:09:09 +01006396 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006397 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006398 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006399 }
Eric Laurente552edb2014-03-10 17:42:56 -07006400
Eric Laurent3b73df72014-03-11 09:06:29 -07006401 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006402 // first call getAudioPort to get the supported attributes from the HAL
6403 struct audio_port_v7 port = {};
6404 device->toAudioPort(&port);
6405 status_t status = mpClientInterface->getAudioPort(&port);
6406 if (status == NO_ERROR) {
6407 device->importAudioPort(port);
6408 }
6409
6410 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006411 for (size_t i = 0; i < mOutputs.size(); i++) {
6412 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006413 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006414 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006415 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6416 mOutputs.keyAt(i), device->toString().c_str());
6417 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006418 }
6419 }
6420 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006421 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006422 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006423 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6424 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006425 if (profile->supportsDevice(device)) {
6426 profiles.add(profile);
6427 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6428 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006429 }
6430 }
6431 }
6432
Eric Laurent7b279bb2015-12-14 10:18:23 -08006433 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006434
Eric Laurente552edb2014-03-10 17:42:56 -07006435 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006436 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006437 return BAD_VALUE;
6438 }
6439
6440 // open outputs for matching profiles if needed. Direct outputs are also opened to
6441 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6442 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006443 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006444
6445 // nothing to do if one output is already opened for this profile
6446 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006447 for (j = 0; j < outputs.size(); j++) {
6448 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006449 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006450 // matching profile: save the sample rates, format and channel masks supported
6451 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006452 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006453 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006454 }
Eric Laurente552edb2014-03-10 17:42:56 -07006455 break;
6456 }
6457 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006458 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006459 continue;
6460 }
6461
Eric Laurent3974e3b2017-12-07 17:58:43 -08006462 if (!profile->canOpenNewIo()) {
6463 ALOGW("Max Output number %u already opened for this profile %s",
6464 profile->maxOpenCount, profile->getTagName().c_str());
6465 continue;
6466 }
6467
Eric Laurent83efe1c2017-07-09 16:51:08 -07006468 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006469 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006470 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6471 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006472 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006473 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006474 profiles.removeAt(profile_index);
6475 profile_index--;
6476 } else {
6477 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006478 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006479 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006480 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6481 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006482 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006483 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006484
François Gaffie11d30102018-11-02 16:09:09 +01006485 if (device_distinguishes_on_address(deviceType)) {
6486 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6487 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306488 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6489 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006490 }
Eric Laurente552edb2014-03-10 17:42:56 -07006491 ALOGV("checkOutputsForDevice(): adding output %d", output);
6492 }
6493 }
6494
6495 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006496 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006497 return BAD_VALUE;
6498 }
Eric Laurentd4692962014-05-05 18:13:44 -07006499 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006500 // check if one opened output is not needed any more after disconnecting one device
6501 for (size_t i = 0; i < mOutputs.size(); i++) {
6502 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006503 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006504 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006505 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006506 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006507 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006508 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006509 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6510 mOutputs.keyAt(i));
6511 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006512 }
Eric Laurente552edb2014-03-10 17:42:56 -07006513 }
6514 }
Eric Laurentd4692962014-05-05 18:13:44 -07006515 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006516 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006517 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6518 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006519 if (!profile->supportsDevice(device)) {
6520 continue;
6521 }
6522 ALOGV("checkOutputsForDevice(): "
6523 "clearing direct output profile %zu on module %s",
6524 j, hwModule->getName());
6525 profile->clearAudioProfiles();
6526 if (!profile->hasDynamicAudioProfile()) {
6527 continue;
6528 }
6529 // When a device is disconnected, if there is an IOProfile that contains dynamic
6530 // profiles and supports the disconnected device, call getAudioPort to repopulate
6531 // the capabilities of the devices that is supported by the IOProfile.
6532 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6533 if (supportedDevice == device ||
6534 !mAvailableOutputDevices.contains(supportedDevice)) {
6535 continue;
6536 }
6537 struct audio_port_v7 port;
6538 supportedDevice->toAudioPort(&port);
6539 status_t status = mpClientInterface->getAudioPort(&port);
6540 if (status == NO_ERROR) {
6541 supportedDevice->importAudioPort(port);
6542 }
Eric Laurente552edb2014-03-10 17:42:56 -07006543 }
6544 }
6545 }
6546 }
6547 return NO_ERROR;
6548}
6549
François Gaffie11d30102018-11-02 16:09:09 +01006550status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006551 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006552{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006553 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006554
François Gaffie11d30102018-11-02 16:09:09 +01006555 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006556 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006557 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006558 }
6559
Eric Laurentd4692962014-05-05 18:13:44 -07006560 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006561 // first call getAudioPort to get the supported attributes from the HAL
6562 struct audio_port_v7 port = {};
6563 device->toAudioPort(&port);
6564 status_t status = mpClientInterface->getAudioPort(&port);
6565 if (status == NO_ERROR) {
6566 device->importAudioPort(port);
6567 }
6568
Eric Laurent0dd51852019-04-19 18:18:58 -07006569 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006570 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006571 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006572 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006573 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006574 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006575 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006576
François Gaffie11d30102018-11-02 16:09:09 +01006577 if (profile->supportsDevice(device)) {
6578 profiles.add(profile);
6579 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6580 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006581 }
6582 }
6583 }
6584
Eric Laurent0dd51852019-04-19 18:18:58 -07006585 if (profiles.isEmpty()) {
6586 ALOGW("%s: No input profile available for device %s",
6587 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006588 return BAD_VALUE;
6589 }
6590
6591 // open inputs for matching profiles if needed. Direct inputs are also opened to
6592 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6593 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6594
Eric Laurent1c333e22014-05-20 10:48:17 -07006595 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006596
Eric Laurentd4692962014-05-05 18:13:44 -07006597 // nothing to do if one input is already opened for this profile
6598 size_t input_index;
6599 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6600 desc = mInputs.valueAt(input_index);
6601 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006602 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006603 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006604 }
Eric Laurentd4692962014-05-05 18:13:44 -07006605 break;
6606 }
6607 }
6608 if (input_index != mInputs.size()) {
6609 continue;
6610 }
6611
Eric Laurent3974e3b2017-12-07 17:58:43 -08006612 if (!profile->canOpenNewIo()) {
6613 ALOGW("Max Input number %u already opened for this profile %s",
6614 profile->maxOpenCount, profile->getTagName().c_str());
6615 continue;
6616 }
6617
Eric Laurentfe231122017-11-17 17:48:06 -08006618 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006619 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006620 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006621
Eric Laurentcf2c0212014-07-25 16:20:43 -07006622 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006623 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006624 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006625 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006626 mpClientInterface->setParameters(input, String8(param));
6627 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006628 }
François Gaffie11d30102018-11-02 16:09:09 +01006629 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006630 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006631 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006632 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006633 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006634 }
6635
Eric Laurent0dd51852019-04-19 18:18:58 -07006636 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006637 addInput(input, desc);
6638 }
6639 } // endif input != 0
6640
Eric Laurentcf2c0212014-07-25 16:20:43 -07006641 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006642 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006643 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006644 profiles.removeAt(profile_index);
6645 profile_index--;
6646 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006647 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006648 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006649 }
Eric Laurentd4692962014-05-05 18:13:44 -07006650 ALOGV("checkInputsForDevice(): adding input %d", input);
6651 }
6652 } // end scan profiles
6653
6654 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006655 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006656 return BAD_VALUE;
6657 }
6658 } else {
6659 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006660 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006661 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006662 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006663 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006664 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006665 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006666 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006667 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6668 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006669 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006670 }
6671 }
6672 }
6673 } // end disconnect
6674
6675 return NO_ERROR;
6676}
6677
6678
Eric Laurente0720872014-03-11 09:30:41 -07006679void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006680{
6681 ALOGV("closeOutput(%d)", output);
6682
François Gaffie1c878552018-11-22 16:53:21 +01006683 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6684 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006685 ALOGW("closeOutput() unknown output %d", output);
6686 return;
6687 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006688 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006689 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006690
Eric Laurente552edb2014-03-10 17:42:56 -07006691 // look for duplicated outputs connected to the output being removed.
6692 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006693 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6694 if (dupOutput->isDuplicated() &&
6695 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6696 sp<SwAudioOutputDescriptor> remainingOutput =
6697 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006698 // As all active tracks on duplicated output will be deleted,
6699 // and as they were also referenced on the other output, the reference
6700 // count for their stream type must be adjusted accordingly on
6701 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006702 const bool wasActive = remainingOutput->isActive();
6703 // Note: no-op on the closing output where all clients has already been set inactive
6704 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006705 // stop() will be a no op if the output is still active but is needed in case all
6706 // active streams refcounts where cleared above
6707 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006708 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006709 }
Eric Laurente552edb2014-03-10 17:42:56 -07006710 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6711 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6712
6713 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006714 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006715 }
6716 }
6717
Eric Laurent05b90f82014-08-27 15:32:29 -07006718 nextAudioPortGeneration();
6719
François Gaffie1c878552018-11-22 16:53:21 +01006720 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006721 if (index >= 0) {
6722 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006723 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6724 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006725 mAudioPatches.removeItemsAt(index);
6726 mpClientInterface->onAudioPatchListUpdate();
6727 }
6728
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006729 if (closingOutputWasActive) {
6730 closingOutput->stop();
6731 }
François Gaffie1c878552018-11-22 16:53:21 +01006732 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006733
François Gaffie53615e22015-03-19 09:24:12 +01006734 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006735 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006736 if (closingOutput == mSpatializerOutput) {
6737 mSpatializerOutput.clear();
6738 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006739
6740 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6741 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006742 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006743 bool directOutputOpen = false;
6744 for (size_t i = 0; i < mOutputs.size(); i++) {
6745 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6746 directOutputOpen = true;
6747 break;
6748 }
6749 }
6750 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006751 ALOGV("no direct outputs open, reset MSD patches");
6752 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6753 // how output devices for patching are resolved. Avoid by caching and reusing the
6754 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6755 // devices to patch to. This may be complicated by the fact that devices may become
6756 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006757 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006758 }
6759 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006760}
6761
6762void AudioPolicyManager::closeInput(audio_io_handle_t input)
6763{
6764 ALOGV("closeInput(%d)", input);
6765
6766 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6767 if (inputDesc == NULL) {
6768 ALOGW("closeInput() unknown input %d", input);
6769 return;
6770 }
6771
Eric Laurent6a94d692014-05-20 11:18:06 -07006772 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006773
François Gaffie11d30102018-11-02 16:09:09 +01006774 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006775 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006776 if (index >= 0) {
6777 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006778 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6779 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006780 mAudioPatches.removeItemsAt(index);
6781 mpClientInterface->onAudioPatchListUpdate();
6782 }
6783
François Gaffie6ebbce02023-07-19 13:27:53 +02006784 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006785 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006786 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006787
François Gaffie11d30102018-11-02 16:09:09 +01006788 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6789 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006790 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006791 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006792 }
Eric Laurente552edb2014-03-10 17:42:56 -07006793}
6794
François Gaffie11d30102018-11-02 16:09:09 +01006795SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6796 const DeviceVector &devices,
6797 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006798{
6799 SortedVector<audio_io_handle_t> outputs;
6800
François Gaffie11d30102018-11-02 16:09:09 +01006801 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006802 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006803 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006804 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006805 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006806 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006807 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006808 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006809 outputs.add(openOutputs.keyAt(i));
6810 }
6811 }
6812 return outputs;
6813}
6814
Mikhail Naganov37977152018-07-11 15:54:44 -07006815void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6816{
6817 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6818 // output is suspended before any tracks are moved to it
6819 checkA2dpSuspend();
6820 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006821 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006822 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006823 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006824 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006825 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6826 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6827 // configuration changes will ultimately be rerouted correctly. We can still avoid
6828 // unnecessary rerouting by caching and reusing the arguments to
6829 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6830 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006831 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006832 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006833 // an event that changed routing likely occurred, inform upper layers
6834 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006835}
6836
François Gaffiec005e562018-11-06 15:04:49 +01006837bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6838 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006839{
François Gaffiec005e562018-11-06 15:04:49 +01006840 return mEngine->getProductStrategyForAttributes(lAttr) ==
6841 mEngine->getProductStrategyForAttributes(rAttr);
6842}
6843
Francois Gaffieff1eb522020-05-06 18:37:04 +02006844void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6845{
6846 for (size_t i = 0; i < mAudioSources.size(); i++) {
6847 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6848 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006849 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006850 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006851 connectAudioSource(sourceDesc);
6852 }
6853 }
6854}
6855
6856void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6857{
6858 for (size_t i = 0; i < mAudioSources.size(); i++) {
6859 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6860 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6861 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6862 disconnectAudioSource(sourceDesc);
6863 }
6864 }
6865}
6866
François Gaffiec005e562018-11-06 15:04:49 +01006867void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6868{
6869 auto psId = mEngine->getProductStrategyForAttributes(attr);
6870
6871 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6872 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006873
François Gaffie11d30102018-11-02 16:09:09 +01006874 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6875 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006876
Eric Laurentc209fe42020-06-05 18:11:23 -07006877 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006878 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006879 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006880 // take into account dynamic audio policies related changes: if a client is now associated
6881 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006882 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006883 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6884 if (desc->isDuplicated()) {
6885 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006886 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006887 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6888 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6889 continue;
6890 }
6891 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006892 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006893 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6894 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6895 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006896 if (status != OK) {
6897 continue;
6898 }
yucliuf4de36d2020-09-14 14:57:56 -07006899 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006900 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006901 maxLatency = desc->latency();
6902 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006903 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006904 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006905 }
6906 }
6907
Eric Laurent56ed8842022-11-15 16:04:41 +01006908 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006909 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6910 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006911 for (audio_io_handle_t srcOut : srcOutputs) {
6912 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006913 if (desc == nullptr) continue;
6914
6915 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006916 maxLatency = desc->latency();
6917 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006918
Eric Laurent56ed8842022-11-15 16:04:41 +01006919 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006920 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006921 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006922 // a client on a non direct outputs has necessarily a linear PCM format
6923 // so we can call selectOutput() safely
6924 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6925 client->flags(),
6926 client->config().format,
6927 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006928 client->config().sample_rate,
6929 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006930 if (newOutput != srcOut) {
6931 invalidate = true;
6932 break;
6933 }
6934 } else {
6935 sp<IOProfile> profile = getProfileForOutput(newDevices,
6936 client->config().sample_rate,
6937 client->config().format,
6938 client->config().channel_mask,
6939 client->flags(),
6940 true /* directOnly */);
6941 if (profile != desc->mProfile) {
6942 invalidate = true;
6943 break;
6944 }
6945 }
6946 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006947 // mute strategy while moving tracks from one output to another
6948 if (invalidate) {
6949 invalidatedOutputs.push_back(desc);
6950 if (desc->isStrategyActive(psId)) {
6951 setStrategyMute(psId, true, desc);
6952 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6953 newDevices.types());
6954 }
Eric Laurente552edb2014-03-10 17:42:56 -07006955 }
François Gaffiec005e562018-11-06 15:04:49 +01006956 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006957 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006958 connectAudioSource(source);
6959 }
Eric Laurente552edb2014-03-10 17:42:56 -07006960 }
6961
Eric Laurent56ed8842022-11-15 16:04:41 +01006962 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6963 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6964 std::to_string(srcOutputs[0]).c_str(),
6965 std::to_string(dstOutputs[0]).c_str());
6966
François Gaffiec005e562018-11-06 15:04:49 +01006967 // Move effects associated to this stream from previous output to new output
6968 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006969 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006970 }
François Gaffiec005e562018-11-06 15:04:49 +01006971 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006972 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006973 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006974 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006975 desc->setTracksInvalidatedStatusByStrategy(psId);
6976 }
Eric Laurente552edb2014-03-10 17:42:56 -07006977 }
6978 }
6979}
6980
Eric Laurente0720872014-03-11 09:30:41 -07006981void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006982{
François Gaffiec005e562018-11-06 15:04:49 +01006983 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6984 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6985 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006986 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006987 }
Eric Laurente552edb2014-03-10 17:42:56 -07006988}
6989
Kevin Rocard153f92d2018-12-18 18:33:28 -08006990void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006991 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006992 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006993 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006994 for (size_t i = 0; i < mOutputs.size(); i++) {
6995 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6996 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006997 sp<AudioPolicyMix> primaryMix;
6998 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006999 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007000 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7001 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7002 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007003 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7004 for (auto &secondaryMix : secondaryMixes) {
7005 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7006 if (outputDesc != nullptr &&
7007 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7008 secondaryDescs.push_back(outputDesc);
7009 }
7010 }
7011
jiabinc44b3462022-12-08 12:52:31 -08007012 if (status != OK &&
7013 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7014 // When it failed to query secondary output, only invalidate the client that is not
7015 // MMAP. The reason is that MMAP stream will not support secondary output.
7016 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007017 } else if (!std::equal(
7018 client->getSecondaryOutputs().begin(),
7019 client->getSecondaryOutputs().end(),
7020 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007021 if (!audio_is_linear_pcm(client->config().format)) {
7022 // If the format is not PCM, the tracks should be invalidated to get correct
7023 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007024 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007025 } else {
7026 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7027 std::vector<audio_io_handle_t> secondaryOutputIds;
7028 for (const auto &secondaryDesc: secondaryDescs) {
7029 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7030 weakSecondaryDescs.push_back(secondaryDesc);
7031 }
7032 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7033 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007034 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007035 }
7036 }
7037 }
jiabin10a03f12021-05-07 23:46:28 +00007038 if (!trackSecondaryOutputs.empty()) {
7039 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7040 }
jiabinc44b3462022-12-08 12:52:31 -08007041 if (!clientsToInvalidate.empty()) {
7042 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7043 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007044 }
7045}
7046
Eric Laurent2517af32020-11-25 15:31:27 +01007047bool AudioPolicyManager::isScoRequestedForComm() const {
7048 AudioDeviceTypeAddrVector devices;
7049 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7050 for (const auto &device : devices) {
7051 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7052 return true;
7053 }
7054 }
7055 return false;
7056}
7057
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007058bool AudioPolicyManager::isHearingAidUsedForComm() const {
7059 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7060 true /*fromCache*/);
7061 for (const auto &device : devices) {
7062 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7063 return true;
7064 }
7065 }
7066 return false;
7067}
7068
7069
Eric Laurente0720872014-03-11 09:30:41 -07007070void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007071{
François Gaffie53615e22015-03-19 09:24:12 +01007072 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007073 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007074 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007075 return;
7076 }
7077
Eric Laurent3a4311c2014-03-17 12:00:47 -07007078 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007079 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7080 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007081 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007082
7083 // if suspended, restore A2DP output if:
7084 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007085 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007086 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007087 //
Eric Laurentf732e072016-08-03 19:30:28 -07007088 // if not suspended, suspend A2DP output if:
7089 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007090 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007091 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007092 //
7093 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007094 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007095 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007096 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007097 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007098
7099 mpClientInterface->restoreOutput(a2dpOutput);
7100 mA2dpSuspended = false;
7101 }
7102 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007103 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007104 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007105 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007106 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007107
7108 mpClientInterface->suspendOutput(a2dpOutput);
7109 mA2dpSuspended = true;
7110 }
7111 }
7112}
7113
François Gaffie11d30102018-11-02 16:09:09 +01007114DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7115 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007116{
François Gaffie11d30102018-11-02 16:09:09 +01007117 DeviceVector devices;
7118
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007119 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007120 if (index >= 0) {
7121 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007122 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007123 ALOGV("%s device %s forced by patch %d", __func__,
7124 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7125 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007126 }
7127 }
7128
Dean Wheatley514b4312020-06-17 21:45:00 +10007129 // Do not retrieve engine device for outputs through MSD
7130 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7131 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7132 return outputDesc->devices();
7133 }
7134
Eric Laurent97ac8712018-07-27 18:59:02 -07007135 // Honor explicit routing requests only if no client using default routing is active on this
7136 // input: a specific app can not force routing for other apps by setting a preferred device.
7137 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007138 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007139 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007140 if (device != nullptr) {
7141 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007142 }
7143
François Gaffiea807ef92018-11-05 10:44:33 +01007144 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7145 // of setForceUse / Default Bus device here
7146 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7147 if (device != nullptr) {
7148 return DeviceVector(device);
7149 }
7150
François Gaffiec005e562018-11-06 15:04:49 +01007151 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7152 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7153 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307154 auto hasStreamActive = [&](auto stream) {
7155 return hasStream(streams, stream) && isStreamActive(stream, 0);
7156 };
Eric Laurent484e9272018-06-07 17:29:23 -07007157
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307158 auto doGetOutputDevicesForVoice = [&]() {
7159 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007160 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307161 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007162 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7163 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307164 };
7165
7166 // With low-latency playing on speaker, music on WFD, when the first low-latency
7167 // output is stopped, getNewOutputDevices checks for a product strategy
7168 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007169 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307170 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7171 // stream is associated to the output descriptor.
7172 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7173 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7174 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7175 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007176 // Retrieval of devices for voice DL is done on primary output profile, cannot
7177 // check the route (would force modifying configuration file for this profile)
7178 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7179 break;
7180 }
Eric Laurente552edb2014-03-10 17:42:56 -07007181 }
François Gaffiec005e562018-11-06 15:04:49 +01007182 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007183 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007184}
7185
François Gaffie11d30102018-11-02 16:09:09 +01007186sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7187 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007188{
François Gaffie11d30102018-11-02 16:09:09 +01007189 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007190
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007191 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007192 if (index >= 0) {
7193 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007194 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007195 ALOGV("getNewInputDevice() device %s forced by patch %d",
7196 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7197 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007198 }
7199 }
7200
Eric Laurent97ac8712018-07-27 18:59:02 -07007201 // Honor explicit routing requests only if no client using default routing is active on this
7202 // input: a specific app can not force routing for other apps by setting a preferred device.
7203 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007204 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7205 if (device != nullptr) {
7206 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007207 }
7208
Eric Laurentdc95a252018-04-12 12:46:56 -07007209 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007210 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007211 audio_attributes_t attributes;
7212 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007213 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007214 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7215 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007216 attributes = topClient->attributes();
7217 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007218 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007219 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007220 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7221 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007222 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007223 }
7224
Francois Gaffie716e1432019-01-14 16:58:59 +01007225 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7226 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007227 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007228 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007229 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007230 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007231
Eric Laurente552edb2014-03-10 17:42:56 -07007232 return device;
7233}
7234
Eric Laurent794fde22016-03-11 09:50:45 -08007235bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7236 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007237 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007238}
7239
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007240status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007241 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007242 if (devices == nullptr) {
7243 return BAD_VALUE;
7244 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007245
Andy Hung6d23c0f2022-02-16 09:37:15 -08007246 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007247 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7248 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007249 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007250 for (const auto& device : curDevices) {
7251 devices->push_back(device->getDeviceTypeAddr());
7252 }
7253 return NO_ERROR;
7254}
7255
Eric Laurente0720872014-03-11 09:30:41 -07007256void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007257 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007258 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007259 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007260 updateDevicesAndOutputs();
7261 break;
7262 default:
7263 break;
7264 }
7265}
7266
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007267uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007268
7269 // skip beacon mute management if a dedicated TTS output is available
7270 if (mTtsOutputAvailable) {
7271 return 0;
7272 }
7273
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007274 switch(event) {
7275 case STARTING_OUTPUT:
7276 mBeaconMuteRefCount++;
7277 break;
7278 case STOPPING_OUTPUT:
7279 if (mBeaconMuteRefCount > 0) {
7280 mBeaconMuteRefCount--;
7281 }
7282 break;
7283 case STARTING_BEACON:
7284 mBeaconPlayingRefCount++;
7285 break;
7286 case STOPPING_BEACON:
7287 if (mBeaconPlayingRefCount > 0) {
7288 mBeaconPlayingRefCount--;
7289 }
7290 break;
7291 }
7292
7293 if (mBeaconMuteRefCount > 0) {
7294 // any playback causes beacon to be muted
7295 return setBeaconMute(true);
7296 } else {
7297 // no other playback: unmute when beacon starts playing, mute when it stops
7298 return setBeaconMute(mBeaconPlayingRefCount == 0);
7299 }
7300}
7301
7302uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7303 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7304 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7305 // keep track of muted state to avoid repeating mute/unmute operations
7306 if (mBeaconMuted != mute) {
7307 // mute/unmute AUDIO_STREAM_TTS on all outputs
7308 ALOGV("\t muting %d", mute);
7309 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007310 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7311 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7312 ALOGV("\t no tts volume source available");
7313 return 0;
7314 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007315 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007316 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007317 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007318 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007319 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007320 maxLatency = latency;
7321 }
7322 }
7323 mBeaconMuted = mute;
7324 return maxLatency;
7325 }
7326 return 0;
7327}
7328
Eric Laurente0720872014-03-11 09:30:41 -07007329void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007330{
François Gaffiec005e562018-11-06 15:04:49 +01007331 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007332 mPreviousOutputs = mOutputs;
7333}
7334
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007335uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007336 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007337 uint32_t delayMs)
7338{
7339 // mute/unmute strategies using an incompatible device combination
7340 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7341 // if unmuting, unmute only after the specified delay
7342 if (outputDesc->isDuplicated()) {
7343 return 0;
7344 }
7345
7346 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007347 DeviceVector devices = outputDesc->devices();
7348 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007349
François Gaffiec005e562018-11-06 15:04:49 +01007350 auto productStrategies = mEngine->getOrderedProductStrategies();
7351 for (const auto &productStrategy : productStrategies) {
7352 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7353 DeviceVector curDevices =
7354 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7355 curDevices = curDevices.filter(outputDesc->supportedDevices());
7356 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007357 bool doMute = false;
7358
François Gaffiec005e562018-11-06 15:04:49 +01007359 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007360 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007361 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7362 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007363 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007364 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007365 }
Eric Laurent99401132014-05-07 19:48:15 -07007366 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007367 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007368 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007369 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007370 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007371 continue;
7372 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307373 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007374 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7375 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7376 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007377 if (mute) {
7378 // FIXME: should not need to double latency if volume could be applied
7379 // immediately by the audioflinger mixer. We must account for the delay
7380 // between now and the next time the audioflinger thread for this output
7381 // will process a buffer (which corresponds to one buffer size,
7382 // usually 1/2 or 1/4 of the latency).
7383 if (muteWaitMs < desc->latency() * 2) {
7384 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007385 }
7386 }
7387 }
7388 }
7389 }
7390 }
7391
Eric Laurent99401132014-05-07 19:48:15 -07007392 // temporary mute output if device selection changes to avoid volume bursts due to
7393 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007394 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007395 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007396
Eric Laurentdc462862016-07-19 12:29:53 -07007397 if (muteWaitMs < tempMuteWaitMs) {
7398 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007399 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007400
7401 // If recommended duration is defined, replace temporary mute duration to avoid
7402 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7403 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7404 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7405 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7406 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7407
François Gaffieaaac0fd2018-11-22 17:56:39 +01007408 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7409 // make sure that we do not start the temporary mute period too early in case of
7410 // delayed device change
7411 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7412 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007413 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007414 }
7415 }
7416
Eric Laurente552edb2014-03-10 17:42:56 -07007417 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7418 if (muteWaitMs > delayMs) {
7419 muteWaitMs -= delayMs;
7420 usleep(muteWaitMs * 1000);
7421 return muteWaitMs;
7422 }
7423 return 0;
7424}
7425
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307426uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7427 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007428 const DeviceVector &devices,
7429 bool force,
7430 int delayMs,
7431 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007432 bool requiresMuteCheck, bool requiresVolumeCheck,
7433 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007434{
jiabin3ff8d7d2022-12-13 06:27:44 +00007435 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307436 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7437 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7438 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007439 uint32_t muteWaitMs;
7440
7441 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307442 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007443 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307444 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007445 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007446 return muteWaitMs;
7447 }
Eric Laurente552edb2014-03-10 17:42:56 -07007448
7449 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007450 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007451 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007452 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007453
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307454 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7455 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007456
7457 if (!filteredDevices.isEmpty()) {
7458 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007459 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007460
7461 // if the outputs are not materially active, there is no need to mute.
7462 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007463 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007464 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307465 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7466 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007467 muteWaitMs = 0;
7468 }
Eric Laurente552edb2014-03-10 17:42:56 -07007469
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007470 bool outputRouted = outputDesc->isRouted();
7471
Eric Laurent79ea9582020-06-11 18:49:24 -07007472 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7473 // output profile or if new device is not supported AND previous device(s) is(are) still
7474 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007475 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307476 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7477 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007478 // restore previous device after evaluating strategy mute state
7479 outputDesc->setDevices(prevDevices);
7480 return muteWaitMs;
7481 }
7482
Eric Laurente552edb2014-03-10 17:42:56 -07007483 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007484 // the requested device is AUDIO_DEVICE_NONE
7485 // OR the requested device is the same as current device
7486 // AND force is not specified
7487 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007488 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007489 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307490 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7491 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7492 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007493 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307494 ALOGV("%s %s setting same device on routed output, force apply volumes",
7495 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007496 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7497 }
Eric Laurente552edb2014-03-10 17:42:56 -07007498 return muteWaitMs;
7499 }
7500
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307501 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7502 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007503
Eric Laurente552edb2014-03-10 17:42:56 -07007504 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007505 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007506 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007507 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007508 PatchBuilder patchBuilder;
7509 patchBuilder.addSource(outputDesc);
7510 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7511 for (const auto &filteredDevice : filteredDevices) {
7512 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007513 }
7514
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007515 // Add half reported latency to delayMs when muteWaitMs is null in order
7516 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007517 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7518 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7519 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007520 }
Eric Laurente552edb2014-03-10 17:42:56 -07007521
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007522 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7523 if (!skipMuteDelay) {
7524 // update stream volumes according to new device
7525 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7526 }
Eric Laurente552edb2014-03-10 17:42:56 -07007527
7528 return muteWaitMs;
7529}
7530
Eric Laurentc75307b2015-03-17 15:29:32 -07007531status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007532 int delayMs,
7533 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007534{
Eric Laurent6a94d692014-05-20 11:18:06 -07007535 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007536 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7537 return INVALID_OPERATION;
7538 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007539 if (patchHandle) {
7540 index = mAudioPatches.indexOfKey(*patchHandle);
7541 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007542 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007543 }
7544 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007545 return INVALID_OPERATION;
7546 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007547 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007548 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007549 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007550 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007551 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007552 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007553 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007554 return status;
7555}
7556
7557status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007558 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007559 bool force,
7560 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007561{
7562 status_t status = NO_ERROR;
7563
Eric Laurent1f2f2232014-06-02 12:01:23 -07007564 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007565 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7566 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007567
François Gaffie11d30102018-11-02 16:09:09 +01007568 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007569 PatchBuilder patchBuilder;
7570 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007571 // AUDIO_SOURCE_HOTWORD is for internal use only:
7572 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007573 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7574 auto result = usecase;
7575 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7576 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7577 }
7578 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007579 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007580 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007581 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007582 }
7583 }
7584 return status;
7585}
7586
Eric Laurent6a94d692014-05-20 11:18:06 -07007587status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7588 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007589{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007590 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007591 ssize_t index;
7592 if (patchHandle) {
7593 index = mAudioPatches.indexOfKey(*patchHandle);
7594 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007595 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007596 }
7597 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007598 return INVALID_OPERATION;
7599 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007600 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007601 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007602 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007603 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007604 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007605 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007606 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007607 return status;
7608}
7609
François Gaffie11d30102018-11-02 16:09:09 +01007610sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007611 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007612 audio_format_t& format,
7613 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007614 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007615{
7616 // Choose an input profile based on the requested capture parameters: select the first available
7617 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007618 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007619 //
7620 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7621 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007622
Atneya Nair0f0a8032022-12-12 16:20:12 -08007623 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7624 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7625 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7626
7627 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007628
jiabin2fd710d2022-05-02 23:20:22 +00007629 for (;;) {
7630 sp<IOProfile> firstInexact = nullptr;
7631 uint32_t updatedSamplingRate = 0;
7632 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7633 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7634 for (const auto& hwModule : mHwModules) {
7635 for (const auto& profile : hwModule->getInputProfiles()) {
7636 // profile->log();
7637 //updatedFormat = format;
7638 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7639 &samplingRate /*updatedSamplingRate*/,
7640 format,
7641 &format, /*updatedFormat*/
7642 channelMask,
7643 &channelMask /*updatedChannelMask*/,
7644 // FIXME ugly cast
7645 (audio_output_flags_t) flags,
7646 true /*exactMatchRequiredForInputFlags*/)) {
7647 return profile;
7648 }
7649 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7650 samplingRate,
7651 &updatedSamplingRate,
7652 format,
7653 &updatedFormat,
7654 channelMask,
7655 &updatedChannelMask,
7656 // FIXME ugly cast
7657 (audio_output_flags_t) flags,
7658 false /*exactMatchRequiredForInputFlags*/)) {
7659 firstInexact = profile;
7660 }
7661 }
7662 }
7663
7664 if (firstInexact != nullptr) {
7665 samplingRate = updatedSamplingRate;
7666 format = updatedFormat;
7667 channelMask = updatedChannelMask;
7668 return firstInexact;
7669 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7670 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7671 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7672 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7673 flags = AUDIO_INPUT_FLAG_NONE;
7674 } else { // fail
7675 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7676 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7677 samplingRate, format, channelMask, oriFlags);
7678 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007679 }
7680 }
jiabin2fd710d2022-05-02 23:20:22 +00007681
7682 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007683}
7684
François Gaffieaaac0fd2018-11-22 17:56:39 +01007685float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7686 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007687 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007688 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007689{
jiabin9a3361e2019-10-01 09:38:30 -07007690 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007691
7692 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7693 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7694 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7695 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007696 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7697 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7698 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7699 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7700 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007701
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007702 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007703 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7704 mOutputs.isActive(ringVolumeSrc, 0)) {
7705 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007706 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007707 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007708 }
7709
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007710 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007711 if ((volumeSource != callVolumeSrc && (isInCall() ||
7712 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007713 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007714 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7715 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007716 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7717 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7718 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007719 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007720 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007721 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007722 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007723 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007724 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007725 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7726 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7727 // programmatically muted.
7728 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7729 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7730 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007731 bool exemptFromCapping =
7732 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7733 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007734 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7735 volumeSource, volumeDb);
7736 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007737 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7738 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7739 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007740 }
7741 }
Eric Laurente552edb2014-03-10 17:42:56 -07007742 // if a headset is connected, apply the following rules to ring tones and notifications
7743 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007744 // - always attenuate notifications volume by 6dB
7745 // - attenuate ring tones volume by 6dB unless music is not playing and
7746 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007747 // - if music is playing, always limit the volume to current music volume,
7748 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007749 if (!Intersection(deviceTypes,
7750 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7751 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007752 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7753 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007754 ((volumeSource == alarmVolumeSrc ||
7755 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007756 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7757 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7758 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007759 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7760 curves.canBeMuted()) {
7761
Eric Laurente552edb2014-03-10 17:42:56 -07007762 // when the phone is ringing we must consider that music could have been paused just before
7763 // by the music application and behave as if music was active if the last music track was
7764 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007765 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007766 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007767 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007768 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007769 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7770 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007771 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007772 float musicVolDb = computeVolume(musicCurves,
7773 musicVolumeSrc,
7774 musicCurves.getVolumeIndex(musicDevice),
7775 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007776 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7777 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7778 if (volumeDb > minVolDb) {
7779 volumeDb = minVolDb;
7780 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007781 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007782 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7783 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7784 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007785 // on A2DP, also ensure notification volume is not too low compared to media when
7786 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007787 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007788 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007789 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7790 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007791 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7792 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007793 }
7794 }
jiabin9a3361e2019-10-01 09:38:30 -07007795 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007796 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007797 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007798 }
7799 }
7800
François Gaffie43c73442018-11-08 08:21:55 +01007801 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007802}
7803
Eric Laurent3839bc02018-07-10 18:33:34 -07007804int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007805 VolumeSource fromVolumeSource,
7806 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007807{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007808 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007809 return srcIndex;
7810 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007811 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7812 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007813 float minSrc = (float)srcCurves.getVolumeIndexMin();
7814 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7815 float minDst = (float)dstCurves.getVolumeIndexMin();
7816 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007817
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007818 // preserve mute request or correct range
7819 if (srcIndex < minSrc) {
7820 if (srcIndex == 0) {
7821 return 0;
7822 }
7823 srcIndex = minSrc;
7824 } else if (srcIndex > maxSrc) {
7825 srcIndex = maxSrc;
7826 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007827 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7828}
7829
François Gaffieaaac0fd2018-11-22 17:56:39 +01007830status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7831 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007832 int index,
7833 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007834 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007835 int delayMs,
7836 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007837{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007838 // do not change actual attributes volume if the attributes is muted
7839 if (outputDesc->isMuted(volumeSource)) {
7840 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7841 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007842 return NO_ERROR;
7843 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007844 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7845 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7846 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7847 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007848
Eric Laurent2517af32020-11-25 15:31:27 +01007849 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007850 bool isHAUsed = isHearingAidUsedForComm();
7851
Eric Laurente552edb2014-03-10 17:42:56 -07007852 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007853 // if sco and call follow same curves, bypass forceUseForComm
7854 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007855 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007856 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7857 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007858 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007859 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007860 // Do not return an error here as AudioService will always set both voice call
7861 // and bluetooth SCO volumes due to stream aliasing.
7862 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007863 }
jiabin9a3361e2019-10-01 09:38:30 -07007864 if (deviceTypes.empty()) {
7865 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007866 index = curves.getVolumeIndex(deviceTypes);
7867 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7868 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007869 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007870
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007871 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7872 ALOGE("invalid volume index range");
7873 return BAD_VALUE;
7874 }
7875
jiabin9a3361e2019-10-01 09:38:30 -07007876 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7877 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007878 // Force VoIP volume to max for bluetooth SCO device except if muted
7879 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007880 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007881 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007882 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007883 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007884 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7885 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007886
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007887 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007888 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007889 // 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 +01007890 if (isVoiceVolSrc) {
7891 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007892 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007893 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007894 }
Eric Laurent18fba842016-03-31 14:41:26 -07007895 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007896 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7897 mLastVoiceVolume = voiceVolume;
7898 }
7899 }
Eric Laurente552edb2014-03-10 17:42:56 -07007900 return NO_ERROR;
7901}
7902
Eric Laurentc75307b2015-03-17 15:29:32 -07007903void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007904 const DeviceTypeSet& deviceTypes,
7905 int delayMs,
7906 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007907{
jiabincd510522020-01-22 09:40:55 -08007908 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007909 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7910 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7911 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007912 curves.getVolumeIndex(deviceTypes),
7913 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007914 }
7915}
7916
François Gaffiec005e562018-11-06 15:04:49 +01007917void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7918 bool on,
7919 const sp<AudioOutputDescriptor>& outputDesc,
7920 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007921 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007922{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007923 std::vector<VolumeSource> sourcesToMute;
7924 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7925 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7926 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007927 VolumeSource source = toVolumeSource(attributes, false);
7928 if ((source != VOLUME_SOURCE_NONE) &&
7929 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7930 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007931 sourcesToMute.push_back(source);
7932 }
Eric Laurente552edb2014-03-10 17:42:56 -07007933 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007934 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007935 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007936 }
7937
Eric Laurente552edb2014-03-10 17:42:56 -07007938}
7939
François Gaffieaaac0fd2018-11-22 17:56:39 +01007940void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7941 bool on,
7942 const sp<AudioOutputDescriptor>& outputDesc,
7943 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007944 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007945{
jiabin9a3361e2019-10-01 09:38:30 -07007946 if (deviceTypes.empty()) {
7947 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007948 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007949 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007950 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007951 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007952 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007953 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007954 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7955 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007956 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007957 }
7958 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007959 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7960 // ignored
7961 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007962 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007963 if (!outputDesc->isMuted(volumeSource)) {
7964 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007965 return;
7966 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007967 if (outputDesc->decMuteCount(volumeSource) == 0) {
7968 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007969 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007970 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007971 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007972 delayMs);
7973 }
7974 }
7975}
7976
François Gaffie53615e22015-03-19 09:24:12 +01007977bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7978{
François Gaffiec005e562018-11-06 15:04:49 +01007979 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007980 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7981 return true;
7982 }
7983
7984 // has known usage?
7985 switch (paa->usage) {
7986 case AUDIO_USAGE_UNKNOWN:
7987 case AUDIO_USAGE_MEDIA:
7988 case AUDIO_USAGE_VOICE_COMMUNICATION:
7989 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7990 case AUDIO_USAGE_ALARM:
7991 case AUDIO_USAGE_NOTIFICATION:
7992 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7993 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7994 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7995 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7996 case AUDIO_USAGE_NOTIFICATION_EVENT:
7997 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7998 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7999 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8000 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008001 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008002 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008003 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008004 case AUDIO_USAGE_EMERGENCY:
8005 case AUDIO_USAGE_SAFETY:
8006 case AUDIO_USAGE_VEHICLE_STATUS:
8007 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008008 break;
8009 default:
8010 return false;
8011 }
8012 return true;
8013}
8014
François Gaffie2110e042015-03-24 08:41:51 +01008015audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8016{
8017 return mEngine->getForceUse(usage);
8018}
8019
Eric Laurent96d1dda2022-03-14 17:14:19 +01008020bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008021 return isStateInCall(mEngine->getPhoneState());
8022}
8023
Eric Laurent96d1dda2022-03-14 17:14:19 +01008024bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008025 return is_state_in_call(state);
8026}
8027
Eric Laurentf9cccec2022-11-16 19:12:00 +01008028bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008029 audio_mode_t mode = mEngine->getPhoneState();
8030 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008031 || (mode == AUDIO_MODE_CALL_SCREEN)
8032 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008033}
8034
Eric Laurentf9cccec2022-11-16 19:12:00 +01008035bool AudioPolicyManager::isInCallOrScreening() const {
8036 audio_mode_t mode = mEngine->getPhoneState();
8037 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8038}
8039
Eric Laurentd60560a2015-04-10 11:31:20 -07008040void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8041{
8042 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008043 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008044 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008045 sourceDesc->sinkDevice()->equals(deviceDesc))
8046 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008047 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008048 }
8049 }
8050
8051 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8052 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8053 bool release = false;
8054 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8055 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8056 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8057 source->ext.device.type == deviceDesc->type()) {
8058 release = true;
8059 }
8060 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008061 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008062 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8063 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8064 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008065 sink->ext.device.type == deviceDesc->type() &&
8066 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8067 || strncmp(sink->ext.device.address, address,
8068 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008069 release = true;
8070 }
8071 }
8072 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008073 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8074 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008075 }
8076 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008077
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008078 mInputs.clearSessionRoutesForDevice(deviceDesc);
8079
Francois Gaffie716e1432019-01-14 16:58:59 +01008080 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008081}
8082
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008083void AudioPolicyManager::modifySurroundFormats(
8084 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008085 std::unordered_set<audio_format_t> enforcedSurround(
8086 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008087 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008088 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008089 allSurround.insert(pair.first);
8090 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8091 }
Phil Burk09bc4612016-02-24 15:58:15 -08008092
8093 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8094 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008095 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008096 // This is the resulting set of formats depending on the surround mode:
8097 // 'all surround' = allSurround
8098 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8099 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8100 // 'manual surround' = mManualSurroundFormats
8101 // AUTO: formats v 'enforced surround'
8102 // ALWAYS: formats v 'all surround' v 'enforced surround'
8103 // NEVER: formats ^ 'non-surround'
8104 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008105
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008106 std::unordered_set<audio_format_t> formatSet;
8107 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8108 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008109 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008110 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008111 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008112 formatSet.insert(*formatIter);
8113 }
8114 }
8115 } else {
8116 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8117 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008118 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008119
jiabin81772902018-04-02 17:52:27 -07008120 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008121 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008122 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8123 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8124 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008125 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008126 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8127 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8128 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008129 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008130 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008131 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008132 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008133 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008134 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008135}
8136
jiabin06e4bab2019-07-29 10:13:34 -07008137void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8138 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008139 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8140 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8141
8142 // If NEVER, then remove support for channelMasks > stereo.
8143 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008144 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8145 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008146 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008147 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008148 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008149 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008150 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008151 }
8152 }
jiabin81772902018-04-02 17:52:27 -07008153 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8154 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8155 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008156 bool supports5dot1 = false;
8157 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008158 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008159 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8160 supports5dot1 = true;
8161 break;
8162 }
8163 }
8164 // If not then add 5.1 support.
8165 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008166 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008167 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008168 }
Phil Burk09bc4612016-02-24 15:58:15 -08008169 }
8170}
8171
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008172void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008173 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01008174 AudioProfileVector &profiles)
8175{
8176 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008177 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07008178
François Gaffie112b0af2015-11-19 16:13:25 +01008179 // Format MUST be checked first to update the list of AudioProfile
8180 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008181 reply = mpClientInterface->getParameters(
8182 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008183 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008184 AudioParameter repliedParameters(reply);
jiabinf26596b2023-04-12 18:56:39 +00008185 FormatVector formats;
Eric Laurent62e4bc52016-02-02 18:37:28 -08008186 if (repliedParameters.get(
jiabinf26596b2023-04-12 18:56:39 +00008187 String8(AudioParameter::keyStreamSupportedFormats), reply) == NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008188 formats = formatsFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008189 } else if (devDesc->hasValidAudioProfile()) {
8190 ALOGD("%s: using the device profiles", __func__);
8191 formats = devDesc->getAudioProfiles().getSupportedFormats();
8192 } else {
8193 ALOGE("%s: failed to retrieve format, bailing out", __func__);
François Gaffie112b0af2015-11-19 16:13:25 +01008194 return;
8195 }
Kriti Dangef6be8f2020-11-05 11:58:19 +01008196 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08008197 if (device == AUDIO_DEVICE_OUT_HDMI
8198 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008199 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07008200 }
jiabin3e277cc2019-09-10 14:27:34 -07008201 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01008202 }
François Gaffie112b0af2015-11-19 16:13:25 +01008203
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008204 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabinf26596b2023-04-12 18:56:39 +00008205 std::optional<ChannelMaskSet> channelMasks;
jiabin06e4bab2019-07-29 10:13:34 -07008206 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01008207 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07008208 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01008209
8210 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07008211 reply = mpClientInterface->getParameters(
8212 ioHandle,
8213 requestedParameters.toString() + ";" +
8214 AudioParameter::keyStreamSupportedSamplingRates);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008215 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008216 AudioParameter repliedParameters(reply);
8217 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008218 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008219 samplingRates = samplingRatesFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008220 } else {
8221 samplingRates = devDesc->getAudioProfiles().getSampleRatesFor(format);
François Gaffie112b0af2015-11-19 16:13:25 +01008222 }
8223 }
8224 if (profiles.hasDynamicChannelsFor(format)) {
8225 reply = mpClientInterface->getParameters(ioHandle,
8226 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07008227 AudioParameter::keyStreamSupportedChannels);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008228 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.c_str());
Eric Laurent62e4bc52016-02-02 18:37:28 -08008229 AudioParameter repliedParameters(reply);
8230 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07008231 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008232 channelMasks = channelMasksFromString(reply.c_str());
jiabinf26596b2023-04-12 18:56:39 +00008233 } else {
8234 channelMasks = devDesc->getAudioProfiles().getChannelMasksFor(format);
8235 }
8236 if (channelMasks.has_value() && (device == AUDIO_DEVICE_OUT_HDMI
8237 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD))) {
8238 modifySurroundChannelMasks(&channelMasks.value());
François Gaffie112b0af2015-11-19 16:13:25 +01008239 }
8240 }
jiabin3e277cc2019-09-10 14:27:34 -07008241 addDynamicAudioProfileAndSort(
jiabinf26596b2023-04-12 18:56:39 +00008242 profiles, new AudioProfile(
8243 format, channelMasks.value_or(ChannelMaskSet()), samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01008244 }
8245}
Eric Laurentd60560a2015-04-10 11:31:20 -07008246
Mikhail Naganovdc769682018-05-04 15:34:08 -07008247status_t AudioPolicyManager::installPatch(const char *caller,
8248 audio_patch_handle_t *patchHandle,
8249 AudioIODescriptorInterface *ioDescriptor,
8250 const struct audio_patch *patch,
8251 int delayMs)
8252{
8253 ssize_t index = mAudioPatches.indexOfKey(
8254 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8255 *patchHandle : ioDescriptor->getPatchHandle());
8256 sp<AudioPatch> patchDesc;
8257 status_t status = installPatch(
8258 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8259 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008260 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008261 }
8262 return status;
8263}
8264
8265status_t AudioPolicyManager::installPatch(const char *caller,
8266 ssize_t index,
8267 audio_patch_handle_t *patchHandle,
8268 const struct audio_patch *patch,
8269 int delayMs,
8270 uid_t uid,
8271 sp<AudioPatch> *patchDescPtr)
8272{
8273 sp<AudioPatch> patchDesc;
8274 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8275 if (index >= 0) {
8276 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008277 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008278 }
8279
8280 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8281 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8282 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8283 if (status == NO_ERROR) {
8284 if (index < 0) {
8285 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008286 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008287 } else {
8288 patchDesc->mPatch = *patch;
8289 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008290 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008291 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008292 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008293 }
8294 nextAudioPortGeneration();
8295 mpClientInterface->onAudioPatchListUpdate();
8296 }
8297 if (patchDescPtr) *patchDescPtr = patchDesc;
8298 return status;
8299}
8300
jiabinbce0c1d2020-10-05 11:20:18 -07008301bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8302{
8303 const TrackClientVector activeClients = output->getActiveClients();
8304 if (activeClients.empty()) {
8305 return true;
8306 }
8307 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8308 if (index < 0) {
8309 ALOGE("%s, no audio patch found while there are active clients on output %d",
8310 __func__, output->getId());
8311 return false;
8312 }
8313 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8314 DeviceVector routedDevices;
8315 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8316 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8317 patchDesc->mPatch.sinks[i].id);
8318 if (device == nullptr) {
8319 ALOGE("%s, no audio device found with id(%d)",
8320 __func__, patchDesc->mPatch.sinks[i].id);
8321 return false;
8322 }
8323 routedDevices.add(device);
8324 }
8325 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008326 if (client->isInvalid()) {
8327 // No need to take care about invalidated clients.
8328 continue;
8329 }
jiabinbce0c1d2020-10-05 11:20:18 -07008330 sp<DeviceDescriptor> preferredDevice =
8331 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8332 if (mEngine->getOutputDevicesForAttributes(
8333 client->attributes(), preferredDevice, false) == routedDevices) {
8334 return false;
8335 }
8336 }
8337 return true;
8338}
8339
8340sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008341 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008342 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8343 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008344{
8345 for (const auto& device : devices) {
8346 // TODO: This should be checking if the profile supports the device combo.
8347 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008348 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8349 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008350 return nullptr;
8351 }
8352 }
8353 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8354 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008355 status_t status = desc->open(halConfig, mixerConfig, devices,
8356 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008357 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008358 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008359 return nullptr;
8360 }
8361
8362 // Here is where the out_set_parameters() for card & device gets called
8363 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8364 const audio_devices_t deviceType = device->type();
8365 const String8 &address = String8(device->address().c_str());
8366 if (!address.isEmpty()) {
8367 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8368 mpClientInterface->setParameters(output, String8(param));
8369 free(param);
8370 }
8371 updateAudioProfiles(device, output, profile->getAudioProfiles());
8372 if (!profile->hasValidAudioProfile()) {
8373 ALOGW("%s() missing param", __func__);
8374 desc->close();
8375 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008376 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8377 // Reopen the output with the best audio profile picked by APM when the profile supports
8378 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008379 desc->close();
8380 output = AUDIO_IO_HANDLE_NONE;
8381 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8382 profile->pickAudioProfile(
8383 config.sample_rate, config.channel_mask, config.format);
8384 config.offload_info.sample_rate = config.sample_rate;
8385 config.offload_info.channel_mask = config.channel_mask;
8386 config.offload_info.format = config.format;
8387
jiabina84c3d32022-12-02 18:59:55 +00008388 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008389 if (status != NO_ERROR) {
8390 return nullptr;
8391 }
8392 }
8393
8394 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008395
baek.kim -61c20122022-07-27 10:05:32 +00008396 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8397 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8398
jiabinbce0c1d2020-10-05 11:20:18 -07008399 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8400 sp<AudioPolicyMix> policyMix;
8401 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8402 policyMix->setOutput(desc);
8403 desc->mPolicyMix = policyMix;
8404 } else {
8405 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008406 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008407 }
8408
baek.kim -61c20122022-07-27 10:05:32 +00008409 } else if (hasPrimaryOutput() && speaker != nullptr
8410 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008411 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8412 // no duplicated output for:
8413 // - direct outputs
8414 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008415 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008416 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8417
8418 //TODO: configure audio effect output stage here
8419
8420 // open a duplicating output thread for the new output and the primary output
8421 sp<SwAudioOutputDescriptor> dupOutputDesc =
8422 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8423 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8424 if (status == NO_ERROR) {
8425 // add duplicated output descriptor
8426 addOutput(duplicatedOutput, dupOutputDesc);
8427 } else {
8428 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8429 mPrimaryOutput->mIoHandle, output);
8430 desc->close();
8431 removeOutput(output);
8432 nextAudioPortGeneration();
8433 return nullptr;
8434 }
8435 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008436 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8437 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8438 mPrimaryOutput = desc;
8439 }
jiabinbce0c1d2020-10-05 11:20:18 -07008440 return desc;
8441}
8442
jiabinf1c73972022-04-14 16:28:52 -07008443status_t AudioPolicyManager::getDevicesForAttributes(
8444 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8445 // Devices are determined in the following precedence:
8446 //
8447 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8448 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8449 //
8450 // If no such dynamic policy then
8451 // 2) Devices containing an active client using setPreferredDevice
8452 // with same strategy as the attributes.
8453 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8454 //
8455 // If no corresponding active client with setPreferredDevice then
8456 // 3) Devices associated with the strategy determined by the attributes
8457 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8458 //
8459 // See related getOutputForAttrInt().
8460
8461 // check dynamic policies but only for primary descriptors (secondary not used for audible
8462 // audio routing, only used for duplication for playback capture)
8463 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008464 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008465 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008466 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8467 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8468 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008469 if (status != OK) {
8470 return status;
8471 }
8472
8473 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8474 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8475 // as they are unaffected by device/stream volume
8476 // (per SwAudioOutputDescriptor::isFixedVolume()).
8477 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8478 ) {
8479 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8480 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8481 devices.add(deviceDesc);
8482 } else {
8483 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8484 // which selects setPreferredDevice if active. This means forVolume call
8485 // will take an active setPreferredDevice, if such exists.
8486
8487 devices = mEngine->getOutputDevicesForAttributes(
8488 attr, nullptr /* preferredDevice */, false /* fromCache */);
8489 }
8490
8491 if (forVolume) {
8492 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8493 // for single volume control in AudioService (such relationship should exist if
8494 // SPEAKER_SAFE is present).
8495 //
8496 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8497 DeviceVector speakerSafeDevices =
8498 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8499 if (!speakerSafeDevices.isEmpty()) {
8500 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8501 devices.remove(speakerSafeDevices);
8502 }
8503 }
8504
8505 return NO_ERROR;
8506}
8507
8508status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8509 AudioProfileVector& audioProfiles,
8510 uint32_t flags,
8511 bool isInput) {
8512 for (const auto& hwModule : mHwModules) {
8513 // the MSD module checks for different conditions
8514 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8515 continue;
8516 }
8517 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8518 : hwModule->getOutputProfiles();
8519 for (const auto& profile : ioProfiles) {
8520 if (!profile->areAllDevicesSupported(devices) ||
8521 !profile->isCompatibleProfileForFlags(
8522 flags, false /*exactMatchRequiredForInputFlags*/)) {
8523 continue;
8524 }
8525 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8526 }
8527 }
8528
8529 if (!isInput) {
8530 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8531 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8532 if (msdModule != nullptr) {
8533 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8534 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8535 for (const auto &profile: msdModule->getOutputProfiles()) {
8536 if (!profile->asAudioPort()->isDirectOutput()) {
8537 continue;
8538 }
8539 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8540 }
8541 } else {
8542 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8543 }
8544 }
8545 }
8546
8547 return NO_ERROR;
8548}
8549
jiabin3ff8d7d2022-12-13 06:27:44 +00008550sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8551 const audio_config_t *config,
8552 audio_output_flags_t flags,
8553 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008554 closeOutput(outputDesc->mIoHandle);
8555 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8556 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8557 if (preferredOutput == nullptr) {
8558 ALOGE("%s failed to reopen output device=%d, caller=%s",
8559 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008560 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008561 return preferredOutput;
8562}
8563
8564void AudioPolicyManager::reopenOutputsWithDevices(
8565 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8566 for (const auto& [output, devices] : outputsToReopen) {
8567 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8568 closeOutput(output);
8569 openOutputWithProfileAndDevice(desc->mProfile, devices);
8570 }
jiabina84c3d32022-12-02 18:59:55 +00008571}
8572
jiabinc44b3462022-12-08 12:52:31 -08008573PortHandleVector AudioPolicyManager::getClientsForStream(
8574 audio_stream_type_t streamType) const {
8575 PortHandleVector clients;
8576 for (size_t i = 0; i < mOutputs.size(); ++i) {
8577 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8578 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8579 }
8580 return clients;
8581}
8582
8583void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8584 PortHandleVector clients;
8585 for (auto stream : streams) {
8586 PortHandleVector clientsForStream = getClientsForStream(stream);
8587 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8588 }
8589 mpClientInterface->invalidateTracks(clients);
8590}
8591
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008592} // namespace android