blob: e8066fbba4e6ec7c010047477a9ce839767b2488 [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{
François Gaffiedb1755b2023-09-01 11:50:35 +0200661 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662 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;
François Gaffiedb1755b2023-09-01 11:50:35 +0200674 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700675 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 }
François Gaffie11d30102018-11-02 16:09:09 +0100678
Francois Gaffie716e1432019-01-14 16:58:59 +0100679 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100680 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200681
682 disconnectTelephonyAudioSource(mCallRxSourceClient);
683 disconnectTelephonyAudioSource(mCallTxSourceClient);
684
685 if (rxDevices.isEmpty()) {
686 ALOGW("%s() no selected output device", __func__);
687 return INVALID_OPERATION;
688 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000689 if (txSourceDevice == nullptr) {
690 ALOGE("%s() selected input device not available", __func__);
691 return INVALID_OPERATION;
692 }
François Gaffiec005e562018-11-06 15:04:49 +0100693
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100694 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100695 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700696
François Gaffie9eb18552018-11-05 10:33:26 +0100697 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700698 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100699 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700700 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100701 // retrieve Rx Source and Tx Sink device descriptors
702 sp<DeviceDescriptor> rxSourceDevice =
703 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
704 String8(),
705 AUDIO_FORMAT_DEFAULT);
706 sp<DeviceDescriptor> txSinkDevice =
707 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
708 String8(),
709 AUDIO_FORMAT_DEFAULT);
710
711 // RX and TX Telephony device are declared by Primary Audio HAL
712 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
713 (telephonyRxModule->getHalVersionMajor() >= 3)) {
714 if (rxSourceDevice == 0 || txSinkDevice == 0) {
715 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100716 ALOGE("%s() no telephony Tx and/or RX device", __func__);
717 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100718 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100719 // createAudioPatchInternal now supports both HW / SW bridging
720 createRxPatch = true;
721 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100722 } else {
723 // If the RX device is on the primary HW module, then use legacy routing method for
724 // voice calls via setOutputDevice() on primary output.
725 // Otherwise, create two audio patches for TX and RX path.
726 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
727 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728 // If the TX device is also on the primary HW module, setOutputDevice() will take care
729 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100730 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
731 (txSinkDevice != 0);
732 }
733 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
734 // Otherwise, create two audio patches for TX and RX path.
735 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200736 if (!hasPrimaryOutput()) {
737 ALOGW("%s() no primary output available", __func__);
738 return INVALID_OPERATION;
739 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530740 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700741 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200742 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800743 // If the TX device is on the primary HW module but RX device is
744 // on other HW module, SinkMetaData of telephony input should handle it
745 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700746 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700747 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100748 // terminate active capture if on the same HW module as the call TX source device
749 // FIXME: would be better to refine to only inputs whose profile connects to the
750 // call TX device but this information is not in the audio patch and logic here must be
751 // symmetric to the one in startInput()
752 for (const auto& activeDesc : mInputs.getActiveInputs()) {
753 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
754 closeActiveClients(activeDesc);
755 }
756 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200757 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800758 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100759 if (waitMs != nullptr) {
760 *waitMs = muteWaitMs;
761 }
762 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800763}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700764
Mikhail Naganov100f0122018-11-29 11:22:16 -0800765bool AudioPolicyManager::isDeviceOfModule(
766 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
767 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
768 if (module != 0) {
769 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
770 .indexOf(devDesc) != NAME_NOT_FOUND
771 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
772 .indexOf(devDesc) != NAME_NOT_FOUND;
773 }
774 return false;
775}
776
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200777void AudioPolicyManager::connectTelephonyRxAudioSource()
778{
Francois Gaffie601801d2021-06-22 13:27:39 +0200779 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200780 const struct audio_port_config source = {
781 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
782 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
783 };
784 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200785 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
786 ALOGE_IF(mCallRxSourceClient == nullptr,
787 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200788}
789
Francois Gaffie601801d2021-06-22 13:27:39 +0200790void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200791{
Francois Gaffie601801d2021-06-22 13:27:39 +0200792 if (clientDesc == nullptr) {
793 return;
794 }
795 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
796 "%s error stopping audio source", __func__);
797 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200798}
799
800void AudioPolicyManager::connectTelephonyTxAudioSource(
801 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
802 uint32_t delayMs)
803{
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200805 if (srcDevice == nullptr || sinkDevice == nullptr) {
806 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
807 return;
808 }
809 PatchBuilder patchBuilder;
810 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
811 ALOGV("%s between source %s and sink %s", __func__,
812 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200813 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200814 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
815
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200816 struct audio_port_config source = {};
817 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200818 mCallTxSourceClient = new InternalSourceClientDescriptor(
819 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200820 mCommunnicationStrategy, toVolumeSource(aa));
821 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
822 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200823 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
824 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200825 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
826 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200827 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200828 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200829}
830
Eric Laurente0720872014-03-11 09:30:41 -0700831void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700832{
833 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100834 // store previous phone state for management of sonification strategy below
835 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100836 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100837
838 if (mEngine->setPhoneState(state) != NO_ERROR) {
839 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 return;
841 }
François Gaffie2110e042015-03-24 08:41:51 +0100842 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700843 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700844 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700845 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800846 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700847 }
848
François Gaffie2110e042015-03-24 08:41:51 +0100849 /**
850 * Switching to or from incall state or switching between telephony and VoIP lead to force
851 * routing command.
852 */
Eric Laurent74b71512019-11-06 17:21:57 -0800853 bool force = ((isStateInCall(oldState) != isStateInCall(state))
854 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700855
856 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700857 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700858
Eric Laurente552edb2014-03-10 17:42:56 -0700859 int delayMs = 0;
860 if (isStateInCall(state)) {
861 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100862 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
863 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700864 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700865 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700866 // mute media and sonification strategies and delay device switch by the largest
867 // latency of any output where either strategy is active.
868 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100869 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
870 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
871 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700872 (delayMs < (int)desc->latency()*2)) {
873 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700874 }
François Gaffiec005e562018-11-06 15:04:49 +0100875 setStrategyMute(musicStrategy, true, desc);
876 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
877 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
878 nullptr, true /*fromCache*/).types());
879 setStrategyMute(sonificationStrategy, true, desc);
880 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
881 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
882 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700883 }
884 }
885
François Gaffiedb1755b2023-09-01 11:50:35 +0200886 if (state == AUDIO_MODE_IN_CALL) {
887 (void)updateCallRouting(false /*fromCache*/, delayMs);
888 } else {
889 if (oldState == AUDIO_MODE_IN_CALL) {
890 disconnectTelephonyAudioSource(mCallRxSourceClient);
891 disconnectTelephonyAudioSource(mCallTxSourceClient);
892 }
893 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100894 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
895 // force routing command to audio hardware when ending call
896 // even if no device change is needed
897 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
898 rxDevices = mPrimaryOutput->devices();
899 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530900 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700901 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700902 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700903
jiabin3ff8d7d2022-12-13 06:27:44 +0000904 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700905 // reevaluate routing on all outputs in case tracks have been started during the call
906 for (size_t i = 0; i < mOutputs.size(); i++) {
907 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100908 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200909 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
910 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000911 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
912 // If the device is using preferred mixer attributes, the output need to reopen
913 // with default configuration when the new selected devices are different from
914 // current routing devices.
915 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
916 continue;
917 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530918 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200919 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700920 }
921 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000922 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700923
Eric Laurent96d1dda2022-03-14 17:14:19 +0100924 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
925
Eric Laurente552edb2014-03-10 17:42:56 -0700926 if (isStateInCall(state)) {
927 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700928 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800929 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700930 }
931
932 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100933 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
934 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700935}
936
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700937audio_mode_t AudioPolicyManager::getPhoneState() {
938 return mEngine->getPhoneState();
939}
940
Eric Laurente0720872014-03-11 09:30:41 -0700941void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100942 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700943{
François Gaffie2110e042015-03-24 08:41:51 +0100944 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700945 if (config == mEngine->getForceUse(usage)) {
946 return;
947 }
Eric Laurente552edb2014-03-10 17:42:56 -0700948
François Gaffie2110e042015-03-24 08:41:51 +0100949 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
950 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
951 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700952 }
François Gaffie2110e042015-03-24 08:41:51 +0100953 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
954 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
955 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700956
957 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700958 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800959
Eric Laurent22fcda22019-05-17 16:28:47 -0700960 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
961 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800962 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700963 }
964
Eric Laurentdc462862016-07-19 12:29:53 -0700965 //FIXME: workaround for truncated touch sounds
966 // to be removed when the problem is handled by system UI
967 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700968 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
969 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
970 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700971
972 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100973 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700974}
975
Eric Laurente0720872014-03-11 09:30:41 -0700976void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700977{
978 ALOGV("setSystemProperty() property %s, value %s", property, value);
979}
980
Dorin Drimusecc9f422022-03-09 17:57:40 +0100981// Find an MSD output profile compatible with the parameters passed.
982// When "directOnly" is set, restrict search to profiles for direct outputs.
983sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
984 const DeviceVector& devices,
985 uint32_t samplingRate,
986 audio_format_t format,
987 audio_channel_mask_t channelMask,
988 audio_output_flags_t flags,
989 bool directOnly)
990{
991 flags = getRelevantFlags(flags, directOnly);
992
993 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
994 if (msdModule != nullptr) {
995 // for the msd module check if there are patches to the output devices
996 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
997 HwModuleCollection modules;
998 modules.add(msdModule);
999 return searchCompatibleProfileHwModules(
1000 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1001 flags, directOnly);
1002 }
1003 }
1004 return nullptr;
1005}
1006
Michael Chana94fbb22018-04-24 14:31:19 +10001007// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1008// search to profiles for direct outputs.
1009sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001010 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001011 uint32_t samplingRate,
1012 audio_format_t format,
1013 audio_channel_mask_t channelMask,
1014 audio_output_flags_t flags,
1015 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001016{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001017 flags = getRelevantFlags(flags, directOnly);
1018
1019 return searchCompatibleProfileHwModules(
1020 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1021}
1022
1023audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1024 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001025 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001026 // only retain flags that will drive the direct output profile selection
1027 // if explicitly requested
1028 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001029 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001030 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1031 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001032 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001033 return flags;
1034}
Eric Laurent861a6282015-05-18 15:40:16 -07001035
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1037 const HwModuleCollection& hwModules,
1038 const DeviceVector& devices,
1039 uint32_t samplingRate,
1040 audio_format_t format,
1041 audio_channel_mask_t channelMask,
1042 audio_output_flags_t flags,
1043 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001044 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001045 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001046 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001047 if (!curProfile->isCompatibleProfile(devices,
1048 samplingRate, NULL /*updatedSamplingRate*/,
1049 format, NULL /*updatedFormat*/,
1050 channelMask, NULL /*updatedChannelMask*/,
1051 flags)) {
1052 continue;
1053 }
1054 // reject profiles not corresponding to a device currently available
1055 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1056 continue;
1057 }
1058 // reject profiles if connected device does not support codec
1059 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1060 continue;
1061 }
1062 if (!directOnly) {
1063 return curProfile;
1064 }
1065
1066 // when searching for direct outputs, if several profiles are compatible, give priority
1067 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001068 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001069 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001070 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001071 }
1072 profile = curProfile;
1073 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1074 break;
1075 }
Eric Laurente552edb2014-03-10 17:42:56 -07001076 }
1077 }
Eric Laurent861a6282015-05-18 15:40:16 -07001078 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001079}
1080
Eric Laurentfa0f6742021-08-17 18:39:44 +02001081sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001082 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001083{
1084 for (const auto& hwModule : mHwModules) {
1085 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001086 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001087 continue;
1088 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001089 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001090 // reject profiles not corresponding to a device currently available
1091 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1092 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1093 continue;
1094 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001095 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1096 != devices.size()) {
1097 continue;
1098 }
1099 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001100 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1101 return curProfile;
1102 }
1103 }
1104 return nullptr;
1105}
1106
Eric Laurentf4e63452017-11-06 19:31:46 +00001107audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001108{
François Gaffiec005e562018-11-06 15:04:49 +01001109 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001110
1111 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1112 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1113 // format, flags, etc. This may result in some discrepancy for functions that utilize
1114 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1115 // and AudioSystem::getOutputSamplingRate().
1116
François Gaffie11d30102018-11-02 16:09:09 +01001117 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001118 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1119 if (stream == AUDIO_STREAM_MUSIC &&
1120 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1121 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1122 }
1123 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001124
François Gaffie11d30102018-11-02 16:09:09 +01001125 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1126 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001127 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001128}
1129
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001130status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1131 const audio_attributes_t *srcAttr,
1132 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001133{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001134 if (srcAttr != NULL) {
1135 if (!isValidAttributes(srcAttr)) {
1136 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1137 __func__,
1138 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1139 srcAttr->tags);
1140 return BAD_VALUE;
1141 }
1142 *dstAttr = *srcAttr;
1143 } else {
1144 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1145 ALOGE("%s: invalid stream type", __func__);
1146 return BAD_VALUE;
1147 }
François Gaffiec005e562018-11-06 15:04:49 +01001148 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001150
1151 // Only honor audibility enforced when required. The client will be
1152 // forced to reconnect if the forced usage changes.
1153 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001154 dstAttr->flags = static_cast<audio_flags_mask_t>(
1155 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001156 }
1157
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001158 return NO_ERROR;
1159}
1160
Kevin Rocard153f92d2018-12-18 18:33:28 -08001161status_t AudioPolicyManager::getOutputForAttrInt(
1162 audio_attributes_t *resultAttr,
1163 audio_io_handle_t *output,
1164 audio_session_t session,
1165 const audio_attributes_t *attr,
1166 audio_stream_type_t *stream,
1167 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001168 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001169 audio_output_flags_t *flags,
1170 audio_port_handle_t *selectedDeviceId,
1171 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001172 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001173 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001174 bool *isSpatialized,
1175 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001176{
François Gaffiec005e562018-11-06 15:04:49 +01001177 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001178 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001179 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001180 const sp<DeviceDescriptor> requestedDevice =
1181 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1182
Eric Laurent8a1095a2019-11-08 14:44:16 -08001183 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001184 *isSpatialized = false;
1185
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001186 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1187 if (status != NO_ERROR) {
1188 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001189 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001190 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001191 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001192 }
François Gaffiec005e562018-11-06 15:04:49 +01001193 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001194
François Gaffiec005e562018-11-06 15:04:49 +01001195 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1196 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001197
Oscar Azucena873d10f2023-01-12 18:34:42 -08001198 bool usePrimaryOutputFromPolicyMixes = false;
1199
Kevin Rocard153f92d2018-12-18 18:33:28 -08001200 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1201 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1202 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001203 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001204 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1205 .channel_mask = config->channel_mask,
1206 .format = config->format,
1207 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001208 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001209 mAvailableOutputDevices, requestedDevice, primaryMix,
1210 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001211 if (status != OK) {
1212 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001213 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001214
Kevin Rocard153f92d2018-12-18 18:33:28 -08001215 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001216 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1217 && !audio_is_linear_pcm(config->format)) {
1218 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 return BAD_VALUE;
1220 }
1221 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001222 sp<DeviceDescriptor> deviceDesc =
1223 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1224 primaryMix->mDeviceAddress,
1225 AUDIO_FORMAT_DEFAULT);
1226 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001227 bool tryDirectForFlags = policyDesc == nullptr ||
1228 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1229 // if a direct output can be opened to deliver the track's multi-channel content to the
1230 // output rather than being downmixed by the primary output, then use this direct
1231 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1232 // mix.
1233 bool tryDirectForChannelMask = policyDesc != nullptr
1234 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1235 audio_channel_count_from_out_mask(config->channel_mask));
1236 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001237 audio_io_handle_t newOutput;
1238 status = openDirectOutput(
1239 *stream, session, config,
1240 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1241 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001242 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001243 policyDesc = mOutputs.valueFor(newOutput);
1244 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001245 } else if (tryDirectForFlags) {
1246 policyDesc = nullptr;
1247 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001248 }
1249 if (policyDesc != nullptr) {
1250 policyDesc->mPolicyMix = primaryMix;
1251 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001252 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001253
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001254 ALOGV("getOutputForAttr() returns output %d", *output);
1255 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1256 *outputType = API_OUT_MIX_PLAYBACK;
1257 } else {
1258 *outputType = API_OUTPUT_LEGACY;
1259 }
1260 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001261 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001262 }
François Gaffiec005e562018-11-06 15:04:49 +01001263 // Virtual sources must always be dynamicaly or explicitly routed
1264 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1265 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1266 return BAD_VALUE;
1267 }
1268 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1269 // in order to let the choice of the order to future vendor engine
1270 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001271
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001272 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001273 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001274 }
1275
Nadav Barb2f18162018-07-18 13:01:53 +03001276 // Set incall music only if device was explicitly set, and fallback to the device which is
1277 // chosen by the engine if not.
1278 // FIXME: provide a more generic approach which is not device specific and move this back
1279 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001280 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001281 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001282 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001283 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001284 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001285 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001286 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001287 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001288 }
1289 }
1290
François Gaffiec005e562018-11-06 15:04:49 +01001291 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1292 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1293 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001294
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001295 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001296 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001297 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001298 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001299 ALOGV("%s() Using MSD devices %s instead of devices %s",
1300 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001301 } else {
1302 *output = AUDIO_IO_HANDLE_NONE;
1303 }
1304 }
1305 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001306 sp<PreferredMixerAttributesInfo> info = nullptr;
1307 if (outputDevices.size() == 1) {
1308 info = getPreferredMixerAttributesInfo(
1309 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001310 mEngine->getProductStrategyForAttributes(*resultAttr),
1311 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001312 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1313 // and it is currently active.
1314 if (info != nullptr && info->getUid() != uid &&
1315 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1316 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001317 info = nullptr;
1318 }
1319 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001320 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001321 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001322 // The client will be active if the client is currently preferred mixer owner and the
1323 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001324 *isBitPerfect = (info != nullptr
1325 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001326 && info->getUid() == uid
1327 && *output != AUDIO_IO_HANDLE_NONE
1328 // When bit-perfect output is selected for the preferred mixer attributes owner,
1329 // only need to consider the config matches.
1330 && mOutputs.valueFor(*output)->isConfigurationMatched(
1331 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001332 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001333 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001334 AudioProfileVector profiles;
1335 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1336 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001337 const auto channels = profiles[0]->getChannels();
1338 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1339 config->channel_mask = *channels.begin();
1340 }
1341 const auto sampleRates = profiles[0]->getSampleRates();
1342 if (!sampleRates.empty() &&
1343 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1344 config->sample_rate = *sampleRates.begin();
1345 }
jiabinf1c73972022-04-14 16:28:52 -07001346 config->format = profiles[0]->getFormat();
1347 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001348 return INVALID_OPERATION;
1349 }
Paul McLeanaa981192015-03-21 09:55:15 -07001350
François Gaffiec005e562018-11-06 15:04:49 +01001351 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001352 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001353 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001354 *selectedDeviceId = outputDevice->getId();
1355 break;
1356 }
1357 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001358
Eric Laurent8a1095a2019-11-08 14:44:16 -08001359 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1360 *outputType = API_OUTPUT_TELEPHONY_TX;
1361 } else {
1362 *outputType = API_OUTPUT_LEGACY;
1363 }
1364
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001365 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1366
1367 return NO_ERROR;
1368}
1369
1370status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1371 audio_io_handle_t *output,
1372 audio_session_t session,
1373 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001374 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001375 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001376 audio_output_flags_t *flags,
1377 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001378 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001379 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001380 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001381 bool *isSpatialized,
1382 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001383{
1384 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1385 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1386 return INVALID_OPERATION;
1387 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001388 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001389 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001390 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001391 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001392 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001393 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001394 const sp<DeviceDescriptor> requestedDevice =
1395 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1396
1397 // Prevent from storing invalid requested device id in clients
1398 const audio_port_handle_t sanitizedRequestedPortId =
1399 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1400 *selectedDeviceId = sanitizedRequestedPortId;
1401
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001402 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001403 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001404 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1405 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001406 if (status != NO_ERROR) {
1407 return status;
1408 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001409 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001410 if (secondaryOutputs != nullptr) {
1411 for (auto &secondaryMix : secondaryMixes) {
1412 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1413 if (outputDesc != nullptr &&
1414 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1415 secondaryOutputs->push_back(outputDesc->mIoHandle);
1416 weakSecondaryOutputDescs.push_back(outputDesc);
1417 }
1418 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001419 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001420
Eric Laurent8fc147b2018-07-22 19:13:55 -07001421 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001422 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001423 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001424 };
jiabin4ef93452019-09-10 14:29:54 -07001425 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001426
Eric Laurentc209fe42020-06-05 18:11:23 -07001427 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001428 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001429 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001430 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001431 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001432 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001433 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001434 std::move(weakSecondaryOutputDescs),
1435 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001436 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001437
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001438 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1439 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001440
Eric Laurente83b55d2014-11-14 10:06:21 -08001441 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001442}
1443
Eric Laurentc529cf62020-04-17 18:19:10 -07001444status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1445 audio_session_t session,
1446 const audio_config_t *config,
1447 audio_output_flags_t flags,
1448 const DeviceVector &devices,
1449 audio_io_handle_t *output) {
1450
1451 *output = AUDIO_IO_HANDLE_NONE;
1452
1453 // skip direct output selection if the request can obviously be attached to a mixed output
1454 // and not explicitly requested
1455 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1456 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1457 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1458 return NAME_NOT_FOUND;
1459 }
1460
1461 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1462 // This prevents creating an offloaded track and tearing it down immediately after start
1463 // when audioflinger detects there is an active non offloadable effect.
1464 // FIXME: We should check the audio session here but we do not have it in this context.
1465 // This may prevent offloading in rare situations where effects are left active by apps
1466 // in the background.
1467 sp<IOProfile> profile;
1468 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1469 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1470 profile = getProfileForOutput(
1471 devices, config->sample_rate, config->format, config->channel_mask,
1472 flags, true /* directOnly */);
1473 }
1474
1475 if (profile == nullptr) {
1476 return NAME_NOT_FOUND;
1477 }
1478
1479 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1480 for (size_t i = 0; i < mOutputs.size(); i++) {
1481 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1482 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1483 // reuse direct output if currently open by the same client
1484 // and configured with same parameters
1485 if ((config->sample_rate == desc->getSamplingRate()) &&
1486 (config->format == desc->getFormat()) &&
1487 (config->channel_mask == desc->getChannelMask()) &&
1488 (session == desc->mDirectClientSession)) {
1489 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001490 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001491 mOutputs.keyAt(i), session);
1492 *output = mOutputs.keyAt(i);
1493 return NO_ERROR;
1494 }
1495 }
1496 }
1497
1498 if (!profile->canOpenNewIo()) {
1499 return NAME_NOT_FOUND;
1500 }
1501
1502 sp<SwAudioOutputDescriptor> outputDesc =
1503 new SwAudioOutputDescriptor(profile, mpClientInterface);
1504
Michael Chan6fb34492020-12-08 15:44:49 +11001505 // An MSD patch may be using the only output stream that can service this request. Release
1506 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001507 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001508
Eric Laurentf1f22e72021-07-13 14:04:14 +02001509 status_t status =
1510 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001511
1512 // only accept an output with the requested parameters
1513 if (status != NO_ERROR ||
1514 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1515 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1516 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1517 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1518 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1519 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1520 config->channel_mask, outputDesc->getChannelMask());
1521 if (*output != AUDIO_IO_HANDLE_NONE) {
1522 outputDesc->close();
1523 }
1524 // fall back to mixer output if possible when the direct output could not be open
1525 if (audio_is_linear_pcm(config->format) &&
1526 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1527 return NAME_NOT_FOUND;
1528 }
1529 *output = AUDIO_IO_HANDLE_NONE;
1530 return BAD_VALUE;
1531 }
1532 outputDesc->mDirectOpenCount = 1;
1533 outputDesc->mDirectClientSession = session;
1534
1535 addOutput(*output, outputDesc);
1536 mPreviousOutputs = mOutputs;
1537 ALOGV("%s returns new direct output %d", __func__, *output);
1538 mpClientInterface->onAudioPortListUpdate();
1539 return NO_ERROR;
1540}
1541
François Gaffie11d30102018-11-02 16:09:09 +01001542audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1543 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001544 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001545 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001546 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001547 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001548 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001549 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001550 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001551{
Andy Hungc88b0642018-04-27 15:42:35 -07001552 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001553
jiabine375d412019-02-26 12:54:53 -08001554 // Discard haptic channel mask when forcing muting haptic channels.
1555 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001556 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1557 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001558
Eric Laurente552edb2014-03-10 17:42:56 -07001559 // open a direct output if required by specified parameters
1560 //force direct flag if offload flag is set: offloading implies a direct output stream
1561 // and all common behaviors are driven by checking only the direct flag
1562 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001563 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1564 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001565 }
Nadav Bar766fb022018-01-07 12:18:03 +02001566 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1567 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001568 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001569
1570 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1571
Eric Laurente83b55d2014-11-14 10:06:21 -08001572 // only allow deep buffering for music stream type
1573 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001574 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001575 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001576 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001577 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1578 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001579 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001580 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001581 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001582 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001583 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001584 audio_is_linear_pcm(config->format) &&
1585 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001586 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001587 AUDIO_OUTPUT_FLAG_DIRECT);
1588 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001589 }
Eric Laurente552edb2014-03-10 17:42:56 -07001590
Carter Hsua3abb402021-10-26 11:11:20 +08001591 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1592 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1593 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1594 }
1595
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001596 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001597 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001598 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001599 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001600 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001601 }
1602
Eric Laurentc529cf62020-04-17 18:19:10 -07001603 audio_config_t directConfig = *config;
1604 directConfig.channel_mask = channelMask;
1605 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1606 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001607 return output;
1608 }
1609
Eric Laurent14cbfca2016-03-17 09:42:16 -07001610 // A request for HW A/V sync cannot fallback to a mixed output because time
1611 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001612 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001613 return AUDIO_IO_HANDLE_NONE;
1614 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001615 // A request for Tuner cannot fallback to a mixed output
1616 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1617 return AUDIO_IO_HANDLE_NONE;
1618 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001619
Eric Laurente552edb2014-03-10 17:42:56 -07001620 // ignoring channel mask due to downmix capability in mixer
1621
1622 // open a non direct output
1623
1624 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001625 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001626 // get which output is suitable for the specified stream. The actual
1627 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001628 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001629 if (prefMixerConfigInfo != nullptr) {
1630 for (audio_io_handle_t outputHandle : outputs) {
1631 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1632 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1633 output = outputHandle;
1634 break;
1635 }
1636 }
1637 if (output == AUDIO_IO_HANDLE_NONE) {
1638 // No output open with the preferred profile. Open a new one.
1639 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1640 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1641 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1642 config.format = prefMixerConfigInfo->getConfigBase().format;
1643 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1644 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1645 &config, prefMixerConfigInfo->getFlags());
1646 if (preferredOutput == nullptr) {
1647 ALOGE("%s failed to open output with preferred mixer config", __func__);
1648 } else {
1649 output = preferredOutput->mIoHandle;
1650 }
1651 }
1652 } else {
1653 // at this stage we should ignore the DIRECT flag as no direct output could be
1654 // found earlier
1655 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1656 output = selectOutput(
1657 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1658 }
Eric Laurente552edb2014-03-10 17:42:56 -07001659 }
François Gaffie11d30102018-11-02 16:09:09 +01001660 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001661 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001662 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001663
Eric Laurente552edb2014-03-10 17:42:56 -07001664 return output;
1665}
1666
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001667sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001668 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1669 mAvailableInputDevices);
1670 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1671}
1672
1673DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1674 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1675 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001676}
1677
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001678const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001679 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001680 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1681 if (msdModule != 0) {
1682 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1683 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1684 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1685 const struct audio_port_config *source = &patch->mPatch.sources[j];
1686 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1687 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001688 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001689 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001690 }
1691 }
1692 }
1693 return msdPatches;
1694}
1695
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001696bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1697 ssize_t index = mAudioPatches.indexOfKey(handle);
1698 if (index < 0) {
1699 return false;
1700 }
1701 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1702 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1703 if (msdModule == nullptr) {
1704 return false;
1705 }
1706 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1707 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1708 return true;
1709 }
1710 index = getMsdOutputPatches().indexOfKey(handle);
1711 if (index < 0) {
1712 return false;
1713 }
1714 return true;
1715}
1716
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001717status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1718 const InputProfileCollection &inputProfiles,
1719 const OutputProfileCollection &outputProfiles,
1720 const sp<DeviceDescriptor> &sourceDevice,
1721 const sp<DeviceDescriptor> &sinkDevice,
1722 AudioProfileVector& sourceProfiles,
1723 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001725 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001726 return NO_INIT;
1727 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001728 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001729 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001730 return NO_INIT;
1731 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001732 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001733 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1734 inProfile->supportsDevice(sourceDevice)) {
1735 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001736 }
1737 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001738 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001739 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001740 outProfile->supportsDevice(sinkDevice)) {
1741 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001742 }
1743 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001744 return NO_ERROR;
1745}
1746
1747status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1748 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1749 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1750{
Dean Wheatley16809da2022-12-09 14:55:46 +11001751 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1752 static const std::vector<audio_format_t> formatsOrder = {{
1753 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001754 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1755 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001756 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1757 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1758 // preferred).
1759 std::vector<audio_channel_mask_t> masks = {{
1760 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1761 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1762 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1763 // insert index masks (higher counts most preferred) as preferred over position masks
1764 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1765 masks.insert(
1766 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1767 }
1768 return masks;
1769 }();
1770
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001772 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1773 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001774 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001775 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1776 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001777 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001778 }
1779 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1780 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1781 sinkConfig->format = bestSinkConfig.format;
1782 // For encoded streams force direct flag to prevent downstream mixing.
1783 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1784 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001785 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1786 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001787 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001788 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1789 // raw and IEC61937 framed streams.
1790 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1791 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1792 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001793 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1794 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001795 sourceConfig->channel_mask =
1796 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1797 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1798 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001799 sourceConfig->format = bestSinkConfig.format;
1800 // Copy input stream directly without any processing (e.g. resampling).
1801 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1802 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1803 if (hwAvSync) {
1804 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1805 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1806 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1807 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1808 }
1809 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1810 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1811 sinkConfig->config_mask |= config_mask;
1812 sourceConfig->config_mask |= config_mask;
1813 return NO_ERROR;
1814}
1815
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001816PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1817 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001818{
1819 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001820 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1821 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1822 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1823 if (deviceModule == nullptr) {
1824 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1825 return patchBuilder;
1826 }
1827 const InputProfileCollection inputProfiles = msdIsSource ?
1828 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1829 const OutputProfileCollection outputProfiles = msdIsSource ?
1830 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1831
1832 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1833 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1834 device : getMsdAudioOutDevices().itemAt(0);
1835 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1836
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001837 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1838 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001839 AudioProfileVector sourceProfiles;
1840 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001841 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1842 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001843 for (auto hwAvSync : { true, false }) {
1844 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1845 sourceProfiles, sinkProfiles) != NO_ERROR) {
1846 continue;
1847 }
1848 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1849 &sinkConfig) == NO_ERROR) {
1850 // Found a matching config. Re-create PatchBuilder with this config.
1851 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1852 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001853 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001854 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001855 " supporting PCM format conversion.", __func__);
1856 return patchBuilder;
1857}
1858
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001859status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001860 DeviceVector devices;
1861 if (outputDevices != nullptr && outputDevices->size() > 0) {
1862 devices.add(*outputDevices);
1863 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001864 // Use media strategy for unspecified output device. This should only
1865 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1866 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001867 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001868 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001869 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001870 }
Michael Chan6fb34492020-12-08 15:44:49 +11001871 std::vector<PatchBuilder> patchesToCreate;
1872 for (auto i = 0u; i < devices.size(); ++i) {
1873 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001874 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001875 }
1876 // Retain only the MSD patches associated with outputDevices request.
1877 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001878 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001879 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1880 auto retainedPatch = false;
1881 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1882 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1883 patchesToRemove.removeItemsAt(i);
1884 retainedPatch = true;
1885 break;
1886 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001887 }
Michael Chan6fb34492020-12-08 15:44:49 +11001888 if (retainedPatch) {
1889 it = patchesToCreate.erase(it);
1890 continue;
1891 }
1892 ++it;
1893 }
1894 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1895 return NO_ERROR;
1896 }
1897 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1898 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001899 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001900 }
Michael Chan6fb34492020-12-08 15:44:49 +11001901 status_t status = NO_ERROR;
1902 for (const auto &p : patchesToCreate) {
1903 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1904 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1905 char message[256];
1906 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1907 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1908 currStatus == NO_ERROR ? "Success" : "Error",
1909 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1910 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1911 if (currStatus == NO_ERROR) {
1912 ALOGD("%s", message);
1913 } else {
1914 ALOGE("%s", message);
1915 if (status == NO_ERROR) {
1916 status = currStatus;
1917 }
1918 }
1919 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001920 return status;
1921}
1922
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001923void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1924 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001925 for (size_t i = 0; i < msdPatches.size(); i++) {
1926 const auto& patch = msdPatches[i];
1927 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1928 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1929 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1930 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1931 releaseAudioPatch(patch->getHandle(), mUidCached);
1932 break;
1933 }
1934 }
1935 }
1936}
1937
Dorin Drimus94d94412022-02-02 09:05:02 +01001938bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001939 DeviceVector devicesToCheck =
1940 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001941 AudioPatchCollection msdPatches = getMsdOutputPatches();
1942 for (size_t i = 0; i < msdPatches.size(); i++) {
1943 const auto& patch = msdPatches[i];
1944 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1945 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1946 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1947 const auto& foundDevice = devicesToCheck.getDevice(
1948 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1949 if (foundDevice != nullptr) {
1950 devicesToCheck.remove(foundDevice);
1951 if (devicesToCheck.isEmpty()) {
1952 return true;
1953 }
1954 }
1955 }
1956 }
1957 }
1958 return false;
1959}
1960
Eric Laurente0720872014-03-11 09:30:41 -07001961audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001962 audio_output_flags_t flags,
1963 audio_format_t format,
1964 audio_channel_mask_t channelMask,
1965 uint32_t samplingRate,
1966 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001967{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001968 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1969 "%s called with format %#x", __func__, format);
1970
jiabinebb6af42020-06-09 17:31:17 -07001971 // Return the output that haptic-generating attached to when 1) session id is specified,
1972 // 2) haptic-generating effect exists for given session id and 3) the output that
1973 // haptic-generating effect attached to is in given outputs.
1974 if (sessionId != AUDIO_SESSION_NONE) {
1975 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1976 sessionId, FX_IID_HAPTICGENERATOR);
1977 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1978 return hapticGeneratingOutput;
1979 }
1980 }
1981
Eric Laurent16c66dd2019-05-01 17:54:10 -07001982 // Flags disqualifying an output: the match must happen before calling selectOutput()
1983 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1984 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1985
1986 // Flags expressing a functional request: must be honored in priority over
1987 // other criteria
1988 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1989 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001990 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1991 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001992 // Flags expressing a performance request: have lower priority than serving
1993 // requested sampling rate or channel mask
1994 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1995 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1996 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1997
1998 const audio_output_flags_t functionalFlags =
1999 (audio_output_flags_t)(flags & kFunctionalFlags);
2000 const audio_output_flags_t performanceFlags =
2001 (audio_output_flags_t)(flags & kPerformanceFlags);
2002
2003 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2004
Eric Laurente552edb2014-03-10 17:42:56 -07002005 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002006 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002007 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002008 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002009 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002010 // with tiebreak preferring the minimum number of extra functional flags
2011 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002012 // 3: the output supporting the exact channel mask
2013 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002014 // 5: the output with the highest sampling rate if the requested sample rate is
2015 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002016 // 6: the output with the highest number of requested performance flags
2017 // 7: the output with the bit depth the closest to the requested one
2018 // 8: the primary output
2019 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002020
Eric Laurent16c66dd2019-05-01 17:54:10 -07002021 // matching criteria values in priority order for best matching output so far
2022 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002023
Eric Laurent16c66dd2019-05-01 17:54:10 -07002024 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2025 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2026 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002027
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002028 for (audio_io_handle_t output : outputs) {
2029 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002030 // matching criteria values in priority order for current output
2031 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002032
Eric Laurent16c66dd2019-05-01 17:54:10 -07002033 if (outputDesc->isDuplicated()) {
2034 continue;
2035 }
2036 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2037 continue;
2038 }
Eric Laurent8838a382014-09-08 16:44:28 -07002039
Eric Laurent16c66dd2019-05-01 17:54:10 -07002040 // If haptic channel is specified, use the haptic output if present.
2041 // When using haptic output, same audio format and sample rate are required.
2042 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002043 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002044 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2045 continue;
2046 }
2047 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002048 && format == outputDesc->getFormat()
2049 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002050 currentMatchCriteria[0] = outputHapticChannelCount;
2051 }
2052
2053 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002054 const int matchingFunctionalFlags =
2055 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2056 const int totalFunctionalFlags =
2057 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2058 // Prefer matching functional flags, but subtract unnecessary functional flags.
2059 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002060
2061 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002062 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2063 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002064 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2065 channelCount <= outputChannelCount) {
2066 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002067 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2068 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002069 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002070 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002071 currentMatchCriteria[3] = outputChannelCount;
2072 }
2073
2074 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002075 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002076 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002077 }
2078
2079 // performance flags match
2080 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2081
2082 // format match
2083 if (format != AUDIO_FORMAT_INVALID) {
2084 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002085 PolicyAudioPort::kFormatDistanceMax -
2086 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002087 }
2088
2089 // primary output match
2090 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2091
2092 // compare match criteria by priority then value
2093 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2094 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2095 bestMatchCriteria = currentMatchCriteria;
2096 bestOutput = output;
2097
2098 std::stringstream result;
2099 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2100 std::ostream_iterator<int>(result, " "));
2101 ALOGV("%s new bestOutput %d criteria %s",
2102 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002103 }
2104 }
2105
Eric Laurent16c66dd2019-05-01 17:54:10 -07002106 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002107}
2108
Eric Laurent8fc147b2018-07-22 19:13:55 -07002109status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002110{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002111 ALOGV("%s portId %d", __FUNCTION__, portId);
2112
2113 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2114 if (outputDesc == 0) {
2115 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002116 return BAD_VALUE;
2117 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002118 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002119
Eric Laurent8fc147b2018-07-22 19:13:55 -07002120 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002121 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002122
Eric Laurent733ce942017-12-07 12:18:25 -08002123 status_t status = outputDesc->start();
2124 if (status != NO_ERROR) {
2125 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002126 }
2127
Eric Laurent97ac8712018-07-27 18:59:02 -07002128 uint32_t delayMs;
2129 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002130
2131 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002132 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002133 if (status == DEAD_OBJECT) {
2134 sp<SwAudioOutputDescriptor> desc =
2135 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2136 if (desc == nullptr) {
2137 // This is not common, it may indicate something wrong with the HAL.
2138 ALOGE("%s unable to open output with default config", __func__);
2139 return status;
2140 }
2141 desc->mUsePreferredMixerAttributes = true;
2142 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002143 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002144 }
jiabina84c3d32022-12-02 18:59:55 +00002145
2146 // If the client is the first one active on preferred mixer parameters, reopen the output
2147 // if the current mixer parameters doesn't match the preferred one.
2148 if (outputDesc->devices().size() == 1) {
2149 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2150 outputDesc->devices()[0]->getId(), client->strategy());
2151 if (info != nullptr && info->getUid() == client->uid()) {
2152 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2153 info->getConfigBase(), info->getFlags())) {
2154 stopSource(outputDesc, client);
2155 outputDesc->stop();
2156 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2157 config.channel_mask = info->getConfigBase().channel_mask;
2158 config.sample_rate = info->getConfigBase().sample_rate;
2159 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002160 sp<SwAudioOutputDescriptor> desc =
2161 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2162 if (desc == nullptr) {
2163 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002164 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002165 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002166 // Intentionally return error to let the client side resending request for
2167 // creating and starting.
2168 return DEAD_OBJECT;
2169 }
2170 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002171 if (info->getActiveClientCount() == 1 &&
2172 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2173 // If it is first bit-perfect client, reroute all clients that will be routed to
2174 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2175 PortHandleVector clientsToInvalidate;
2176 for (size_t i = 0; i < mOutputs.size(); i++) {
2177 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002178 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002179 continue;
2180 }
2181 for (const auto& c : mOutputs[i]->getClientIterable()) {
2182 clientsToInvalidate.push_back(c->portId());
2183 }
2184 }
2185 if (!clientsToInvalidate.empty()) {
2186 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2187 __func__);
2188 mpClientInterface->invalidateTracks(clientsToInvalidate);
2189 }
2190 }
jiabina84c3d32022-12-02 18:59:55 +00002191 }
2192 }
2193
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002194 if (client->hasPreferredDevice()) {
2195 // playback activity with preferred device impacts routing occurred, inform upper layers
2196 mpClientInterface->onRoutingUpdated();
2197 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002198 if (delayMs != 0) {
2199 usleep(delayMs * 1000);
2200 }
2201
2202 return status;
2203}
2204
Eric Laurent96d1dda2022-03-14 17:14:19 +01002205bool AudioPolicyManager::isLeUnicastActive() const {
2206 if (isInCall()) {
2207 return true;
2208 }
2209 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2210}
2211
2212bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2213 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2214 return false;
2215 }
2216 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2217 ALOGV("%s active %d", __func__, active);
2218 return active;
2219}
2220
Eric Laurent97ac8712018-07-27 18:59:02 -07002221status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2222 const sp<TrackClientDescriptor>& client,
2223 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002224{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002225 // cannot start playback of STREAM_TTS if any other output is being used
2226 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002227
2228 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002229 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002230 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002231 auto clientStrategy = client->strategy();
2232 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002233 if (stream == AUDIO_STREAM_TTS) {
2234 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002235 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002236 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002237 return INVALID_OPERATION;
2238 } else {
2239 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2240 }
2241 } else {
2242 // some playback other than beacon starts
2243 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2244 }
2245
Eric Laurent77305a62016-07-25 16:39:22 -07002246 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002247 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002248 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002249
François Gaffie11d30102018-11-02 16:09:09 +01002250 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002251 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002252 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002253 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002254 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002255 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002256 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002257 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002258 } else {
2259 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002260 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002261 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2262 AUDIO_FORMAT_DEFAULT);
2263 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2264 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002265 }
2266
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002267 // requiresMuteCheck is false when we can bypass mute strategy.
2268 // It covers a common case when there is no materially active audio
2269 // and muting would result in unnecessary delay and dropped audio.
2270 const uint32_t outputLatencyMs = outputDesc->latency();
2271 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002272 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002273
Eric Laurente552edb2014-03-10 17:42:56 -07002274 // increment usage count for this stream on the requested output:
2275 // NOTE that the usage count is the same for duplicated output and hardware output which is
2276 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002277 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002278
2279 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002280 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002281 // Preferred device may be exclusive, use only if no other active clients on this output
2282 devices = DeviceVector(
2283 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2284 } else {
2285 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2286 }
François Gaffie11d30102018-11-02 16:09:09 +01002287 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002288 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002289 }
2290 }
Eric Laurente552edb2014-03-10 17:42:56 -07002291
François Gaffiec005e562018-11-06 15:04:49 +01002292 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002293 selectOutputForMusicEffects();
2294 }
2295
François Gaffie1c878552018-11-22 16:53:21 +01002296 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002297 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002298 if (devices.isEmpty()) {
2299 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002300 }
François Gaffiec005e562018-11-06 15:04:49 +01002301 bool shouldWait =
2302 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2303 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2304 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002305 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002306 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002307 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002308 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002309 // An output has a shared device if
2310 // - managed by the same hw module
2311 // - supports the currently selected device
2312 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002313 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002314
Eric Laurent77305a62016-07-25 16:39:22 -07002315 // force a device change if any other output is:
2316 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002317 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002318 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002319 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002320 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002321 // change the device currently selected by the other output.
2322 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002323 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002324 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002325 force = true;
2326 }
2327 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002328 // a notification so that audio focus effect can propagate, or that a mute/unmute
2329 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002330 const uint32_t latencyMs = desc->latency();
2331 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2332
2333 if (shouldWait && isActive && (waitMs < latencyMs)) {
2334 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002335 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002336
2337 // Require mute check if another output is on a shared device
2338 // and currently active to have proper drain and avoid pops.
2339 // Note restoring AudioTracks onto this output needs to invoke
2340 // a volume ramp if there is no mute.
2341 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002342 }
2343 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002344
jiabin3ff8d7d2022-12-13 06:27:44 +00002345 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2346 // If the output is open with preferred mixer attributes, but the routed device is
2347 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2348 // changed.
2349 return DEAD_OBJECT;
2350 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002351 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302352 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2353 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002354
Eric Laurente552edb2014-03-10 17:42:56 -07002355 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002356 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002357 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002358 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002359 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002360 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002361 outputDesc->useHwGain() /*force*/)) {
2362 // request AudioService to reinitialize the volume curves asynchronously
2363 ALOGE("checkAndSetVolume failed, requesting volume range init");
2364 mpClientInterface->onVolumeRangeInitRequest();
2365 };
Eric Laurente552edb2014-03-10 17:42:56 -07002366
2367 // update the outputs if starting an output with a stream that can affect notification
2368 // routing
2369 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002370
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002371 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002372 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002373 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002374 }
Eric Laurentdc462862016-07-19 12:29:53 -07002375
2376 if (waitMs > muteWaitMs) {
2377 *delayMs = waitMs - muteWaitMs;
2378 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002379
2380 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2381 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2382 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2383 // change occurs after the MixerThread starts and causes a stream volume
2384 // glitch.
2385 //
2386 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002387 }
Eric Laurentdc462862016-07-19 12:29:53 -07002388
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002389 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002390 mEngine->getForceUse(
2391 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002392 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002393 }
2394
Eric Laurent97ac8712018-07-27 18:59:02 -07002395 // Automatically enable the remote submix input when output is started on a re routing mix
2396 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002397 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2398 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002399 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2400 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2401 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002402 "remote-submix",
2403 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002404 }
2405
Eric Laurent96d1dda2022-03-14 17:14:19 +01002406 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2407
Eric Laurente552edb2014-03-10 17:42:56 -07002408 return NO_ERROR;
2409}
2410
Eric Laurent96d1dda2022-03-14 17:14:19 +01002411void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2412 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2413 bool isUnicastActive = isLeUnicastActive();
2414
2415 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002416 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002417 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2418 for (size_t i = 0; i < mOutputs.size(); i++) {
2419 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2420 if (desc != ignoredOutput && desc->isActive()
2421 && ((isUnicastActive &&
2422 !desc->devices().
2423 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2424 || (wasUnicastActive &&
2425 !desc->devices().getDevicesFromTypes(
2426 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2427 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2428 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002429 if (desc->mUsePreferredMixerAttributes && force) {
2430 // If the device is using preferred mixer attributes, the output need to reopen
2431 // with default configuration when the new selected devices are different from
2432 // current routing devices.
2433 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2434 continue;
2435 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302436 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002437 // re-apply device specific volume if not done by setOutputDevice()
2438 if (!force) {
2439 applyStreamVolumes(desc, newDevices.types(), delayMs);
2440 }
2441 }
2442 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002443 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002444 }
2445}
2446
Eric Laurent8fc147b2018-07-22 19:13:55 -07002447status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002448{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002449 ALOGV("%s portId %d", __FUNCTION__, portId);
2450
2451 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2452 if (outputDesc == 0) {
2453 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002454 return BAD_VALUE;
2455 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002456 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002457
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002458 if (client->hasPreferredDevice(true)) {
2459 // playback activity with preferred device impacts routing occurred, inform upper layers
2460 mpClientInterface->onRoutingUpdated();
2461 }
2462
Eric Laurent97ac8712018-07-27 18:59:02 -07002463 ALOGV("stopOutput() output %d, stream %d, session %d",
2464 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002465
Eric Laurent97ac8712018-07-27 18:59:02 -07002466 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002467
Eric Laurent733ce942017-12-07 12:18:25 -08002468 if (status == NO_ERROR ) {
2469 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002470 } else {
2471 return status;
2472 }
2473
2474 if (outputDesc->devices().size() == 1) {
2475 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2476 outputDesc->devices()[0]->getId(), client->strategy());
2477 if (info != nullptr && info->getUid() == client->uid()) {
2478 info->decreaseActiveClient();
2479 if (info->getActiveClientCount() == 0) {
2480 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2481 }
2482 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002483 }
2484 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002485}
2486
Eric Laurent97ac8712018-07-27 18:59:02 -07002487status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2488 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002489{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002490 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002491 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002492 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002493 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002494
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002495 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2496
François Gaffie1c878552018-11-22 16:53:21 +01002497 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2498 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002499 // Automatically disable the remote submix input when output is stopped on a
2500 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002501 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002502 if (isSingleDeviceType(
2503 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002504 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002505 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002506 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2507 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002508 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002509 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002510 }
2511 }
2512 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002513 if (client->hasPreferredDevice(true) &&
2514 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002515 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002516 forceDeviceUpdate = true;
2517 }
2518
Eric Laurente552edb2014-03-10 17:42:56 -07002519 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002520 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002521
Eric Laurente552edb2014-03-10 17:42:56 -07002522 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002523 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002524 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002525 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002526
2527 // If the routing does not change, if an output is routed on a device using HwGain
2528 // (aka setAudioPortConfig) and there are still active clients following different
2529 // volume group(s), force reapply volume
2530 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2531 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2532
Eric Laurente552edb2014-03-10 17:42:56 -07002533 // delay the device switch by twice the latency because stopOutput() is executed when
2534 // the track stop() command is received and at that time the audio track buffer can
2535 // still contain data that needs to be drained. The latency only covers the audio HAL
2536 // and kernel buffers. Also the latency does not always include additional delay in the
2537 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302538 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002539 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002540
2541 // force restoring the device selection on other active outputs if it differs from the
2542 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002543 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002544 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002545 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002546 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002547 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002548 desc->isActive() &&
2549 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002550 (newDevices != desc->devices())) {
2551 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2552 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002553
jiabin3ff8d7d2022-12-13 06:27:44 +00002554 if (desc->mUsePreferredMixerAttributes && force) {
2555 // If the device is using preferred mixer attributes, the output need to
2556 // reopen with default configuration when the new selected devices are
2557 // different from current routing devices.
2558 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2559 continue;
2560 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302561 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002562
Eric Laurent57de36c2016-09-28 16:59:11 -07002563 // re-apply device specific volume if not done by setOutputDevice()
2564 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002565 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002566 }
Eric Laurente552edb2014-03-10 17:42:56 -07002567 }
2568 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002569 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002570 // update the outputs if stopping one with a stream that can affect notification routing
2571 handleNotificationRoutingForStream(stream);
2572 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002573
2574 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2575 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002576 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002577 }
2578
François Gaffiec005e562018-11-06 15:04:49 +01002579 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002580 selectOutputForMusicEffects();
2581 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002582
2583 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2584
Eric Laurente552edb2014-03-10 17:42:56 -07002585 return NO_ERROR;
2586 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002587 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002588 return INVALID_OPERATION;
2589 }
2590}
2591
jiabinbce0c1d2020-10-05 11:20:18 -07002592bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002593{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002594 ALOGV("%s portId %d", __FUNCTION__, portId);
2595
2596 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2597 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002598 // If an output descriptor is closed due to a device routing change,
2599 // then there are race conditions with releaseOutput from tracks
2600 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2601 // destroyed shortly thereafter.
2602 //
2603 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002604 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002605 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002606 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002607
2608 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002609
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302610 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2611 if (outputDesc->isClientActive(client)) {
2612 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2613 stopOutput(portId);
2614 }
2615
Eric Laurent8fc147b2018-07-22 19:13:55 -07002616 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2617 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002618 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002619 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002620 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002621 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002622 if (--outputDesc->mDirectOpenCount == 0) {
2623 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002624 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002625 }
2626 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302627
Andy Hung39efb7a2018-09-26 15:39:28 -07002628 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002629 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2630 // The output is pending reopened to query dynamic profiles and
2631 // there is no active clients
2632 closeOutput(outputDesc->mIoHandle);
2633 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2634 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2635 if (newOutputDesc == nullptr) {
2636 ALOGE("%s failed to open output", __func__);
2637 }
2638 return true;
2639 }
2640 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002641}
2642
Eric Laurentcaf7f482014-11-25 17:50:47 -08002643status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2644 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002645 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002646 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002647 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002648 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002649 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002650 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002651 input_type_t *inputType,
2652 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002653{
François Gaffiec005e562018-11-06 15:04:49 +01002654 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002655 "flags %#x attributes=%s requested device ID %d",
2656 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2657 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002658
Eric Laurentad2e7b92017-09-14 20:06:42 -07002659 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002660 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002661 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002662 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002663 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002664 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002665 sp<RecordClientDescriptor> clientDesc;
2666 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002667 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002668 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002669
2670 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2671 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2672 return INVALID_OPERATION;
2673 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002674
Francois Gaffie716e1432019-01-14 16:58:59 +01002675 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2676 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002677 }
2678
Paul McLean466dc8e2015-04-17 13:15:36 -06002679 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002680 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002681 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002682
Eric Laurentad2e7b92017-09-14 20:06:42 -07002683 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2684 // possible
2685 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2686 *input != AUDIO_IO_HANDLE_NONE) {
2687 ssize_t index = mInputs.indexOfKey(*input);
2688 if (index < 0) {
2689 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2690 status = BAD_VALUE;
2691 goto error;
2692 }
2693 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002694 RecordClientVector clients = inputDesc->getClientsForSession(session);
2695 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002696 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2697 status = BAD_VALUE;
2698 goto error;
2699 }
2700 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2701 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002702 // corresponds to a new client and is only permitted from the same UID.
2703 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002704 if (clients.size() > 1) {
2705 for (const auto& client : clients) {
2706 // The client map is ordered by key values (portId) and portIds are allocated
2707 // incrementaly. So the first client in this list is the one opened by audio flinger
2708 // when the mmap stream is created and should be ignored as it does not correspond
2709 // to an actual client
2710 if (client == *clients.cbegin()) {
2711 continue;
2712 }
2713 if (uid != client->uid() && !client->isSilenced()) {
2714 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2715 uid, client->portId(), client->uid());
2716 status = INVALID_OPERATION;
2717 goto error;
2718 }
Eric Laurent331679c2018-04-16 17:03:16 -07002719 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002720 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002721 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002722 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002723
Eric Laurentfecbceb2021-02-09 14:46:43 +01002724 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002725 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002726 }
2727
2728 *input = AUDIO_IO_HANDLE_NONE;
2729 *inputType = API_INPUT_INVALID;
2730
Francois Gaffie716e1432019-01-14 16:58:59 +01002731 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002732 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002733 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002734 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002735 ALOGW("%s could not find input mix for attr %s",
2736 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002737 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002738 }
jiabinc1de2df2019-05-07 14:26:40 -07002739 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2740 String8(attr->tags + strlen("addr=")),
2741 AUDIO_FORMAT_DEFAULT);
2742 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002743 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002744 __func__, attributes.source, attributes.tags);
2745 status = BAD_VALUE;
2746 goto error;
2747 }
2748
Kevin Rocard25f9b052019-02-27 15:08:54 -08002749 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2750 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2751 } else {
2752 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2753 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002754 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002755 if (explicitRoutingDevice != nullptr) {
2756 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002757 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002758 // Prevent from storing invalid requested device id in clients
2759 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002760 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002761 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2762 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002763 }
François Gaffie11d30102018-11-02 16:09:09 +01002764 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002765 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002766 status = BAD_VALUE;
2767 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002768 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002769 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2770 *inputType = API_INPUT_MIX_CAPTURE;
2771 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002772 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2773 // there is an external policy, but this input is attached to a mix of recorders,
2774 // meaning it receives audio injected into the framework, so the recorder doesn't
2775 // know about it and is therefore considered "legacy"
2776 *inputType = API_INPUT_LEGACY;
2777 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002778 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002779 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002780 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002781 } else {
2782 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002783 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002784
Eric Laurent599c7582015-12-07 18:05:55 -08002785 }
2786
François Gaffiec005e562018-11-06 15:04:49 +01002787 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002788 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002789 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002790 AudioProfileVector profiles;
2791 status_t ret = getProfilesForDevices(
2792 DeviceVector(device), profiles, flags, true /*isInput*/);
2793 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002794 const auto channels = profiles[0]->getChannels();
2795 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2796 config->channel_mask = *channels.begin();
2797 }
2798 const auto sampleRates = profiles[0]->getSampleRates();
2799 if (!sampleRates.empty() &&
2800 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2801 config->sample_rate = *sampleRates.begin();
2802 }
jiabinf1c73972022-04-14 16:28:52 -07002803 config->format = profiles[0]->getFormat();
2804 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002805 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002806 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002807
Eric Laurent8f42ea12018-08-08 09:08:25 -07002808exit:
2809
François Gaffiec005e562018-11-06 15:04:49 +01002810 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2811 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002812
Francois Gaffie716e1432019-01-14 16:58:59 +01002813 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002814 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002815 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002816
Mikhail Naganov2996f672019-04-18 12:29:59 -07002817 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002818 requestedDeviceId, attributes.source, flags,
2819 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002820 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002821 // Move (if found) effect for the client session to its input
2822 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002823 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002824
2825 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2826 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002827
Eric Laurent599c7582015-12-07 18:05:55 -08002828 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002829
2830error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002831 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002832}
2833
2834
François Gaffie11d30102018-11-02 16:09:09 +01002835audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002836 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002837 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002838 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002839 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002840 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002841{
2842 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002843 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002844 bool isSoundTrigger = false;
2845
François Gaffiec005e562018-11-06 15:04:49 +01002846 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002847 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2848 if (index >= 0) {
2849 input = mSoundTriggerSessions.valueFor(session);
2850 isSoundTrigger = true;
2851 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2852 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2853 } else {
2854 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002855 }
François Gaffiec005e562018-11-06 15:04:49 +01002856 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002857 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002858 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002859 }
2860
Carter Hsua3abb402021-10-26 11:11:20 +08002861 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2862 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2863 }
2864
Eric Laurentfe231122017-11-17 17:48:06 -08002865 // sampling rate and flags may be updated by getInputProfile
2866 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2867 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002868 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002869 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002870 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002871 // find a compatible input profile (not necessarily identical in parameters)
2872 sp<IOProfile> profile = getInputProfile(
2873 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2874 if (profile == nullptr) {
2875 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002876 }
jiabin2fd710d2022-05-02 23:20:22 +00002877
Glenn Kasten05ddca52016-02-11 08:17:12 -08002878 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002879 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002880 if (samplingRate == 0) {
2881 samplingRate = profileSamplingRate;
2882 }
Eric Laurente552edb2014-03-10 17:42:56 -07002883
Eric Laurent322b4d22015-04-03 15:57:54 -07002884 if (profile->getModuleHandle() == 0) {
2885 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002886 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002887 }
2888
Eric Laurentec376dc2021-04-08 20:41:22 +02002889 // Reuse an already opened input if a client with the same session ID already exists
2890 // on that input
2891 for (size_t i = 0; i < mInputs.size(); i++) {
2892 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2893 if (desc->mProfile != profile) {
2894 continue;
2895 }
2896 RecordClientVector clients = desc->clientsList();
2897 for (const auto &client : clients) {
2898 if (session == client->session()) {
2899 return desc->mIoHandle;
2900 }
2901 }
2902 }
2903
Eric Laurent3974e3b2017-12-07 17:58:43 -08002904 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002905 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002906 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002907 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002908 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002909 continue;
2910 }
2911 // if sound trigger, reuse input if used by other sound trigger on same session
2912 // else
2913 // reuse input if active client app is not in IDLE state
2914 //
2915 RecordClientVector clients = desc->clientsList();
2916 bool doClose = false;
2917 for (const auto& client : clients) {
2918 if (isSoundTrigger != client->isSoundTrigger()) {
2919 continue;
2920 }
2921 if (client->isSoundTrigger()) {
2922 if (session == client->session()) {
2923 return desc->mIoHandle;
2924 }
2925 continue;
2926 }
2927 if (client->active() && client->appState() != APP_STATE_IDLE) {
2928 return desc->mIoHandle;
2929 }
2930 doClose = true;
2931 }
2932 if (doClose) {
2933 closeInput(desc->mIoHandle);
2934 } else {
2935 i++;
2936 }
2937 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002938 }
2939
Eric Laurentfe231122017-11-17 17:48:06 -08002940 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002941
Eric Laurentfe231122017-11-17 17:48:06 -08002942 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2943 lConfig.sample_rate = profileSamplingRate;
2944 lConfig.channel_mask = profileChannelMask;
2945 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002946
François Gaffie11d30102018-11-02 16:09:09 +01002947 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002948
2949 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002950 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002951 (profileSamplingRate != lConfig.sample_rate) ||
2952 !audio_formats_match(profileFormat, lConfig.format) ||
2953 (profileChannelMask != lConfig.channel_mask)) {
2954 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002955 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002956 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002957 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002958 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002959 }
Eric Laurent599c7582015-12-07 18:05:55 -08002960 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002961 }
2962
Eric Laurentc722f302014-12-10 11:21:49 -08002963 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002964
Eric Laurent599c7582015-12-07 18:05:55 -08002965 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002966 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002967
Eric Laurent599c7582015-12-07 18:05:55 -08002968 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002969}
2970
Eric Laurent4eb58f12018-12-07 16:41:02 -08002971status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002972{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002973 ALOGV("%s portId %d", __FUNCTION__, portId);
2974
2975 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2976 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002977 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002978 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002979 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002980 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002981 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002982 if (client->active()) {
2983 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2984 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002985 }
2986
Eric Laurent8f42ea12018-08-08 09:08:25 -07002987 audio_session_t session = client->session();
2988
Eric Laurent4eb58f12018-12-07 16:41:02 -08002989 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002990
Eric Laurent4eb58f12018-12-07 16:41:02 -08002991 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002992
Eric Laurent4eb58f12018-12-07 16:41:02 -08002993 status_t status = inputDesc->start();
2994 if (status != NO_ERROR) {
2995 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002996 }
Eric Laurente552edb2014-03-10 17:42:56 -07002997
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002998 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002999 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003000 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003001
Eric Laurent8f42ea12018-08-08 09:08:25 -07003002 // indicate active capture to sound trigger service if starting capture from a mic on
3003 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003004 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003005 if (device != nullptr) {
3006 status = setInputDevice(input, device, true /* force */);
3007 } else {
3008 ALOGW("%s no new input device can be found for descriptor %d",
3009 __FUNCTION__, inputDesc->getId());
3010 status = BAD_VALUE;
3011 }
Eric Laurente552edb2014-03-10 17:42:56 -07003012
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003013 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003014 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003015 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003016 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003017 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3018 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003019 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003020 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003021
François Gaffie11d30102018-11-02 16:09:09 +01003022 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3023 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003024 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003025 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003026 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003027
Eric Laurent8f42ea12018-08-08 09:08:25 -07003028 // automatically enable the remote submix output when input is started if not
3029 // used by a policy mix of type MIX_TYPE_RECORDERS
3030 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003031 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003032 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003033 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003034 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003035 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3036 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003037 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003038 if (address != "") {
3039 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3040 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003041 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003042 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003043 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003044 } else if (status != NO_ERROR) {
3045 // Restore client activity state.
3046 inputDesc->setClientActive(client, false);
3047 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003048 }
3049
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003050 ALOGV("%s input %d source = %d status = %d exit",
3051 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003052
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003053 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003054}
3055
Eric Laurent8fc147b2018-07-22 19:13:55 -07003056status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003057{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003058 ALOGV("%s portId %d", __FUNCTION__, portId);
3059
3060 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3061 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003063 return BAD_VALUE;
3064 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003065 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003066 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003067 if (!client->active()) {
3068 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003069 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003070 }
Carter Hsue6139d52021-07-08 10:30:20 +08003071 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003073
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074 inputDesc->stop();
3075 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003076 auto current_source = inputDesc->source();
3077 setInputDevice(input, getNewInputDevice(inputDesc),
3078 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003079 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003080 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003081 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003082 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003083 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3084 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003085 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003086 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003087
3088 // automatically disable the remote submix output when input is stopped if not
3089 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003090 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003091 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003092 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003093 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003094 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3095 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003096 }
3097 if (address != "") {
3098 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3099 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003100 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003101 }
3102 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003103 resetInputDevice(input);
3104
3105 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3106 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003107 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3108 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003109 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003110 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003111 }
3112 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003113 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003114 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003115}
3116
Eric Laurent8fc147b2018-07-22 19:13:55 -07003117void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003118{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003119 ALOGV("%s portId %d", __FUNCTION__, portId);
3120
3121 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3122 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003123 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003124 return;
3125 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003126 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003127 audio_io_handle_t input = inputDesc->mIoHandle;
3128
Eric Laurent8f42ea12018-08-08 09:08:25 -07003129 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003130
Andy Hung39efb7a2018-09-26 15:39:28 -07003131 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003132 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003133 if (inputDesc->getClientCount() > 0) {
3134 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003135 return;
3136 }
3137
Eric Laurent05b90f82014-08-27 15:32:29 -07003138 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003139 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003140 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003141}
3142
Eric Laurent8f42ea12018-08-08 09:08:25 -07003143void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003144{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003145 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003146
3147 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003148 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003149 }
3150}
3151
Eric Laurent8f42ea12018-08-08 09:08:25 -07003152void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3153{
3154 stopInput(portId);
3155 releaseInput(portId);
3156}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003157
Eric Laurent0dd51852019-04-19 18:18:58 -07003158void AudioPolicyManager::checkCloseInputs() {
3159 // After connecting or disconnecting an input device, close input if:
3160 // - it has no client (was just opened to check profile) OR
3161 // - none of its supported devices are connected anymore OR
3162 // - one of its clients cannot be routed to one of its supported
3163 // devices anymore. Otherwise update device selection
3164 std::vector<audio_io_handle_t> inputsToClose;
3165 for (size_t i = 0; i < mInputs.size(); i++) {
3166 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3167 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003168 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003169 inputsToClose.push_back(mInputs.keyAt(i));
3170 } else {
3171 bool close = false;
3172 for (const auto& client : input->clientsList()) {
3173 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003174 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3175 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003176 if (!input->supportedDevices().contains(device)) {
3177 close = true;
3178 break;
3179 }
3180 }
3181 if (close) {
3182 inputsToClose.push_back(mInputs.keyAt(i));
3183 } else {
3184 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3185 }
3186 }
3187 }
3188
3189 for (const audio_io_handle_t handle : inputsToClose) {
3190 ALOGV("%s closing input %d", __func__, handle);
3191 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003192 }
Eric Laurentd4692962014-05-05 18:13:44 -07003193}
3194
François Gaffie251c7f02018-11-07 10:41:08 +01003195void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003196{
3197 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003198 if (indexMin < 0 || indexMax < 0) {
3199 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3200 return;
3201 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003202 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003203
3204 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003205 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3206 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003207 continue;
3208 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003209 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003210 }
Eric Laurente552edb2014-03-10 17:42:56 -07003211}
3212
Eric Laurente0720872014-03-11 09:30:41 -07003213status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003214 int index,
3215 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003216{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003217 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003218 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3219 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3220 return NO_ERROR;
3221 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003222 ALOGV("%s: stream %s attributes=%s", __func__,
3223 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003224 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003225}
3226
Eric Laurente0720872014-03-11 09:30:41 -07003227status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003228 int *index,
3229 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003230{
François Gaffiec005e562018-11-06 15:04:49 +01003231 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3232 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003233 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003234 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003235 deviceTypes = mEngine->getOutputDevicesForStream(
3236 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003237 }
jiabin9a3361e2019-10-01 09:38:30 -07003238 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003239}
3240
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003241status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003242 int index,
3243 audio_devices_t device)
3244{
3245 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003246 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3247 if (group == VOLUME_GROUP_NONE) {
3248 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003249 return BAD_VALUE;
3250 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003251 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003252 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003253 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003254 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003255 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3256 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3257 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3258 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003259 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3260
3261 status = setVolumeCurveIndex(index, device, curves);
3262 if (status != NO_ERROR) {
3263 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3264 return status;
3265 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003266
jiabin9a3361e2019-10-01 09:38:30 -07003267 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003268 auto curCurvAttrs = curves.getAttributes();
3269 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3270 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003271 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003272 } else if (!curves.getStreamTypes().empty()) {
3273 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003274 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003275 } else {
3276 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3277 return BAD_VALUE;
3278 }
jiabin9a3361e2019-10-01 09:38:30 -07003279 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3280 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003281
François Gaffiecfe17322018-11-07 13:41:29 +01003282 // update volume on all outputs and streams matching the following:
3283 // - The requested stream (or a stream matching for volume control) is active on the output
3284 // - The device (or devices) selected by the engine for this stream includes
3285 // the requested device
3286 // - For non default requested device, currently selected device on the output is either the
3287 // requested device or one of the devices selected by the engine for this stream
3288 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3289 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003290 for (size_t i = 0; i < mOutputs.size(); i++) {
3291 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003292 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003293
jiabin9a3361e2019-10-01 09:38:30 -07003294 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3295 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003296 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003297
3298 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003299 continue;
3300 }
3301 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3302 curDevices.find(device) == curDevices.end()) {
3303 continue;
3304 }
3305 bool applyVolume = false;
3306 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3307 curSrcDevices.insert(device);
3308 applyVolume = (curSrcDevices.find(
3309 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3310 } else {
3311 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3312 }
3313 if (!applyVolume) {
3314 continue; // next output
3315 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003316 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3317 // If a higher priority strategy is active, and the output is routed to a device with a
3318 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003319 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003320 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003321 // If the volume source is active with higher priority source, ensure at least Sw Muted
3322 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003323 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3324 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3325 false /*preferredDevice*/);
3326 if (activeClients.empty()) {
3327 continue;
3328 }
3329 bool isPreempted = false;
3330 bool isHigherPriority = productStrategy < strategy;
3331 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003332 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003333 ALOGV("%s: Strategy=%d (\nrequester:\n"
3334 " group %d, volumeGroup=%d attributes=%s)\n"
3335 " higher priority source active:\n"
3336 " volumeGroup=%d attributes=%s) \n"
3337 " on output %zu, bailing out", __func__, productStrategy,
3338 group, group, toString(attributes).c_str(),
3339 client->volumeSource(), toString(client->attributes()).c_str(), i);
3340 applyVolume = false;
3341 isPreempted = true;
3342 break;
3343 }
3344 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003345 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003346 applyVolume = true;
3347 }
3348 }
3349 if (isPreempted || applyVolume) {
3350 break;
3351 }
3352 }
3353 if (!applyVolume) {
3354 continue; // next output
3355 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003356 }
François Gaffieed91f582020-01-31 10:35:37 +01003357 //FIXME: workaround for truncated touch sounds
3358 // delayed volume change for system stream to be removed when the problem is
3359 // handled by system UI
3360 status_t volStatus = checkAndSetVolume(
3361 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003362 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003363 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3364 if (volStatus != NO_ERROR) {
3365 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003366 }
3367 }
François Gaffiecfe17322018-11-07 13:41:29 +01003368 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3369 return status;
3370}
3371
François Gaffieaaac0fd2018-11-22 17:56:39 +01003372status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003373 audio_devices_t device,
3374 IVolumeCurves &volumeCurves)
3375{
3376 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3377 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003378 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3379 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003380 (index > volumeCurves.getVolumeIndexMax())) {
3381 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3382 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3383 return BAD_VALUE;
3384 }
3385 if (!audio_is_output_device(device)) {
3386 return BAD_VALUE;
3387 }
3388
3389 // Force max volume if stream cannot be muted
3390 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3391
François Gaffieaaac0fd2018-11-22 17:56:39 +01003392 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003393 volumeCurves.addCurrentVolumeIndex(device, index);
3394 return NO_ERROR;
3395}
3396
3397status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3398 int &index,
3399 audio_devices_t device)
3400{
3401 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3402 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003403 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003404 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003405 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003406 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003407 }
jiabin9a3361e2019-10-01 09:38:30 -07003408 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003409}
3410
3411status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3412 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003413 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003414{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003415 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003416 return BAD_VALUE;
3417 }
jiabin9a3361e2019-10-01 09:38:30 -07003418 index = curves.getVolumeIndex(deviceTypes);
3419 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003420 return NO_ERROR;
3421}
3422
3423status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3424 int &index)
3425{
3426 index = getVolumeCurves(attr).getVolumeIndexMin();
3427 return NO_ERROR;
3428}
3429
3430status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3431 int &index)
3432{
3433 index = getVolumeCurves(attr).getVolumeIndexMax();
3434 return NO_ERROR;
3435}
3436
Eric Laurent36829f92017-04-07 19:04:42 -07003437audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003438{
3439 // select one output among several suitable for global effects.
3440 // The priority is as follows:
3441 // 1: An offloaded output. If the effect ends up not being offloadable,
3442 // AudioFlinger will invalidate the track and the offloaded output
3443 // will be closed causing the effect to be moved to a PCM output.
3444 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003445 // 3: The primary output
3446 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003447
François Gaffiec005e562018-11-06 15:04:49 +01003448 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3449 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003450 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003451
Eric Laurent36829f92017-04-07 19:04:42 -07003452 if (outputs.size() == 0) {
3453 return AUDIO_IO_HANDLE_NONE;
3454 }
Eric Laurente552edb2014-03-10 17:42:56 -07003455
Eric Laurent36829f92017-04-07 19:04:42 -07003456 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3457 bool activeOnly = true;
3458
3459 while (output == AUDIO_IO_HANDLE_NONE) {
3460 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3461 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3462 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3463
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003464 for (audio_io_handle_t output : outputs) {
3465 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003466 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003467 continue;
3468 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003469 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3470 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003471 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003472 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003473 }
3474 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003475 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003476 }
3477 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003478 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003479 }
3480 }
3481 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3482 output = outputOffloaded;
3483 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3484 output = outputDeepBuffer;
3485 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3486 output = outputPrimary;
3487 } else {
3488 output = outputs[0];
3489 }
3490 activeOnly = false;
3491 }
3492
3493 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003494 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3495 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003496 mMusicEffectOutput = output;
3497 }
3498
3499 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003500 return output;
3501}
3502
Eric Laurent36829f92017-04-07 19:04:42 -07003503audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3504{
3505 return selectOutputForMusicEffects();
3506}
3507
Eric Laurente0720872014-03-11 09:30:41 -07003508status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003509 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003510 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003511 int session,
3512 int id)
3513{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003514 if (session != AUDIO_SESSION_DEVICE) {
3515 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003516 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003517 index = mInputs.indexOfKey(io);
3518 if (index < 0) {
3519 ALOGW("registerEffect() unknown io %d", io);
3520 return INVALID_OPERATION;
3521 }
Eric Laurente552edb2014-03-10 17:42:56 -07003522 }
3523 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003524 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3525 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3526 || strategy == PRODUCT_STRATEGY_NONE));
3527 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003528}
3529
Eric Laurentc241b0d2018-11-28 09:08:49 -08003530status_t AudioPolicyManager::unregisterEffect(int id)
3531{
3532 if (mEffects.getEffect(id) == nullptr) {
3533 return INVALID_OPERATION;
3534 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003535 if (mEffects.isEffectEnabled(id)) {
3536 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3537 setEffectEnabled(id, false);
3538 }
3539 return mEffects.unregisterEffect(id);
3540}
3541
3542status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3543{
3544 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3545 if (effect == nullptr) {
3546 return INVALID_OPERATION;
3547 }
3548
3549 status_t status = mEffects.setEffectEnabled(id, enabled);
3550 if (status == NO_ERROR) {
3551 mInputs.trackEffectEnabled(effect, enabled);
3552 }
3553 return status;
3554}
3555
Eric Laurent6c796322019-04-09 14:13:17 -07003556
3557status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3558{
3559 mEffects.moveEffects(ids, io);
3560 return NO_ERROR;
3561}
3562
Eric Laurentc75307b2015-03-17 15:29:32 -07003563bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3564{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003565 auto vs = toVolumeSource(stream, false);
3566 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003567}
3568
3569bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3570{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003571 auto vs = toVolumeSource(stream, false);
3572 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003573}
3574
Eric Laurente0720872014-03-11 09:30:41 -07003575bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003576{
3577 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003578 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003579 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003580 return true;
3581 }
3582 }
3583 return false;
3584}
3585
Eric Laurent275e8e92014-11-30 15:14:47 -08003586// Register a list of custom mixes with their attributes and format.
3587// When a mix is registered, corresponding input and output profiles are
3588// added to the remote submix hw module. The profile contains only the
3589// parameters (sampling rate, format...) specified by the mix.
3590// The corresponding input remote submix device is also connected.
3591//
3592// When a remote submix device is connected, the address is checked to select the
3593// appropriate profile and the corresponding input or output stream is opened.
3594//
3595// When capture starts, getInputForAttr() will:
3596// - 1 look for a mix matching the address passed in attribtutes tags if any
3597// - 2 if none found, getDeviceForInputSource() will:
3598// - 2.1 look for a mix matching the attributes source
3599// - 2.2 if none found, default to device selection by policy rules
3600// At this time, the corresponding output remote submix device is also connected
3601// and active playback use cases can be transferred to this mix if needed when reconnecting
3602// after AudioTracks are invalidated
3603//
3604// When playback starts, getOutputForAttr() will:
3605// - 1 look for a mix matching the address passed in attribtutes tags if any
3606// - 2 if none found, look for a mix matching the attributes usage
3607// - 3 if none found, default to device and output selection by policy rules.
3608
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003609status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003610{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003611 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3612 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003613 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003614 sp<HwModule> rSubmixModule;
3615 // examine each mix's route type
3616 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003617 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003618 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3619 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3620 ALOGE("Unsupported Policy Mix %zu of %zu: "
3621 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3622 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003623 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003624 break;
3625 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003626 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3627 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003628 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003629 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3630 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003631 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003632 rSubmixModule = mHwModules.getModuleFromName(
3633 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3634 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003635 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003636 i);
3637 res = INVALID_OPERATION;
3638 break;
3639 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003640 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003641
Eric Laurent97ac8712018-07-27 18:59:02 -07003642 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003643 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003644 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003645 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003646 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3647 } else {
3648 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3649 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003650 }
François Gaffie036e1e92015-03-19 10:16:24 +01003651
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003652 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003653 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003654 res = INVALID_OPERATION;
3655 break;
3656 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003657 audio_config_t outputConfig = mix.mFormat;
3658 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003659 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3660 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003661 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3662 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003663 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003664 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003665 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003666 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003667
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003668 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003669 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003670 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003671 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003672 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003673 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003674 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003675 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3676 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003677 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003678 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003679 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003680
3681 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3682 mix.mDeviceType, mix.mDeviceAddress,
3683 String8(), AUDIO_FORMAT_DEFAULT);
3684 if (device == nullptr) {
3685 res = INVALID_OPERATION;
3686 break;
3687 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003688
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003689 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003690 // First try to find an already opened output supporting the device
3691 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003692 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003693
Eric Laurentc529cf62020-04-17 18:19:10 -07003694 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003695 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003696 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003697 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003698 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003699 } else {
3700 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003701 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003702 }
3703 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003704 // If no output found, try to find a direct output profile supporting the device
3705 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3706 sp<HwModule> module = mHwModules[i];
3707 for (size_t j = 0;
3708 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3709 j++) {
3710 sp<IOProfile> profile = module->getOutputProfiles()[j];
3711 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3712 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3713 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003714 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003715 res = INVALID_OPERATION;
3716 } else {
3717 foundOutput = true;
3718 }
3719 }
3720 }
3721 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003722 if (res != NO_ERROR) {
3723 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003724 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003725 res = INVALID_OPERATION;
3726 break;
3727 } else if (!foundOutput) {
3728 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003729 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003730 res = INVALID_OPERATION;
3731 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003732 } else {
3733 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003734 }
Eric Laurentc722f302014-12-10 11:21:49 -08003735 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003736 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003737 if (res != NO_ERROR) {
3738 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003739 } else if (checkOutputs) {
3740 checkForDeviceAndOutputChanges();
3741 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003742 }
3743 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003744}
3745
3746status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3747{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003748 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003749 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003750 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003751 sp<HwModule> rSubmixModule;
3752 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003753 for (const auto& mix : mixes) {
3754 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003755
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003756 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003757 rSubmixModule = mHwModules.getModuleFromName(
3758 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3759 if (rSubmixModule == 0) {
3760 res = INVALID_OPERATION;
3761 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003762 }
3763 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003764
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003765 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003766
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003767 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003768 res = INVALID_OPERATION;
3769 continue;
3770 }
3771
Kevin Rocard04ed0462019-05-02 17:53:24 -07003772 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003773 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003774 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3775 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003776 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003777 AUDIO_FORMAT_DEFAULT);
3778 if (res != OK) {
3779 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003780 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003781 }
3782 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003783 }
jiabin5740f082019-08-19 15:08:30 -07003784 rSubmixModule->removeOutputProfile(address.c_str());
3785 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003786
Kevin Rocard153f92d2018-12-18 18:33:28 -08003787 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003788 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003789 res = INVALID_OPERATION;
3790 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003791 } else {
3792 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003793 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003794 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003795 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003796 if (res == NO_ERROR && checkOutputs) {
3797 checkForDeviceAndOutputChanges();
3798 updateCallAndOutputRouting();
3799 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003800 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003801}
3802
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003803status_t AudioPolicyManager::updatePolicyMix(
3804 const AudioMix& mix,
3805 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3806 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3807 if (res == NO_ERROR) {
3808 checkForDeviceAndOutputChanges();
3809 updateCallAndOutputRouting();
3810 }
3811 return res;
3812}
3813
Mikhail Naganov100f0122018-11-29 11:22:16 -08003814void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3815{
3816 size_t i = 0;
3817 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3818 for (const auto& fmt : mManualSurroundFormats) {
3819 if (i++ != 0) dst->append(", ");
3820 std::string sfmt;
3821 FormatConverter::toString(fmt, sfmt);
3822 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3823 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3824 }
3825}
3826
Eric Laurentc529cf62020-04-17 18:19:10 -07003827// Returns true if all devices types match the predicate and are supported by one HW module
3828bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003829 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003830 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003831 const char *context,
3832 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003833 for (size_t i = 0; i < devices.size(); i++) {
3834 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003835 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003836 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003837 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003838 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003839 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003840 return false;
3841 }
3842 }
3843 return true;
3844}
3845
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003846void AudioPolicyManager::changeOutputDevicesMuteState(
3847 const AudioDeviceTypeAddrVector& devices) {
3848 ALOGVV("%s() num devices %zu", __func__, devices.size());
3849
3850 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3851 getSoftwareOutputsForDevices(devices);
3852
3853 for (size_t i = 0; i < outputs.size(); i++) {
3854 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3855 DeviceVector prevDevices = outputDesc->devices();
3856 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3857 }
3858}
3859
3860std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3861 const AudioDeviceTypeAddrVector& devices) const
3862{
3863 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3864 DeviceVector deviceDescriptors;
3865 for (size_t j = 0; j < devices.size(); j++) {
3866 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3867 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3868 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3869 ALOGE("%s: device type %#x address %s not supported or not an output device",
3870 __func__, devices[j].mType, devices[j].getAddress());
3871 continue;
3872 }
3873 deviceDescriptors.add(desc);
3874 }
3875 for (size_t i = 0; i < mOutputs.size(); i++) {
3876 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3877 continue;
3878 }
3879 outputs.push_back(mOutputs.valueAt(i));
3880 }
3881 return outputs;
3882}
3883
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003884status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003885 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003886 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003887 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3888 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003889 }
3890 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003891 if (res != NO_ERROR) {
3892 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3893 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003894 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003895
3896 checkForDeviceAndOutputChanges();
3897 updateCallAndOutputRouting();
3898
3899 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003900}
3901
3902status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3903 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003904 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3905 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003906 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003907 __FUNCTION__, uid);
3908 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003909 }
3910
Eric Laurentc529cf62020-04-17 18:19:10 -07003911 checkForDeviceAndOutputChanges();
3912 updateCallAndOutputRouting();
3913
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003914 return res;
3915}
3916
Eric Laurent2517af32020-11-25 15:31:27 +01003917
jiabin0a488932020-08-07 17:32:40 -07003918status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3919 device_role_t role,
3920 const AudioDeviceTypeAddrVector &devices) {
3921 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3922 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003923
Eric Laurentc529cf62020-04-17 18:19:10 -07003924 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003925 return BAD_VALUE;
3926 }
jiabin0a488932020-08-07 17:32:40 -07003927 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003928 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003929 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3930 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003931 return status;
3932 }
3933
3934 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003935
3936 bool forceVolumeReeval = false;
3937 // FIXME: workaround for truncated touch sounds
3938 // to be removed when the problem is handled by system UI
3939 uint32_t delayMs = 0;
3940 if (strategy == mCommunnicationStrategy) {
3941 forceVolumeReeval = true;
3942 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3943 updateInputRouting();
3944 }
3945 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003946
3947 return NO_ERROR;
3948}
3949
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003950void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3951 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003952{
3953 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003954 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003955 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003956 // Only apply special touch sound delay once
3957 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003958 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003959 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003960 for (size_t i = 0; i < mOutputs.size(); i++) {
3961 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3962 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003963 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3964 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003965 // As done in setDeviceConnectionState, we could also fix default device issue by
3966 // preventing the force re-routing in case of default dev that distinguishes on address.
3967 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003968 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00003969 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
3970 // If the device is using preferred mixer attributes, the output need to reopen
3971 // with default configuration when the new selected devices are different from
3972 // current routing devices.
3973 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
3974 continue;
3975 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05303976
3977 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
3978 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003979 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003980 // Only apply special touch sound delay once
3981 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003982 }
3983 if (forceVolumeReeval && !newDevices.isEmpty()) {
3984 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3985 }
3986 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003987 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01003988 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003989}
3990
Eric Laurent2517af32020-11-25 15:31:27 +01003991void AudioPolicyManager::updateInputRouting() {
3992 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303993 // Skip for hotword recording as the input device switch
3994 // is handled within sound trigger HAL
3995 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3996 continue;
3997 }
Eric Laurent2517af32020-11-25 15:31:27 +01003998 auto newDevice = getNewInputDevice(activeDesc);
3999 // Force new input selection if the new device can not be reached via current input
4000 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4001 setInputDevice(activeDesc->mIoHandle, newDevice);
4002 } else {
4003 closeInput(activeDesc->mIoHandle);
4004 }
4005 }
4006}
4007
Paul Wang5d7cdb52022-11-22 09:45:06 +00004008status_t
4009AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4010 device_role_t role,
4011 const AudioDeviceTypeAddrVector &devices) {
4012 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4013 dumpAudioDeviceTypeAddrVector(devices).c_str());
4014
Eric Laurent78fedbf2023-03-09 14:40:44 +01004015 if (!areAllDevicesSupported(
4016 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004017 return BAD_VALUE;
4018 }
4019 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4020 if (status != NO_ERROR) {
4021 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4022 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4023 return status;
4024 }
4025
4026 checkForDeviceAndOutputChanges();
4027
4028 bool forceVolumeReeval = false;
4029 // TODO(b/263479999): workaround for truncated touch sounds
4030 // to be removed when the problem is handled by system UI
4031 uint32_t delayMs = 0;
4032 if (strategy == mCommunnicationStrategy) {
4033 forceVolumeReeval = true;
4034 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4035 updateInputRouting();
4036 }
4037 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4038
4039 return NO_ERROR;
4040}
4041
4042status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4043 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004044{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004045 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004046
Paul Wang5d7cdb52022-11-22 09:45:06 +00004047 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004048 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004049 ALOGW_IF(status != NAME_NOT_FOUND,
4050 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004051 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004052 return status;
4053 }
4054
4055 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004056
4057 bool forceVolumeReeval = false;
4058 // FIXME: workaround for truncated touch sounds
4059 // to be removed when the problem is handled by system UI
4060 uint32_t delayMs = 0;
4061 if (strategy == mCommunnicationStrategy) {
4062 forceVolumeReeval = true;
4063 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4064 updateInputRouting();
4065 }
4066 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004067
4068 return NO_ERROR;
4069}
4070
jiabin0a488932020-08-07 17:32:40 -07004071status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4072 device_role_t role,
4073 AudioDeviceTypeAddrVector &devices) {
4074 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004075}
4076
Jiabin Huang3b98d322020-09-03 17:54:16 +00004077status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4078 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4079 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4080 dumpAudioDeviceTypeAddrVector(devices).c_str());
4081
Mikhail Naganov55773032020-10-01 15:08:13 -07004082 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004083 return BAD_VALUE;
4084 }
4085 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4086 ALOGW_IF(status != NO_ERROR,
4087 "Engine could not set preferred devices %s for audio source %d role %d",
4088 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4089
4090 return status;
4091}
4092
4093status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4094 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4095 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4096 dumpAudioDeviceTypeAddrVector(devices).c_str());
4097
Mikhail Naganov55773032020-10-01 15:08:13 -07004098 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004099 return BAD_VALUE;
4100 }
4101 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4102 ALOGW_IF(status != NO_ERROR,
4103 "Engine could not add preferred devices %s for audio source %d role %d",
4104 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4105
Eric Laurent2517af32020-11-25 15:31:27 +01004106 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004107 return status;
4108}
4109
4110status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4111 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4112{
4113 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4114 dumpAudioDeviceTypeAddrVector(devices).c_str());
4115
Eric Laurent78fedbf2023-03-09 14:40:44 +01004116 if (!areAllDevicesSupported(
4117 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004118 return BAD_VALUE;
4119 }
4120
4121 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4122 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004123 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004124 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004125 if (status == NO_ERROR) {
4126 updateInputRouting();
4127 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004128 return status;
4129}
4130
4131status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4132 device_role_t role) {
4133 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4134
4135 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004136 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004137 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004138 if (status == NO_ERROR) {
4139 updateInputRouting();
4140 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004141 return status;
4142}
4143
4144status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4145 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4146 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4147}
4148
Oscar Azucena90e77632019-11-27 17:12:28 -08004149status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004150 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004151 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004152 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4153 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004154 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004155 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4156 if (status != NO_ERROR) {
4157 ALOGE("%s() could not set device affinity for userId %d",
4158 __FUNCTION__, userId);
4159 return status;
4160 }
4161
4162 // reevaluate outputs for all devices
4163 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004164 changeOutputDevicesMuteState(devices);
4165 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4166 true /* skipDelays */);
4167 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004168
4169 return NO_ERROR;
4170}
4171
4172status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004173 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004174 AudioDeviceTypeAddrVector devices;
4175 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004176 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4177 if (status != NO_ERROR) {
4178 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4179 __FUNCTION__, userId);
4180 return status;
4181 }
4182
4183 // reevaluate outputs for all devices
4184 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004185 changeOutputDevicesMuteState(devices);
4186 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4187 true /* skipDelays */);
4188 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004189
4190 return NO_ERROR;
4191}
4192
Andy Hungc29d82b2018-10-05 12:23:17 -07004193void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004194{
Andy Hungc29d82b2018-10-05 12:23:17 -07004195 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004196 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004197 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004198 std::string stateLiteral;
4199 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004200 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004201 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4202 "communications", "media", "record", "dock", "system",
4203 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4204 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4205 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004206 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4207 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4208 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4209 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4210 dst->append(" (MANUAL: ");
4211 dumpManualSurroundFormats(dst);
4212 dst->append(")");
4213 }
4214 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004215 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004216 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4217 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004218 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004219 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004220
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004221 dst->append("\n");
4222 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4223 dst->append("\n");
4224 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004225 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004226 mOutputs.dump(dst);
4227 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004228 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004229 mAudioPatches.dump(dst);
4230 mPolicyMixes.dump(dst);
4231 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004232
Kevin Rocardb99cc752019-03-21 20:52:24 -07004233 dst->appendFormat(" AllowedCapturePolicies:\n");
4234 for (auto& policy : mAllowedCapturePolicies) {
4235 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4236 }
4237
jiabina84c3d32022-12-02 18:59:55 +00004238 dst->appendFormat(" Preferred mixer audio configuration:\n");
4239 for (const auto it : mPreferredMixerAttrInfos) {
4240 dst->appendFormat(" - device port id: %d\n", it.first);
4241 for (const auto preferredMixerInfoIt : it.second) {
4242 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4243 preferredMixerInfoIt.second->dump(dst);
4244 }
4245 }
4246
François Gaffiec005e562018-11-06 15:04:49 +01004247 dst->appendFormat("\nPolicy Engine dump:\n");
4248 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004249}
4250
4251status_t AudioPolicyManager::dump(int fd)
4252{
4253 String8 result;
4254 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004255 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004256 return NO_ERROR;
4257}
4258
Kevin Rocardb99cc752019-03-21 20:52:24 -07004259status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4260{
4261 mAllowedCapturePolicies[uid] = capturePolicy;
4262 return NO_ERROR;
4263}
4264
Eric Laurente552edb2014-03-10 17:42:56 -07004265// This function checks for the parameters which can be offloaded.
4266// This can be enhanced depending on the capability of the DSP and policy
4267// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004268audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004269{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004270 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004271 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004272 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004273 offloadInfo.format,
4274 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4275 offloadInfo.has_video);
4276
jiabin2b9d5a12021-12-10 01:06:29 +00004277 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004278 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004279 }
4280
4281 // See if there is a profile to support this.
4282 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004283 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004284 offloadInfo.sample_rate,
4285 offloadInfo.format,
4286 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004287 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4288 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004289 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4290 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4291 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004292 if (profile == nullptr) {
4293 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4294 }
4295 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4296 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4297 }
4298 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004299}
4300
Michael Chana94fbb22018-04-24 14:31:19 +10004301bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4302 const audio_attributes_t& attributes) {
4303 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004304 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004305 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4306 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004307 config.sample_rate,
4308 config.format,
4309 config.channel_mask,
4310 output_flags,
4311 true /* directOnly */);
4312 ALOGV("%s() profile %sfound with name: %s, "
4313 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4314 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004315 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004316 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004317
4318 // also try the MSD module if compatible profile not found
4319 if (profile == nullptr) {
4320 profile = getMsdProfileForOutput(outputDevices,
4321 config.sample_rate,
4322 config.format,
4323 config.channel_mask,
4324 output_flags,
4325 true /* directOnly */);
4326 ALOGV("%s() MSD profile %sfound with name: %s, "
4327 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4328 __FUNCTION__, profile != 0 ? "" : "NOT ",
4329 (profile != 0 ? profile->getTagName().c_str() : "null"),
4330 config.sample_rate, config.format, config.channel_mask, output_flags);
4331 }
4332 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004333}
4334
jiabin2b9d5a12021-12-10 01:06:29 +00004335bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4336 bool durationIgnored) {
4337 if (mMasterMono) {
4338 return false; // no offloading if mono is set.
4339 }
4340
4341 // Check if offload has been disabled
4342 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4343 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4344 return false;
4345 }
4346
4347 // Check if stream type is music, then only allow offload as of now.
4348 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4349 {
4350 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4351 return false;
4352 }
4353
4354 //TODO: enable audio offloading with video when ready
4355 const bool allowOffloadWithVideo =
4356 property_get_bool("audio.offload.video", false /* default_value */);
4357 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4358 ALOGV("%s: has_video == true, returning false", __func__);
4359 return false;
4360 }
4361
4362 //If duration is less than minimum value defined in property, return false
4363 const int min_duration_secs = property_get_int32(
4364 "audio.offload.min.duration.secs", -1 /* default_value */);
4365 if (!durationIgnored) {
4366 if (min_duration_secs >= 0) {
4367 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4368 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4369 __func__, min_duration_secs);
4370 return false;
4371 }
4372 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4373 ALOGV("%s: Offload denied by duration < default min(=%u)",
4374 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4375 return false;
4376 }
4377 }
4378
4379 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4380 // creating an offloaded track and tearing it down immediately after start when audioflinger
4381 // detects there is an active non offloadable effect.
4382 // FIXME: We should check the audio session here but we do not have it in this context.
4383 // This may prevent offloading in rare situations where effects are left active by apps
4384 // in the background.
4385 if (mEffects.isNonOffloadableEffectEnabled()) {
4386 return false;
4387 }
4388
4389 return true;
4390}
4391
4392audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4393 const audio_config_t *config) {
4394 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4395 offloadInfo.format = config->format;
4396 offloadInfo.sample_rate = config->sample_rate;
4397 offloadInfo.channel_mask = config->channel_mask;
4398 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4399 offloadInfo.has_video = false;
4400 offloadInfo.is_streaming = false;
4401 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4402
4403 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4404 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4405 audio_flags_to_audio_output_flags(attr->flags, &flags);
4406 // only retain flags that will drive compressed offload or passthrough
4407 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4408 if (offloadPossible) {
4409 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4410 }
4411 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4412
Dorin Drimusfae3c642022-03-17 18:36:30 +01004413 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004414 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004415 DeviceVector outputDevices = engineOutputDevices;
4416 // the MSD module checks for different conditions and output devices
4417 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4418 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4419 continue;
4420 }
4421 outputDevices = getMsdAudioOutDevices();
4422 }
jiabin2b9d5a12021-12-10 01:06:29 +00004423 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004424 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004425 config->sample_rate, nullptr /*updatedSamplingRate*/,
4426 config->format, nullptr /*updatedFormat*/,
4427 config->channel_mask, nullptr /*updatedChannelMask*/,
4428 flags)) {
4429 continue;
4430 }
4431 // reject profiles not corresponding to a device currently available
4432 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4433 continue;
4434 }
4435 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4436 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004437 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004438 != AUDIO_DIRECT_NOT_SUPPORTED) {
4439 // Already reports offload gapless supported. No need to report offload support.
4440 continue;
4441 }
4442 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4443 != AUDIO_OUTPUT_FLAG_NONE) {
4444 // If offload gapless is reported, no need to report offload support.
4445 directMode = (audio_direct_mode_t) ((directMode &
4446 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4447 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4448 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004449 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004450 }
4451 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004452 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004453 }
4454 }
4455 }
4456 return directMode;
4457}
4458
Dorin Drimusf2196d82022-01-03 12:11:18 +01004459status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4460 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004461 if (mEffects.isNonOffloadableEffectEnabled()) {
4462 return OK;
4463 }
jiabinf1c73972022-04-14 16:28:52 -07004464 DeviceVector devices;
4465 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004466 if (status != OK) {
4467 return status;
4468 }
4469 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4470 if (devices.empty()) {
4471 return OK; // no output devices for the attributes
4472 }
jiabinf1c73972022-04-14 16:28:52 -07004473 return getProfilesForDevices(devices, audioProfilesVector,
4474 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004475}
4476
jiabina84c3d32022-12-02 18:59:55 +00004477status_t AudioPolicyManager::getSupportedMixerAttributes(
4478 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4479 ALOGV("%s, portId=%d", __func__, portId);
4480 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4481 if (deviceDescriptor == nullptr) {
4482 ALOGE("%s the requested device is currently unavailable", __func__);
4483 return BAD_VALUE;
4484 }
jiabin96daffc2023-05-11 17:51:55 +00004485 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4486 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4487 deviceDescriptor->type());
4488 return BAD_VALUE;
4489 }
jiabina84c3d32022-12-02 18:59:55 +00004490 for (const auto& hwModule : mHwModules) {
4491 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4492 if (curProfile->supportsDevice(deviceDescriptor)) {
4493 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4494 }
4495 }
4496 }
4497 return NO_ERROR;
4498}
4499
4500status_t AudioPolicyManager::setPreferredMixerAttributes(
4501 const audio_attributes_t *attr,
4502 audio_port_handle_t portId,
4503 uid_t uid,
4504 const audio_mixer_attributes_t *mixerAttributes) {
4505 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4506 "mixerBehavior=%d}, uid=%d, portId=%u",
4507 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4508 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4509 mixerAttributes->mixer_behavior, uid, portId);
4510 if (attr->usage != AUDIO_USAGE_MEDIA) {
4511 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4512 return BAD_VALUE;
4513 }
4514 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4515 if (deviceDescriptor == nullptr) {
4516 ALOGE("%s the requested device is currently unavailable", __func__);
4517 return BAD_VALUE;
4518 }
4519 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4520 ALOGE("%s(%d), type=%d, is not a usb output device",
4521 __func__, portId, deviceDescriptor->type());
4522 return BAD_VALUE;
4523 }
4524
4525 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4526 audio_flags_to_audio_output_flags(attr->flags, &flags);
4527 flags = (audio_output_flags_t) (flags |
4528 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4529 sp<IOProfile> profile = nullptr;
4530 DeviceVector devices(deviceDescriptor);
4531 for (const auto& hwModule : mHwModules) {
4532 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4533 if (curProfile->hasDynamicAudioProfile()
4534 && curProfile->isCompatibleProfile(devices,
4535 mixerAttributes->config.sample_rate,
4536 nullptr /*updatedSamplingRate*/,
4537 mixerAttributes->config.format,
4538 nullptr /*updatedFormat*/,
4539 mixerAttributes->config.channel_mask,
4540 nullptr /*updatedChannelMask*/,
4541 flags,
4542 false /*exactMatchRequiredForInputFlags*/)) {
4543 profile = curProfile;
4544 break;
4545 }
4546 }
4547 }
4548 if (profile == nullptr) {
4549 ALOGE("%s, there is no compatible profile found", __func__);
4550 return BAD_VALUE;
4551 }
4552
4553 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4554 sp<PreferredMixerAttributesInfo>::make(
4555 uid, portId, profile, flags, *mixerAttributes);
4556 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4557 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4558
4559 // If 1) there is any client from the preferred mixer configuration owner that is currently
4560 // active and matches the strategy and 2) current output is on the preferred device and the
4561 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4562 // configuration.
4563 std::vector<audio_io_handle_t> outputsToReopen;
4564 for (size_t i = 0; i < mOutputs.size(); i++) {
4565 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004566 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4567 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4568 output->mUsePreferredMixerAttributes = true;
4569 } else {
4570 for (const auto &client: output->getActiveClients()) {
4571 if (client->uid() == uid && client->strategy() == strategy) {
4572 client->setIsInvalid();
4573 outputsToReopen.push_back(output->mIoHandle);
4574 }
jiabina84c3d32022-12-02 18:59:55 +00004575 }
4576 }
4577 }
4578 }
4579 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4580 config.sample_rate = mixerAttributes->config.sample_rate;
4581 config.channel_mask = mixerAttributes->config.channel_mask;
4582 config.format = mixerAttributes->config.format;
4583 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004584 sp<SwAudioOutputDescriptor> desc =
4585 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4586 if (desc == nullptr) {
4587 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4588 continue;
4589 }
4590 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004591 }
4592
4593 return NO_ERROR;
4594}
4595
4596sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004597 audio_port_handle_t devicePortId,
4598 product_strategy_t strategy,
4599 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004600 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4601 if (it == mPreferredMixerAttrInfos.end()) {
4602 return nullptr;
4603 }
jiabind9a58d32023-06-01 17:57:30 +00004604 if (activeBitPerfectPreferred) {
4605 for (auto [strategy, info] : it->second) {
4606 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4607 && info->getActiveClientCount() != 0) {
4608 return info;
4609 }
4610 }
jiabina84c3d32022-12-02 18:59:55 +00004611 }
jiabind9a58d32023-06-01 17:57:30 +00004612 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4613 return strategyMatchedMixerAttrInfoIt == it->second.end()
4614 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004615}
4616
4617status_t AudioPolicyManager::getPreferredMixerAttributes(
4618 const audio_attributes_t *attr,
4619 audio_port_handle_t portId,
4620 audio_mixer_attributes_t* mixerAttributes) {
4621 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4622 portId, mEngine->getProductStrategyForAttributes(*attr));
4623 if (info == nullptr) {
4624 return NAME_NOT_FOUND;
4625 }
4626 *mixerAttributes = info->getMixerAttributes();
4627 return NO_ERROR;
4628}
4629
4630status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4631 audio_port_handle_t portId,
4632 uid_t uid) {
4633 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4634 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4635 if (preferredMixerAttrInfo == nullptr) {
4636 return NAME_NOT_FOUND;
4637 }
4638 if (preferredMixerAttrInfo->getUid() != uid) {
4639 ALOGE("%s, requested uid=%d, owned uid=%d",
4640 __func__, uid, preferredMixerAttrInfo->getUid());
4641 return PERMISSION_DENIED;
4642 }
4643 mPreferredMixerAttrInfos[portId].erase(strategy);
4644 if (mPreferredMixerAttrInfos[portId].empty()) {
4645 mPreferredMixerAttrInfos.erase(portId);
4646 }
4647
4648 // Reconfig existing output
4649 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4650 for (size_t i = 0; i < mOutputs.size(); i++) {
4651 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4652 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4653 }
4654 }
4655 for (const auto output : potentialOutputsToReopen) {
4656 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4657 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4658 preferredMixerAttrInfo->getFlags())) {
4659 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4660 }
4661 }
4662 return NO_ERROR;
4663}
4664
Eric Laurent6a94d692014-05-20 11:18:06 -07004665status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4666 audio_port_type_t type,
4667 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004668 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004669 unsigned int *generation)
4670{
jiabin19cdba52020-11-24 11:28:58 -08004671 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4672 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004673 return BAD_VALUE;
4674 }
4675 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004676 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004677 *num_ports = 0;
4678 }
4679
4680 size_t portsWritten = 0;
4681 size_t portsMax = *num_ports;
4682 *num_ports = 0;
4683 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004684 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4685 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004686 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004687 for (const auto& dev : mAvailableOutputDevices) {
4688 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004689 continue;
4690 }
4691 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004692 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004693 }
4694 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004695 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004696 }
4697 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004698 for (const auto& dev : mAvailableInputDevices) {
4699 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004700 continue;
4701 }
4702 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004703 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004704 }
4705 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004706 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004707 }
4708 }
4709 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4710 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4711 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4712 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4713 }
4714 *num_ports += mInputs.size();
4715 }
4716 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004717 size_t numOutputs = 0;
4718 for (size_t i = 0; i < mOutputs.size(); i++) {
4719 if (!mOutputs[i]->isDuplicated()) {
4720 numOutputs++;
4721 if (portsWritten < portsMax) {
4722 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4723 }
4724 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004725 }
Eric Laurent84c70242014-06-23 08:46:27 -07004726 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004727 }
4728 }
jiabina84c3d32022-12-02 18:59:55 +00004729
Eric Laurent6a94d692014-05-20 11:18:06 -07004730 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004731 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 return NO_ERROR;
4733}
4734
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004735status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4736 std::vector<media::AudioPortFw>* _aidl_return) {
4737 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4738 audio_port_v7 port;
4739 dev->toAudioPort(&port);
4740 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4741 _aidl_return->push_back(std::move(aidlPort));
4742 return OK;
4743 };
4744
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004745 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004746 for (const auto& dev : module->getDeclaredDevices()) {
4747 if (role == media::AudioPortRole::NONE ||
4748 ((role == media::AudioPortRole::SOURCE)
4749 == audio_is_input_device(dev->type()))) {
4750 RETURN_STATUS_IF_ERROR(pushPort(dev));
4751 }
4752 }
4753 }
4754 return OK;
4755}
4756
jiabin19cdba52020-11-24 11:28:58 -08004757status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004758{
Eric Laurent99fcae42018-05-17 16:59:18 -07004759 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4760 return BAD_VALUE;
4761 }
4762 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4763 if (dev != 0) {
4764 dev->toAudioPort(port);
4765 return NO_ERROR;
4766 }
4767 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4768 if (dev != 0) {
4769 dev->toAudioPort(port);
4770 return NO_ERROR;
4771 }
4772 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4773 if (out != 0) {
4774 out->toAudioPort(port);
4775 return NO_ERROR;
4776 }
4777 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4778 if (in != 0) {
4779 in->toAudioPort(port);
4780 return NO_ERROR;
4781 }
4782 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004783}
4784
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004785status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4786 audio_patch_handle_t *handle,
4787 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004788{
François Gaffieafd4cea2019-11-18 15:50:22 +01004789 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 if (handle == NULL || patch == NULL) {
4791 return BAD_VALUE;
4792 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004793 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004794 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004795 return BAD_VALUE;
4796 }
4797 // only one source per audio patch supported for now
4798 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004799 return INVALID_OPERATION;
4800 }
Eric Laurent874c42872014-08-08 15:13:39 -07004801 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004802 return INVALID_OPERATION;
4803 }
Eric Laurent874c42872014-08-08 15:13:39 -07004804 for (size_t i = 0; i < patch->num_sinks; i++) {
4805 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4806 return INVALID_OPERATION;
4807 }
4808 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004809
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004810 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4811 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4812 if (srcDevice == nullptr || sinkDevice == nullptr) {
4813 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4814 return BAD_VALUE;
4815 }
4816 ALOGV("%s between source %s and sink %s", __func__,
4817 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4818 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4819 // Default attributes, default volume priority, not to infer with non raw audio patches.
4820 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4821 const struct audio_port_config *source = &patch->sources[0];
4822 sp<SourceClientDescriptor> sourceDesc =
4823 new InternalSourceClientDescriptor(
4824 portId, uid, attributes, *source, srcDevice, sinkDevice,
4825 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4826
4827 status_t status =
4828 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4829
4830 if (status != NO_ERROR) {
4831 return INVALID_OPERATION;
4832 }
4833 mAudioSources.add(portId, sourceDesc);
4834 return NO_ERROR;
4835}
4836
4837status_t AudioPolicyManager::connectAudioSourceToSink(
4838 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4839 const struct audio_patch *patch,
4840 audio_patch_handle_t &handle,
4841 uid_t uid, uint32_t delayMs)
4842{
4843 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4844 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4845 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4846 return INVALID_OPERATION;
4847 }
4848 sourceDesc->connect(handle, sinkDevice);
4849 if (isMsdPatch(handle)) {
4850 return NO_ERROR;
4851 }
4852 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4853 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4854 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4855 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4856 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4857 goto FailurePatchAdded;
4858 }
4859 status = swOutput->start();
4860 if (status != NO_ERROR) {
4861 goto FailureSourceAdded;
4862 }
4863 swOutput->addClient(sourceDesc);
4864 status = startSource(swOutput, sourceDesc, &delayMs);
4865 if (status != NO_ERROR) {
4866 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4867 goto FailureSourceActive;
4868 }
4869 if (delayMs != 0) {
4870 usleep(delayMs * 1000);
4871 }
4872 return NO_ERROR;
4873
4874FailureSourceActive:
4875 swOutput->stop();
4876 releaseOutput(sourceDesc->portId());
4877FailureSourceAdded:
4878 sourceDesc->setSwOutput(nullptr);
4879FailurePatchAdded:
4880 releaseAudioPatchInternal(handle);
4881 return INVALID_OPERATION;
4882}
4883
4884status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4885 audio_patch_handle_t *handle,
4886 uid_t uid, uint32_t delayMs,
4887 const sp<SourceClientDescriptor>& sourceDesc)
4888{
4889 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004890 sp<AudioPatch> patchDesc;
4891 ssize_t index = mAudioPatches.indexOfKey(*handle);
4892
François Gaffieafd4cea2019-11-18 15:50:22 +01004893 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4894 patch->sources[0].role,
4895 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004896#if LOG_NDEBUG == 0
4897 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004898 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4899 patch->sinks[i].role,
4900 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004901 }
4902#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004903
4904 if (index >= 0) {
4905 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004906 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4907 __func__, mUidCached, patchDesc->getUid(), uid);
4908 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004909 return INVALID_OPERATION;
4910 }
4911 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004912 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004913 }
4914
4915 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004916 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004917 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004918 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004919 return BAD_VALUE;
4920 }
Eric Laurent84c70242014-06-23 08:46:27 -07004921 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4922 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004923 if (patchDesc != 0) {
4924 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004925 ALOGV("%s source id differs for patch current id %d new id %d",
4926 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004927 return BAD_VALUE;
4928 }
4929 }
Eric Laurent874c42872014-08-08 15:13:39 -07004930 DeviceVector devices;
4931 for (size_t i = 0; i < patch->num_sinks; i++) {
4932 // Only support mix to devices connection
4933 // TODO add support for mix to mix connection
4934 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004935 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004936 return INVALID_OPERATION;
4937 }
4938 sp<DeviceDescriptor> devDesc =
4939 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4940 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004941 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004942 return BAD_VALUE;
4943 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004944
François Gaffie11d30102018-11-02 16:09:09 +01004945 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004946 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004947 NULL, // updatedSamplingRate
4948 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004949 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004950 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004951 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004952 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004953 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004954 return INVALID_OPERATION;
4955 }
4956 devices.add(devDesc);
4957 }
4958 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004959 return INVALID_OPERATION;
4960 }
Eric Laurent874c42872014-08-08 15:13:39 -07004961
Eric Laurent6a94d692014-05-20 11:18:06 -07004962 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004963 ALOGV("%s setting device %s on output %d",
4964 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304965 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004966 index = mAudioPatches.indexOfKey(*handle);
4967 if (index >= 0) {
4968 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004969 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004970 }
4971 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004972 patchDesc->setUid(uid);
4973 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004974 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004975 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004976 return INVALID_OPERATION;
4977 }
4978 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4979 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4980 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004981 // only one sink supported when connecting an input device to a mix
4982 if (patch->num_sinks > 1) {
4983 return INVALID_OPERATION;
4984 }
François Gaffie53615e22015-03-19 09:24:12 +01004985 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 if (inputDesc == NULL) {
4987 return BAD_VALUE;
4988 }
4989 if (patchDesc != 0) {
4990 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4991 return BAD_VALUE;
4992 }
4993 }
François Gaffie11d30102018-11-02 16:09:09 +01004994 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004995 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004996 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004997 return BAD_VALUE;
4998 }
4999
François Gaffie11d30102018-11-02 16:09:09 +01005000 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005001 patch->sinks[0].sample_rate,
5002 NULL, /*updatedSampleRate*/
5003 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005004 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005005 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005006 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005007 // FIXME for the parameter type,
5008 // and the NONE
5009 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005010 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 return INVALID_OPERATION;
5012 }
5013 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005014 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005015 device->toString().c_str(), inputDesc->mIoHandle);
5016 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005017 index = mAudioPatches.indexOfKey(*handle);
5018 if (index >= 0) {
5019 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005020 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 }
5022 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005023 patchDesc->setUid(uid);
5024 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005025 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005026 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 return INVALID_OPERATION;
5028 }
5029 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5030 // device to device connection
5031 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005032 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005033 return BAD_VALUE;
5034 }
5035 }
François Gaffie11d30102018-11-02 16:09:09 +01005036 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005037 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005038 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005039 return BAD_VALUE;
5040 }
Eric Laurent874c42872014-08-08 15:13:39 -07005041
Eric Laurent6a94d692014-05-20 11:18:06 -07005042 //update source and sink with our own data as the data passed in the patch may
5043 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005044 PatchBuilder patchBuilder;
5045 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005046
5047 // if first sink is to MSD, establish single MSD patch
5048 if (getMsdAudioOutDevices().contains(
5049 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5050 ALOGV("%s patching to MSD", __FUNCTION__);
5051 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5052 goto installPatch;
5053 }
5054
François Gaffieafd4cea2019-11-18 15:50:22 +01005055 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5056 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005057
Eric Laurent874c42872014-08-08 15:13:39 -07005058 for (size_t i = 0; i < patch->num_sinks; i++) {
5059 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005060 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005061 return INVALID_OPERATION;
5062 }
François Gaffie11d30102018-11-02 16:09:09 +01005063 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005064 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005065 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005066 return BAD_VALUE;
5067 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005068 audio_port_config sinkPortConfig = {};
5069 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5070 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005071
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005072 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5073 // volume management purpose (tracking activity)
5074 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5075 // in config XML to reach the sink so that is can be declared as available.
5076 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005077 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005078 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005079 // take care of dynamic routing for SwOutput selection,
5080 audio_attributes_t attributes = sourceDesc->attributes();
5081 audio_stream_type_t stream = sourceDesc->stream();
5082 audio_attributes_t resultAttr;
5083 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5084 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005085 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5086 config.channel_mask =
5087 (audio_channel_mask_get_representation(sourceMask)
5088 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5089 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005090 config.format = sourceDesc->config().format;
5091 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5092 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5093 bool isRequestedDeviceForExclusiveUse = false;
5094 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005095 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005096 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005097 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5098 &stream, sourceDesc->uid(), &config, &flags,
5099 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005100 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005101 if (output == AUDIO_IO_HANDLE_NONE) {
5102 ALOGV("%s no output for device %s",
5103 __FUNCTION__, sinkDevice->toString().c_str());
5104 return INVALID_OPERATION;
5105 }
5106 outputDesc = mOutputs.valueFor(output);
5107 if (outputDesc->isDuplicated()) {
5108 ALOGE("%s output is duplicated", __func__);
5109 return INVALID_OPERATION;
5110 }
François Gaffie7e39df22022-04-26 12:48:49 +02005111 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5112 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005113 } else {
5114 // Same for "raw patches" aka created from createAudioPatch API
5115 SortedVector<audio_io_handle_t> outputs =
5116 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5117 // if the sink device is reachable via an opened output stream, request to
5118 // go via this output stream by adding a second source to the patch
5119 // description
5120 output = selectOutput(outputs);
5121 if (output == AUDIO_IO_HANDLE_NONE) {
5122 ALOGE("%s no output available for internal patch sink", __func__);
5123 return INVALID_OPERATION;
5124 }
5125 outputDesc = mOutputs.valueFor(output);
5126 if (outputDesc->isDuplicated()) {
5127 ALOGV("%s output for device %s is duplicated",
5128 __func__, sinkDevice->toString().c_str());
5129 return INVALID_OPERATION;
5130 }
François Gaffie7e39df22022-04-26 12:48:49 +02005131 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005132 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005133 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005134 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005135 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005136 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005137 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5138 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005139 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5140 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005141 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005142 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005143 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005144 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005145 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005146 return INVALID_OPERATION;
5147 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005148 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005149 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005150 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005151 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005152 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005153 srcMixPortConfig.ext.mix.usecase.stream =
5154 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005155 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5156 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005157 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005158 }
Eric Laurent83b88082014-06-20 18:31:16 -07005159 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005160 }
5161 // TODO: check from routing capabilities in config file and other conflicting patches
5162
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005163installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005164 status_t status = installPatch(
5165 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005166 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005167 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005168 return INVALID_OPERATION;
5169 }
5170 } else {
5171 return BAD_VALUE;
5172 }
5173 } else {
5174 return BAD_VALUE;
5175 }
5176 return NO_ERROR;
5177}
5178
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005179status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005180{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005181 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005182 ssize_t index = mAudioPatches.indexOfKey(handle);
5183
5184 if (index < 0) {
5185 return BAD_VALUE;
5186 }
5187 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005188 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5189 __func__, mUidCached, patchDesc->getUid(), uid);
5190 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 return INVALID_OPERATION;
5192 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005193 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5194 for (size_t i = 0; i < mAudioSources.size(); i++) {
5195 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5196 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5197 portId = sourceDesc->portId();
5198 break;
5199 }
5200 }
5201 return portId != AUDIO_PORT_HANDLE_NONE ?
5202 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005203}
Eric Laurent6a94d692014-05-20 11:18:06 -07005204
François Gaffieafd4cea2019-11-18 15:50:22 +01005205status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005206 uint32_t delayMs,
5207 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005208{
5209 ALOGV("%s patch %d", __func__, handle);
5210 if (mAudioPatches.indexOfKey(handle) < 0) {
5211 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5212 return BAD_VALUE;
5213 }
5214 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005216 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005218 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005219 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005220 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005221 return BAD_VALUE;
5222 }
5223
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305224 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005225 getNewOutputDevices(outputDesc, true /*fromCache*/),
5226 true,
5227 0,
5228 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005229 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5230 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005231 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005232 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005233 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005234 return BAD_VALUE;
5235 }
5236 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005237 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005238 true,
5239 NULL);
5240 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005241 status_t status =
5242 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5243 ALOGV("%s patch panel returned %d patchHandle %d",
5244 __func__, status, patchDesc->getAfHandle());
5245 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005246 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005247 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005248 // SW or HW Bridge
5249 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5250 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005251 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005252 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5253 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5254 outputDesc = sourceDesc->swOutput().promote();
5255 }
5256 if (outputDesc == nullptr) {
5257 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5258 // releaseOutput has already called closeOutput in case of direct output
5259 return NO_ERROR;
5260 }
François Gaffie7e39df22022-04-26 12:48:49 +02005261 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005262 // While using a HwBridge, force reconsidering device only if not reusing an existing
5263 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005264 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005265 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5266 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5267 // Reconsider device only for cases:
5268 // 1 / Active Output
5269 // 2 / Inactive Output previously hosting HwBridge
5270 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5271 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5272 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305273 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005274 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5275 outputDesc->devices(),
5276 force,
5277 0,
5278 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 } else {
5280 return BAD_VALUE;
5281 }
5282 } else {
5283 return BAD_VALUE;
5284 }
5285 return NO_ERROR;
5286}
5287
5288status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5289 struct audio_patch *patches,
5290 unsigned int *generation)
5291{
François Gaffie53615e22015-03-19 09:24:12 +01005292 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005293 return BAD_VALUE;
5294 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005295 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005296 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005297}
5298
Eric Laurente1715a42014-05-20 11:30:42 -07005299status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005300{
Eric Laurente1715a42014-05-20 11:30:42 -07005301 ALOGV("setAudioPortConfig()");
5302
5303 if (config == NULL) {
5304 return BAD_VALUE;
5305 }
5306 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5307 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005308 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5309 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005310 }
5311
Eric Laurenta121f902014-06-03 13:32:54 -07005312 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005313 if (config->type == AUDIO_PORT_TYPE_MIX) {
5314 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005315 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005316 if (outputDesc == NULL) {
5317 return BAD_VALUE;
5318 }
Eric Laurent84c70242014-06-23 08:46:27 -07005319 ALOG_ASSERT(!outputDesc->isDuplicated(),
5320 "setAudioPortConfig() called on duplicated output %d",
5321 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005322 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005323 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005324 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005325 if (inputDesc == NULL) {
5326 return BAD_VALUE;
5327 }
Eric Laurenta121f902014-06-03 13:32:54 -07005328 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005329 } else {
5330 return BAD_VALUE;
5331 }
5332 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5333 sp<DeviceDescriptor> deviceDesc;
5334 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5335 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5336 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5337 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5338 } else {
5339 return BAD_VALUE;
5340 }
5341 if (deviceDesc == NULL) {
5342 return BAD_VALUE;
5343 }
Eric Laurenta121f902014-06-03 13:32:54 -07005344 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005345 } else {
5346 return BAD_VALUE;
5347 }
5348
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005349 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005350 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5351 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005352 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005353 audioPortConfig->toAudioPortConfig(&newConfig, config);
5354 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005355 }
Eric Laurenta121f902014-06-03 13:32:54 -07005356 if (status != NO_ERROR) {
5357 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005358 }
Eric Laurente1715a42014-05-20 11:30:42 -07005359
5360 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005361}
5362
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005363void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5364{
Eric Laurentd60560a2015-04-10 11:31:20 -07005365 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005366 clearAudioPatches(uid);
5367 clearSessionRoutes(uid);
5368}
5369
Eric Laurent6a94d692014-05-20 11:18:06 -07005370void AudioPolicyManager::clearAudioPatches(uid_t uid)
5371{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005372 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005373 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005374 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005375 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005376 }
5377 }
5378}
5379
François Gaffiec005e562018-11-06 15:04:49 +01005380void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005381{
François Gaffiec005e562018-11-06 15:04:49 +01005382 // Take the first attributes following the product strategy as it is used to retrieve the routed
5383 // device. All attributes wihin a strategy follows the same "routing strategy"
5384 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5385 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005386 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005387 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005388 for (size_t j = 0; j < mOutputs.size(); j++) {
5389 if (mOutputs.keyAt(j) == ouptutToSkip) {
5390 continue;
5391 }
5392 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005393 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005394 continue;
5395 }
5396 // If the default device for this strategy is on another output mix,
5397 // invalidate all tracks in this strategy to force re connection.
5398 // Otherwise select new device on the output mix.
5399 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005400 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005401 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005402 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5403 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5404 // If the device is using preferred mixer attributes, the output need to reopen
5405 // with default configuration when the new selected devices are different from
5406 // current routing devices.
5407 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5408 continue;
5409 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305410 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005411 }
5412 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005413 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005414}
5415
5416void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5417{
5418 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005419 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005420 for (size_t i = 0; i < mOutputs.size(); i++) {
5421 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005422 for (const auto& client : outputDesc->getClientIterable()) {
5423 if (client->hasPreferredDevice() && client->uid() == uid) {
5424 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005425 auto clientStrategy = client->strategy();
5426 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5427 end(affectedStrategies)) {
5428 continue;
5429 }
5430 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005431 }
5432 }
5433 }
5434 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005435 for (const auto& strategy : affectedStrategies) {
5436 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005437 }
5438
5439 // remove input routes associated with this uid
5440 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005441 for (size_t i = 0; i < mInputs.size(); i++) {
5442 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005443 for (const auto& client : inputDesc->getClientIterable()) {
5444 if (client->hasPreferredDevice() && client->uid() == uid) {
5445 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5446 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005447 }
5448 }
5449 }
5450 // reroute inputs if necessary
5451 SortedVector<audio_io_handle_t> inputsToClose;
5452 for (size_t i = 0; i < mInputs.size(); i++) {
5453 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005454 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005455 inputsToClose.add(inputDesc->mIoHandle);
5456 }
5457 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005458 for (const auto& input : inputsToClose) {
5459 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005460 }
5461}
5462
Eric Laurentd60560a2015-04-10 11:31:20 -07005463void AudioPolicyManager::clearAudioSources(uid_t uid)
5464{
5465 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005466 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5467 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005468 stopAudioSource(mAudioSources.keyAt(i));
5469 }
5470 }
5471}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005472
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005473status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5474 audio_io_handle_t *ioHandle,
5475 audio_devices_t *device)
5476{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005477 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5478 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005479 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005480 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5481 if (deviceDesc == nullptr) {
5482 return INVALID_OPERATION;
5483 }
5484 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005485
François Gaffiedf372692015-03-19 10:43:27 +01005486 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005487}
5488
Eric Laurentd60560a2015-04-10 11:31:20 -07005489status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005490 const audio_attributes_t *attributes,
5491 audio_port_handle_t *portId,
5492 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005493{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005494 ALOGV("%s", __FUNCTION__);
5495 *portId = AUDIO_PORT_HANDLE_NONE;
5496
5497 if (source == NULL || attributes == NULL || portId == NULL) {
5498 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5499 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005500 return BAD_VALUE;
5501 }
5502
Eric Laurentd60560a2015-04-10 11:31:20 -07005503 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5504 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005505 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5506 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005507 return INVALID_OPERATION;
5508 }
5509
François Gaffie11d30102018-11-02 16:09:09 +01005510 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005511 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005512 String8(source->ext.device.address),
5513 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005514 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005515 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005516 return BAD_VALUE;
5517 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005518
jiabin4ef93452019-09-10 14:29:54 -07005519 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005520
François Gaffieaaac0fd2018-11-22 17:56:39 +01005521 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005522 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005523 mEngine->getStreamTypeForAttributes(*attributes),
5524 mEngine->getProductStrategyForAttributes(*attributes),
5525 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005526
5527 status_t status = connectAudioSource(sourceDesc);
5528 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005529 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005530 }
5531 return status;
5532}
5533
Francois Gaffie601801d2021-06-22 13:27:39 +02005534sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5535 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5536{
5537 ALOGV("%s", __FUNCTION__);
5538 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5539
5540 status_t status = startAudioSource(source, attributes, &portId, uid);
5541 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5542 return mAudioSources.valueFor(portId);
5543}
5544
5545
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005546status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005547{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005548 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005549
5550 // make sure we only have one patch per source.
5551 disconnectAudioSource(sourceDesc);
5552
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005553 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005554 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5555 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5556 sourceDesc->srcDevice()->type(),
5557 String8(sourceDesc->srcDevice()->address().c_str()),
5558 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005559 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005560 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005561 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005562 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005563 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5564 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5565 return INVALID_OPERATION;
5566 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005567 PatchBuilder patchBuilder;
5568 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5569 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005570
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005571 return connectAudioSourceToSink(
5572 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005573}
5574
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005575status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005576{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005577 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5578 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005579 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005580 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005581 return BAD_VALUE;
5582 }
5583 status_t status = disconnectAudioSource(sourceDesc);
5584
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005585 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005586 return status;
5587}
5588
Andy Hung2ddee192015-12-18 17:34:44 -08005589status_t AudioPolicyManager::setMasterMono(bool mono)
5590{
5591 if (mMasterMono == mono) {
5592 return NO_ERROR;
5593 }
5594 mMasterMono = mono;
5595 // if enabling mono we close all offloaded devices, which will invalidate the
5596 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5597 // for recreating the new AudioTrack as non-offloaded PCM.
5598 //
5599 // If disabling mono, we leave all tracks as is: we don't know which clients
5600 // and tracks are able to be recreated as offloaded. The next "song" should
5601 // play back offloaded.
5602 if (mMasterMono) {
5603 Vector<audio_io_handle_t> offloaded;
5604 for (size_t i = 0; i < mOutputs.size(); ++i) {
5605 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5606 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5607 offloaded.push(desc->mIoHandle);
5608 }
5609 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005610 for (const auto& handle : offloaded) {
5611 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005612 }
5613 }
5614 // update master mono for all remaining outputs
5615 for (size_t i = 0; i < mOutputs.size(); ++i) {
5616 updateMono(mOutputs.keyAt(i));
5617 }
5618 return NO_ERROR;
5619}
5620
5621status_t AudioPolicyManager::getMasterMono(bool *mono)
5622{
5623 *mono = mMasterMono;
5624 return NO_ERROR;
5625}
5626
Eric Laurentac9cef52017-06-09 15:46:26 -07005627float AudioPolicyManager::getStreamVolumeDB(
5628 audio_stream_type_t stream, int index, audio_devices_t device)
5629{
jiabin9a3361e2019-10-01 09:38:30 -07005630 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005631}
5632
jiabin81772902018-04-02 17:52:27 -07005633status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5634 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005635 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005636{
Kriti Dang6537def2021-03-02 13:46:59 +01005637 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5638 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005639 return BAD_VALUE;
5640 }
Kriti Dang6537def2021-03-02 13:46:59 +01005641 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5642 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005643
5644 size_t formatsWritten = 0;
5645 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005646
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005647 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005648 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5649 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005650 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005651 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005652 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005653 bool formatEnabled = true;
5654 switch (forceUse) {
5655 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005656 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005657 break;
5658 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5659 formatEnabled = false;
5660 break;
5661 default: // AUTO or ALWAYS => true
5662 break;
jiabin81772902018-04-02 17:52:27 -07005663 }
5664 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5665 }
jiabin81772902018-04-02 17:52:27 -07005666 }
5667 return NO_ERROR;
5668}
5669
Kriti Dang6537def2021-03-02 13:46:59 +01005670status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5671 audio_format_t *surroundFormats) {
5672 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5673 return BAD_VALUE;
5674 }
5675 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5676 __func__, *numSurroundFormats, surroundFormats);
5677
5678 size_t formatsWritten = 0;
5679 size_t formatsMax = *numSurroundFormats;
5680 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5681
5682 // Return formats from all device profiles that have already been resolved by
5683 // checkOutputsForDevice().
5684 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5685 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5686 audio_devices_t deviceType = device->type();
5687 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5688 // returns formats reported by HDMI devices.
5689 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5690 continue;
5691 }
5692 // Formats reported by sink devices
5693 std::unordered_set<audio_format_t> formatset;
5694 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5695 formatset.insert(it->second.begin(), it->second.end());
5696 }
5697
5698 // Formats hard-coded in the in policy configuration file (if any).
5699 FormatVector encodedFormats = device->encodedFormats();
5700 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5701 // Filter the formats which are supported by the vendor hardware.
5702 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005703 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005704 formats.insert(*it);
5705 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005706 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005707 if (pair.second.count(*it) != 0) {
5708 formats.insert(pair.first);
5709 break;
5710 }
5711 }
5712 }
5713 }
5714 }
5715 *numSurroundFormats = formats.size();
5716 for (const auto& format: formats) {
5717 if (formatsWritten < formatsMax) {
5718 surroundFormats[formatsWritten++] = format;
5719 }
5720 }
5721 return NO_ERROR;
5722}
5723
jiabin81772902018-04-02 17:52:27 -07005724status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5725{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005726 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005727 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5728 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005729 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005730 return BAD_VALUE;
5731 }
5732
Mikhail Naganov100f0122018-11-29 11:22:16 -08005733 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5734 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005735 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005736 return INVALID_OPERATION;
5737 }
5738
Mikhail Naganov100f0122018-11-29 11:22:16 -08005739 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005740 return NO_ERROR;
5741 }
5742
Mikhail Naganov100f0122018-11-29 11:22:16 -08005743 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005744 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005745 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005746 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005747 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005748 }
5749 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005750 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005751 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005752 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005753 }
5754 }
5755
5756 sp<SwAudioOutputDescriptor> outputDesc;
5757 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005758 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5759 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005760 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5761 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005762 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005763 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005764 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5765 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5766 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005767 name.c_str(),
5768 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005769 if (status != NO_ERROR) {
5770 continue;
5771 }
5772 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5773 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5774 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005775 name.c_str(),
5776 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005777 profileUpdated |= (status == NO_ERROR);
5778 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005779 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005780 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005781 AUDIO_DEVICE_IN_HDMI);
5782 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5783 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005784 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005785 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005786 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5787 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5788 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005789 name.c_str(),
5790 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005791 if (status != NO_ERROR) {
5792 continue;
5793 }
5794 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5795 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5796 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005797 name.c_str(),
5798 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005799 profileUpdated |= (status == NO_ERROR);
5800 }
5801
jiabin81772902018-04-02 17:52:27 -07005802 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005803 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005804 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005805 }
5806
5807 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5808}
5809
Eric Laurent5ada82e2019-08-29 17:53:54 -07005810void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005811{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005812 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005813 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005814 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005815 }
5816}
5817
jiabin6012f912018-11-02 17:06:30 -07005818bool AudioPolicyManager::isHapticPlaybackSupported()
5819{
5820 for (const auto& hwModule : mHwModules) {
5821 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5822 for (const auto &outProfile : outputProfiles) {
5823 struct audio_port audioPort;
5824 outProfile->toAudioPort(&audioPort);
5825 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5826 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5827 return true;
5828 }
5829 }
5830 }
5831 }
5832 return false;
5833}
5834
Carter Hsu325a8eb2022-01-19 19:56:51 +08005835bool AudioPolicyManager::isUltrasoundSupported()
5836{
5837 bool hasUltrasoundOutput = false;
5838 bool hasUltrasoundInput = false;
5839 for (const auto& hwModule : mHwModules) {
5840 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5841 if (!hasUltrasoundOutput) {
5842 for (const auto &outProfile : outputProfiles) {
5843 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5844 hasUltrasoundOutput = true;
5845 break;
5846 }
5847 }
5848 }
5849
5850 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5851 if (!hasUltrasoundInput) {
5852 for (const auto &inputProfile : inputProfiles) {
5853 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5854 hasUltrasoundInput = true;
5855 break;
5856 }
5857 }
5858 }
5859
5860 if (hasUltrasoundOutput && hasUltrasoundInput)
5861 return true;
5862 }
5863 return false;
5864}
5865
Atneya Nair698f5ef2022-12-15 16:15:09 -08005866bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5867{
5868 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5869 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5870 for (const auto& hwModule : mHwModules) {
5871 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5872 for (const auto &inputProfile : inputProfiles) {
5873 if ((inputProfile->getFlags() & mask) == mask) {
5874 return true;
5875 }
5876 }
5877 }
5878 return false;
5879}
5880
Eric Laurent8340e672019-11-06 11:01:08 -08005881bool AudioPolicyManager::isCallScreenModeSupported()
5882{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005883 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005884}
5885
5886
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005887status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005888{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005889 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005890 if (!sourceDesc->isConnected()) {
5891 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5892 return NO_ERROR;
5893 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005894 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5895 if (swOutput != 0) {
5896 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005897 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005898 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005899 }
jiabinbce0c1d2020-10-05 11:20:18 -07005900 if (releaseOutput(sourceDesc->portId())) {
5901 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5902 // no need to release audio patch here but just return NO_ERROR.
5903 return NO_ERROR;
5904 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005905 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005906 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005907 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005908 // close Hwoutput and remove from mHwOutputs
5909 } else {
5910 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5911 }
5912 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005913 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005914 sourceDesc->disconnect();
5915 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005916}
5917
François Gaffiec005e562018-11-06 15:04:49 +01005918sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5919 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005920{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005921 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005922 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005923 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005924 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005925 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5926 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005927 source = sourceDesc;
5928 break;
5929 }
5930 }
5931 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005932}
5933
Eric Laurentb4f42a92022-01-17 17:37:31 +01005934bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005935 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005936 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005937{
5938 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5939 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005940 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005941 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005942 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5943 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5944 return false;
5945 }
5946 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5947 return false;
5948 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005949 }
5950
Eric Laurentd332bc82023-08-04 11:45:23 +02005951 // The caller can have the audio config criteria ignored by either passing a null ptr or
5952 // the AUDIO_CONFIG_INITIALIZER value.
5953 // If an audio config is specified, current policy is to only allow spatialization for
5954 // some positional channel masks and PCM format
5955
5956 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
5957 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
5958 return false;
5959 }
5960 if (!audio_is_linear_pcm(config->format)) {
5961 return false;
5962 }
5963 }
5964
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005965 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005966 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005967 if (profile == nullptr) {
5968 return false;
5969 }
5970
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005971 return true;
5972}
5973
5974void AudioPolicyManager::checkVirtualizerClientRoutes() {
5975 std::set<audio_stream_type_t> streamsToInvalidate;
5976 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005977 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5978 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005979 audio_attributes_t attr = client->attributes();
5980 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5981 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5982 audio_config_base_t clientConfig = client->config();
5983 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005984 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005985 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005986 streamsToInvalidate.insert(client->stream());
5987 }
5988 }
5989 }
5990
jiabinc44b3462022-12-08 12:52:31 -08005991 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005992}
5993
Eric Laurente191d1b2022-04-15 11:59:25 +02005994
5995bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5996 const sp<SwAudioOutputDescriptor>& outputDesc) {
5997 if (outputDesc->isDuplicated()) {
5998 return false;
5999 }
6000 DeviceVector devices = outputDesc->supportedDevices();
6001 for (size_t i = 0; i < mOutputs.size(); i++) {
6002 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6003 if (desc == outputDesc || desc->isDuplicated()) {
6004 continue;
6005 }
6006 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6007 if (!sharedDevices.isEmpty()
6008 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6009 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6010 return false;
6011 }
6012 }
6013 return true;
6014}
6015
6016
Eric Laurentfa0f6742021-08-17 18:39:44 +02006017status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006018 const audio_attributes_t *attr,
6019 audio_io_handle_t *output) {
6020 *output = AUDIO_IO_HANDLE_NONE;
6021
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006022 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6023 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6024 audio_config_t *configPtr = nullptr;
6025 audio_config_t config;
6026 if (mixerConfig != nullptr) {
6027 config = audio_config_initializer(mixerConfig);
6028 configPtr = &config;
6029 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006030 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006031 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006032 return BAD_VALUE;
6033 }
6034
6035 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006036 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006037 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006038 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006039 return BAD_VALUE;
6040 }
6041
Eric Laurente191d1b2022-04-15 11:59:25 +02006042 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006043 for (size_t i = 0; i < mOutputs.size(); i++) {
6044 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006045 if (!desc->isDuplicated()
6046 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6047 spatializerOutputs.push_back(desc);
6048 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006049 }
6050 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006051 mSpatializerOutput.clear();
6052 bool outputsChanged = false;
6053 for (const auto& desc : spatializerOutputs) {
6054 if (desc->mProfile == profile
6055 && (configPtr == nullptr
6056 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6057 mSpatializerOutput = desc;
6058 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6059 } else {
6060 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6061 " and devices %s", __func__, desc->mIoHandle,
6062 configPtr != nullptr ? configPtr->channel_mask : 0,
6063 devices.toString().c_str());
6064 closeOutput(desc->mIoHandle);
6065 outputsChanged = true;
6066 }
Eric Laurent39095982021-08-24 18:29:27 +02006067 }
6068
Eric Laurente191d1b2022-04-15 11:59:25 +02006069 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006070 sp<SwAudioOutputDescriptor> desc =
6071 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006072 if (desc != nullptr) {
6073 mSpatializerOutput = desc;
6074 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006075 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006076 }
6077
6078 checkVirtualizerClientRoutes();
6079
Eric Laurente191d1b2022-04-15 11:59:25 +02006080 if (outputsChanged) {
6081 mPreviousOutputs = mOutputs;
6082 mpClientInterface->onAudioPortListUpdate();
6083 }
6084
6085 if (mSpatializerOutput == nullptr) {
6086 ALOGV("%s could not open spatializer output with requested config", __func__);
6087 return BAD_VALUE;
6088 }
Eric Laurent39095982021-08-24 18:29:27 +02006089 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006090 ALOGV("%s returning new spatializer output %d", __func__, *output);
6091 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006092}
6093
Eric Laurentfa0f6742021-08-17 18:39:44 +02006094status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6095 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006096 return INVALID_OPERATION;
6097 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006098 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006099 return BAD_VALUE;
6100 }
Eric Laurent39095982021-08-24 18:29:27 +02006101
Eric Laurente191d1b2022-04-15 11:59:25 +02006102 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6103 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6104 closeOutput(mSpatializerOutput->mIoHandle);
6105 //from now on mSpatializerOutput is null
6106 checkVirtualizerClientRoutes();
6107 }
Eric Laurent39095982021-08-24 18:29:27 +02006108
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006109 return NO_ERROR;
6110}
6111
Eric Laurente552edb2014-03-10 17:42:56 -07006112// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006113// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006114// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006115uint32_t AudioPolicyManager::nextAudioPortGeneration()
6116{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006117 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006118}
6119
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006120AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006121 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006122 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006123 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006124 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006125 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006126 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006127 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006128 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006129 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006130 mAudioPortGeneration(1),
6131 mBeaconMuteRefCount(0),
6132 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006133 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006134 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006135 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006136 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006137{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006138}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006139
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006140status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006141 if (mEngine == nullptr) {
6142 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006143 }
6144 mEngine->setObserver(this);
6145 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006146 if (status != NO_ERROR) {
6147 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6148 return status;
6149 }
François Gaffie2110e042015-03-24 08:41:51 +01006150
jiabin29230182023-04-04 21:02:36 +00006151 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6152 // at the end of this function.
6153 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006154 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6155 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6156
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006157 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006158 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006159 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006160
Eric Laurent3a4311c2014-03-17 12:00:47 -07006161 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006162 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6163 defaultOutputDevice == nullptr ||
6164 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6165 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6166 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006167 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006168 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006169 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006170
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006171 // Silence ALOGV statements
6172 property_set("log.tag." LOG_TAG, "D");
6173
Eric Laurente552edb2014-03-10 17:42:56 -07006174 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006175 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006176}
6177
Eric Laurente0720872014-03-11 09:30:41 -07006178AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006179{
Eric Laurente552edb2014-03-10 17:42:56 -07006180 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006181 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006182 }
6183 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006184 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006185 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006186 mAvailableOutputDevices.clear();
6187 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006188 mOutputs.clear();
6189 mInputs.clear();
6190 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006191 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006192 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006193}
6194
Eric Laurente0720872014-03-11 09:30:41 -07006195status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006196{
Eric Laurent87ffa392015-05-22 10:32:38 -07006197 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006198}
6199
Eric Laurente552edb2014-03-10 17:42:56 -07006200// ---
6201
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006202void AudioPolicyManager::onNewAudioModulesAvailable()
6203{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006204 DeviceVector newDevices;
6205 onNewAudioModulesAvailableInt(&newDevices);
6206 if (!newDevices.empty()) {
6207 nextAudioPortGeneration();
6208 mpClientInterface->onAudioPortListUpdate();
6209 }
6210}
6211
6212void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6213{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006214 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006215 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6216 continue;
6217 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006218 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006219 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6220 handle != AUDIO_MODULE_HANDLE_NONE) {
6221 hwModule->setHandle(handle);
6222 } else {
6223 ALOGW("could not load HW module %s", hwModule->getName());
6224 continue;
6225 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006226 }
6227 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006228 // open all output streams needed to access attached devices.
6229 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006230 // This also validates mAvailableOutputDevices list
6231 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6232 if (!outProfile->canOpenNewIo()) {
6233 ALOGE("Invalid Output profile max open count %u for profile %s",
6234 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6235 continue;
6236 }
6237 if (!outProfile->hasSupportedDevices()) {
6238 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6239 continue;
6240 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006241 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6242 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006243 mTtsOutputAvailable = true;
6244 }
6245
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006246 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006247 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006248 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006249 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6250 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006251 } else {
6252 // choose first device present in profile's SupportedDevices also part of
6253 // mAvailableOutputDevices.
6254 if (availProfileDevices.isEmpty()) {
6255 continue;
6256 }
6257 supportedDevice = availProfileDevices.itemAt(0);
6258 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006259 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006260 continue;
6261 }
6262 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6263 mpClientInterface);
6264 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006265 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6266 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006267 AUDIO_STREAM_DEFAULT,
6268 AUDIO_OUTPUT_FLAG_NONE, &output);
6269 if (status != NO_ERROR) {
6270 ALOGW("Cannot open output stream for devices %s on hw module %s",
6271 supportedDevice->toString().c_str(), hwModule->getName());
6272 continue;
6273 }
6274 for (const auto &device : availProfileDevices) {
6275 // give a valid ID to an attached device once confirmed it is reachable
6276 if (!device->isAttached()) {
6277 device->attach(hwModule);
6278 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006279 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006280 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006281 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6282 }
6283 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006284 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006285 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6286 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006287 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006288 }
Eric Laurent39095982021-08-24 18:29:27 +02006289 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006290 outputDesc->close();
6291 } else {
6292 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306293 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006294 DeviceVector(supportedDevice),
6295 true,
6296 0,
6297 NULL);
6298 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006299 }
6300 // open input streams needed to access attached devices to validate
6301 // mAvailableInputDevices list
6302 for (const auto& inProfile : hwModule->getInputProfiles()) {
6303 if (!inProfile->canOpenNewIo()) {
6304 ALOGE("Invalid Input profile max open count %u for profile %s",
6305 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6306 continue;
6307 }
6308 if (!inProfile->hasSupportedDevices()) {
6309 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6310 continue;
6311 }
6312 // chose first device present in profile's SupportedDevices also part of
6313 // available input devices
6314 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006315 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006316 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006317 ALOGV("%s: Input device list is empty! for profile %s",
6318 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006319 continue;
6320 }
6321 sp<AudioInputDescriptor> inputDesc =
6322 new AudioInputDescriptor(inProfile, mpClientInterface);
6323
6324 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6325 status_t status = inputDesc->open(nullptr,
6326 availProfileDevices.itemAt(0),
6327 AUDIO_SOURCE_MIC,
6328 AUDIO_INPUT_FLAG_NONE,
6329 &input);
6330 if (status != NO_ERROR) {
6331 ALOGW("Cannot open input stream for device %s on hw module %s",
6332 availProfileDevices.toString().c_str(),
6333 hwModule->getName());
6334 continue;
6335 }
6336 for (const auto &device : availProfileDevices) {
6337 // give a valid ID to an attached device once confirmed it is reachable
6338 if (!device->isAttached()) {
6339 device->attach(hwModule);
6340 device->importAudioPortAndPickAudioProfile(inProfile, true);
6341 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006342 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006343 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6344 }
6345 }
6346 inputDesc->close();
6347 }
6348 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006349
6350 // Check if spatializer outputs can be closed until used.
6351 // mOutputs vector never contains duplicated outputs at this point.
6352 std::vector<audio_io_handle_t> outputsClosed;
6353 for (size_t i = 0; i < mOutputs.size(); i++) {
6354 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6355 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6356 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6357 outputsClosed.push_back(desc->mIoHandle);
6358 desc->close();
6359 }
6360 }
6361 for (auto output : outputsClosed) {
6362 removeOutput(output);
6363 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006364}
6365
Eric Laurent98e38192018-02-15 18:31:53 -08006366void AudioPolicyManager::addOutput(audio_io_handle_t output,
6367 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006368{
Eric Laurent1c333e22014-05-20 10:48:17 -07006369 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006370 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006371 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006372 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006373 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006374}
6375
François Gaffie53615e22015-03-19 09:24:12 +01006376void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6377{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006378 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6379 ALOGV("%s: removing primary output", __func__);
6380 mPrimaryOutput = nullptr;
6381 }
François Gaffie53615e22015-03-19 09:24:12 +01006382 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006383 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006384}
6385
Eric Laurent98e38192018-02-15 18:31:53 -08006386void AudioPolicyManager::addInput(audio_io_handle_t input,
6387 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006388{
Eric Laurent1c333e22014-05-20 10:48:17 -07006389 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006390 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006391}
Eric Laurente552edb2014-03-10 17:42:56 -07006392
François Gaffie11d30102018-11-02 16:09:09 +01006393status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006394 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006395 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006396{
François Gaffie11d30102018-11-02 16:09:09 +01006397 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006398 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006399 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006400
François Gaffie11d30102018-11-02 16:09:09 +01006401 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006402 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006403 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006404 }
Eric Laurente552edb2014-03-10 17:42:56 -07006405
Eric Laurent3b73df72014-03-11 09:06:29 -07006406 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006407 // first call getAudioPort to get the supported attributes from the HAL
6408 struct audio_port_v7 port = {};
6409 device->toAudioPort(&port);
6410 status_t status = mpClientInterface->getAudioPort(&port);
6411 if (status == NO_ERROR) {
6412 device->importAudioPort(port);
6413 }
6414
6415 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006416 for (size_t i = 0; i < mOutputs.size(); i++) {
6417 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006418 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006419 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006420 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6421 mOutputs.keyAt(i), device->toString().c_str());
6422 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006423 }
6424 }
6425 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006426 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006427 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006428 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6429 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006430 if (profile->supportsDevice(device)) {
6431 profiles.add(profile);
6432 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6433 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006434 }
6435 }
6436 }
6437
Eric Laurent7b279bb2015-12-14 10:18:23 -08006438 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006439
Eric Laurente552edb2014-03-10 17:42:56 -07006440 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006441 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006442 return BAD_VALUE;
6443 }
6444
6445 // open outputs for matching profiles if needed. Direct outputs are also opened to
6446 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6447 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006448 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006449
6450 // nothing to do if one output is already opened for this profile
6451 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006452 for (j = 0; j < outputs.size(); j++) {
6453 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006454 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006455 // matching profile: save the sample rates, format and channel masks supported
6456 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006457 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006458 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006459 }
Eric Laurente552edb2014-03-10 17:42:56 -07006460 break;
6461 }
6462 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006463 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006464 continue;
6465 }
6466
Eric Laurent3974e3b2017-12-07 17:58:43 -08006467 if (!profile->canOpenNewIo()) {
6468 ALOGW("Max Output number %u already opened for this profile %s",
6469 profile->maxOpenCount, profile->getTagName().c_str());
6470 continue;
6471 }
6472
Eric Laurent83efe1c2017-07-09 16:51:08 -07006473 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006474 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006475 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6476 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006477 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006478 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006479 profiles.removeAt(profile_index);
6480 profile_index--;
6481 } else {
6482 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006483 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006484 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006485 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6486 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006487 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006488 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006489
François Gaffie11d30102018-11-02 16:09:09 +01006490 if (device_distinguishes_on_address(deviceType)) {
6491 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6492 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306493 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6494 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006495 }
Eric Laurente552edb2014-03-10 17:42:56 -07006496 ALOGV("checkOutputsForDevice(): adding output %d", output);
6497 }
6498 }
6499
6500 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006501 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006502 return BAD_VALUE;
6503 }
Eric Laurentd4692962014-05-05 18:13:44 -07006504 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006505 // check if one opened output is not needed any more after disconnecting one device
6506 for (size_t i = 0; i < mOutputs.size(); i++) {
6507 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006508 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006509 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006510 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006511 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006512 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006513 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006514 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6515 mOutputs.keyAt(i));
6516 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006517 }
Eric Laurente552edb2014-03-10 17:42:56 -07006518 }
6519 }
Eric Laurentd4692962014-05-05 18:13:44 -07006520 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006521 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006522 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6523 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006524 if (!profile->supportsDevice(device)) {
6525 continue;
6526 }
6527 ALOGV("checkOutputsForDevice(): "
6528 "clearing direct output profile %zu on module %s",
6529 j, hwModule->getName());
6530 profile->clearAudioProfiles();
6531 if (!profile->hasDynamicAudioProfile()) {
6532 continue;
6533 }
6534 // When a device is disconnected, if there is an IOProfile that contains dynamic
6535 // profiles and supports the disconnected device, call getAudioPort to repopulate
6536 // the capabilities of the devices that is supported by the IOProfile.
6537 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6538 if (supportedDevice == device ||
6539 !mAvailableOutputDevices.contains(supportedDevice)) {
6540 continue;
6541 }
6542 struct audio_port_v7 port;
6543 supportedDevice->toAudioPort(&port);
6544 status_t status = mpClientInterface->getAudioPort(&port);
6545 if (status == NO_ERROR) {
6546 supportedDevice->importAudioPort(port);
6547 }
Eric Laurente552edb2014-03-10 17:42:56 -07006548 }
6549 }
6550 }
6551 }
6552 return NO_ERROR;
6553}
6554
François Gaffie11d30102018-11-02 16:09:09 +01006555status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006556 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006557{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006558 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006559
François Gaffie11d30102018-11-02 16:09:09 +01006560 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006561 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006562 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006563 }
6564
Eric Laurentd4692962014-05-05 18:13:44 -07006565 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006566 // first call getAudioPort to get the supported attributes from the HAL
6567 struct audio_port_v7 port = {};
6568 device->toAudioPort(&port);
6569 status_t status = mpClientInterface->getAudioPort(&port);
6570 if (status == NO_ERROR) {
6571 device->importAudioPort(port);
6572 }
6573
Eric Laurent0dd51852019-04-19 18:18:58 -07006574 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006575 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006576 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006577 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006578 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006579 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006580 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006581
François Gaffie11d30102018-11-02 16:09:09 +01006582 if (profile->supportsDevice(device)) {
6583 profiles.add(profile);
6584 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6585 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006586 }
6587 }
6588 }
6589
Eric Laurent0dd51852019-04-19 18:18:58 -07006590 if (profiles.isEmpty()) {
6591 ALOGW("%s: No input profile available for device %s",
6592 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006593 return BAD_VALUE;
6594 }
6595
6596 // open inputs for matching profiles if needed. Direct inputs are also opened to
6597 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6598 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6599
Eric Laurent1c333e22014-05-20 10:48:17 -07006600 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006601
Eric Laurentd4692962014-05-05 18:13:44 -07006602 // nothing to do if one input is already opened for this profile
6603 size_t input_index;
6604 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6605 desc = mInputs.valueAt(input_index);
6606 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006607 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006608 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006609 }
Eric Laurentd4692962014-05-05 18:13:44 -07006610 break;
6611 }
6612 }
6613 if (input_index != mInputs.size()) {
6614 continue;
6615 }
6616
Eric Laurent3974e3b2017-12-07 17:58:43 -08006617 if (!profile->canOpenNewIo()) {
6618 ALOGW("Max Input number %u already opened for this profile %s",
6619 profile->maxOpenCount, profile->getTagName().c_str());
6620 continue;
6621 }
6622
Eric Laurentfe231122017-11-17 17:48:06 -08006623 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006624 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006625 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006626
Eric Laurentcf2c0212014-07-25 16:20:43 -07006627 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006628 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006629 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006630 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006631 mpClientInterface->setParameters(input, String8(param));
6632 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006633 }
jiabin12537fc2023-10-12 17:56:08 +00006634 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006635 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006636 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006637 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006638 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006639 }
6640
Eric Laurent0dd51852019-04-19 18:18:58 -07006641 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006642 addInput(input, desc);
6643 }
6644 } // endif input != 0
6645
Eric Laurentcf2c0212014-07-25 16:20:43 -07006646 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006647 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006648 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006649 profiles.removeAt(profile_index);
6650 profile_index--;
6651 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006652 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006653 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006654 }
Eric Laurentd4692962014-05-05 18:13:44 -07006655 ALOGV("checkInputsForDevice(): adding input %d", input);
6656 }
6657 } // end scan profiles
6658
6659 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006660 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006661 return BAD_VALUE;
6662 }
6663 } else {
6664 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006665 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006666 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006667 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006668 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006669 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006670 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006671 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006672 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6673 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006674 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006675 }
6676 }
6677 }
6678 } // end disconnect
6679
6680 return NO_ERROR;
6681}
6682
6683
Eric Laurente0720872014-03-11 09:30:41 -07006684void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006685{
6686 ALOGV("closeOutput(%d)", output);
6687
François Gaffie1c878552018-11-22 16:53:21 +01006688 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6689 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006690 ALOGW("closeOutput() unknown output %d", output);
6691 return;
6692 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006693 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006694 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006695
Eric Laurente552edb2014-03-10 17:42:56 -07006696 // look for duplicated outputs connected to the output being removed.
6697 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006698 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6699 if (dupOutput->isDuplicated() &&
6700 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6701 sp<SwAudioOutputDescriptor> remainingOutput =
6702 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006703 // As all active tracks on duplicated output will be deleted,
6704 // and as they were also referenced on the other output, the reference
6705 // count for their stream type must be adjusted accordingly on
6706 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006707 const bool wasActive = remainingOutput->isActive();
6708 // Note: no-op on the closing output where all clients has already been set inactive
6709 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006710 // stop() will be a no op if the output is still active but is needed in case all
6711 // active streams refcounts where cleared above
6712 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006713 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006714 }
Eric Laurente552edb2014-03-10 17:42:56 -07006715 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6716 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6717
6718 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006719 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006720 }
6721 }
6722
Eric Laurent05b90f82014-08-27 15:32:29 -07006723 nextAudioPortGeneration();
6724
François Gaffie1c878552018-11-22 16:53:21 +01006725 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006726 if (index >= 0) {
6727 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006728 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6729 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006730 mAudioPatches.removeItemsAt(index);
6731 mpClientInterface->onAudioPatchListUpdate();
6732 }
6733
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006734 if (closingOutputWasActive) {
6735 closingOutput->stop();
6736 }
François Gaffie1c878552018-11-22 16:53:21 +01006737 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006738
François Gaffie53615e22015-03-19 09:24:12 +01006739 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006740 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006741 if (closingOutput == mSpatializerOutput) {
6742 mSpatializerOutput.clear();
6743 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006744
6745 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6746 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006747 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006748 bool directOutputOpen = false;
6749 for (size_t i = 0; i < mOutputs.size(); i++) {
6750 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6751 directOutputOpen = true;
6752 break;
6753 }
6754 }
6755 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006756 ALOGV("no direct outputs open, reset MSD patches");
6757 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6758 // how output devices for patching are resolved. Avoid by caching and reusing the
6759 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6760 // devices to patch to. This may be complicated by the fact that devices may become
6761 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006762 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006763 }
6764 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006765}
6766
6767void AudioPolicyManager::closeInput(audio_io_handle_t input)
6768{
6769 ALOGV("closeInput(%d)", input);
6770
6771 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6772 if (inputDesc == NULL) {
6773 ALOGW("closeInput() unknown input %d", input);
6774 return;
6775 }
6776
Eric Laurent6a94d692014-05-20 11:18:06 -07006777 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006778
François Gaffie11d30102018-11-02 16:09:09 +01006779 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006780 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006781 if (index >= 0) {
6782 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006783 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6784 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006785 mAudioPatches.removeItemsAt(index);
6786 mpClientInterface->onAudioPatchListUpdate();
6787 }
6788
François Gaffie6ebbce02023-07-19 13:27:53 +02006789 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006790 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006791 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006792
François Gaffie11d30102018-11-02 16:09:09 +01006793 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6794 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006795 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006796 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006797 }
Eric Laurente552edb2014-03-10 17:42:56 -07006798}
6799
François Gaffie11d30102018-11-02 16:09:09 +01006800SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6801 const DeviceVector &devices,
6802 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006803{
6804 SortedVector<audio_io_handle_t> outputs;
6805
François Gaffie11d30102018-11-02 16:09:09 +01006806 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006807 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006808 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006809 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006810 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006811 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006812 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006813 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006814 outputs.add(openOutputs.keyAt(i));
6815 }
6816 }
6817 return outputs;
6818}
6819
Mikhail Naganov37977152018-07-11 15:54:44 -07006820void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6821{
6822 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6823 // output is suspended before any tracks are moved to it
6824 checkA2dpSuspend();
6825 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006826 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006827 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006828 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006829 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006830 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6831 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6832 // configuration changes will ultimately be rerouted correctly. We can still avoid
6833 // unnecessary rerouting by caching and reusing the arguments to
6834 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6835 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006836 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006837 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006838 // an event that changed routing likely occurred, inform upper layers
6839 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006840}
6841
François Gaffiec005e562018-11-06 15:04:49 +01006842bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6843 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006844{
François Gaffiec005e562018-11-06 15:04:49 +01006845 return mEngine->getProductStrategyForAttributes(lAttr) ==
6846 mEngine->getProductStrategyForAttributes(rAttr);
6847}
6848
Francois Gaffieff1eb522020-05-06 18:37:04 +02006849void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6850{
6851 for (size_t i = 0; i < mAudioSources.size(); i++) {
6852 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6853 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006854 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006855 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006856 connectAudioSource(sourceDesc);
6857 }
6858 }
6859}
6860
6861void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6862{
6863 for (size_t i = 0; i < mAudioSources.size(); i++) {
6864 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6865 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6866 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6867 disconnectAudioSource(sourceDesc);
6868 }
6869 }
6870}
6871
François Gaffiec005e562018-11-06 15:04:49 +01006872void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6873{
6874 auto psId = mEngine->getProductStrategyForAttributes(attr);
6875
6876 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6877 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006878
François Gaffie11d30102018-11-02 16:09:09 +01006879 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6880 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006881
Eric Laurentc209fe42020-06-05 18:11:23 -07006882 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006883 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006884 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006885 // take into account dynamic audio policies related changes: if a client is now associated
6886 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006887 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006888 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6889 if (desc->isDuplicated()) {
6890 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006891 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006892 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6893 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6894 continue;
6895 }
6896 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006897 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006898 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6899 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6900 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006901 if (status != OK) {
6902 continue;
6903 }
yucliuf4de36d2020-09-14 14:57:56 -07006904 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006905 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006906 maxLatency = desc->latency();
6907 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006908 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006909 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006910 }
6911 }
6912
Eric Laurent56ed8842022-11-15 16:04:41 +01006913 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006914 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6915 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006916 for (audio_io_handle_t srcOut : srcOutputs) {
6917 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006918 if (desc == nullptr) continue;
6919
6920 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006921 maxLatency = desc->latency();
6922 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006923
Eric Laurent56ed8842022-11-15 16:04:41 +01006924 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006925 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006926 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006927 // a client on a non direct outputs has necessarily a linear PCM format
6928 // so we can call selectOutput() safely
6929 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6930 client->flags(),
6931 client->config().format,
6932 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006933 client->config().sample_rate,
6934 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006935 if (newOutput != srcOut) {
6936 invalidate = true;
6937 break;
6938 }
6939 } else {
6940 sp<IOProfile> profile = getProfileForOutput(newDevices,
6941 client->config().sample_rate,
6942 client->config().format,
6943 client->config().channel_mask,
6944 client->flags(),
6945 true /* directOnly */);
6946 if (profile != desc->mProfile) {
6947 invalidate = true;
6948 break;
6949 }
6950 }
6951 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006952 // mute strategy while moving tracks from one output to another
6953 if (invalidate) {
6954 invalidatedOutputs.push_back(desc);
6955 if (desc->isStrategyActive(psId)) {
6956 setStrategyMute(psId, true, desc);
6957 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
6958 newDevices.types());
6959 }
Eric Laurente552edb2014-03-10 17:42:56 -07006960 }
François Gaffiec005e562018-11-06 15:04:49 +01006961 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006962 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006963 connectAudioSource(source);
6964 }
Eric Laurente552edb2014-03-10 17:42:56 -07006965 }
6966
Eric Laurent56ed8842022-11-15 16:04:41 +01006967 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
6968 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
6969 std::to_string(srcOutputs[0]).c_str(),
6970 std::to_string(dstOutputs[0]).c_str());
6971
François Gaffiec005e562018-11-06 15:04:49 +01006972 // Move effects associated to this stream from previous output to new output
6973 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006974 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006975 }
François Gaffiec005e562018-11-06 15:04:49 +01006976 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01006977 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08006978 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01006979 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08006980 desc->setTracksInvalidatedStatusByStrategy(psId);
6981 }
Eric Laurente552edb2014-03-10 17:42:56 -07006982 }
6983 }
6984}
6985
Eric Laurente0720872014-03-11 09:30:41 -07006986void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006987{
François Gaffiec005e562018-11-06 15:04:49 +01006988 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6989 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6990 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006991 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006992 }
Eric Laurente552edb2014-03-10 17:42:56 -07006993}
6994
Kevin Rocard153f92d2018-12-18 18:33:28 -08006995void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08006996 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006997 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006998 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006999 for (size_t i = 0; i < mOutputs.size(); i++) {
7000 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7001 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007002 sp<AudioPolicyMix> primaryMix;
7003 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007004 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007005 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7006 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7007 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007008 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7009 for (auto &secondaryMix : secondaryMixes) {
7010 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7011 if (outputDesc != nullptr &&
7012 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7013 secondaryDescs.push_back(outputDesc);
7014 }
7015 }
7016
jiabinc44b3462022-12-08 12:52:31 -08007017 if (status != OK &&
7018 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7019 // When it failed to query secondary output, only invalidate the client that is not
7020 // MMAP. The reason is that MMAP stream will not support secondary output.
7021 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007022 } else if (!std::equal(
7023 client->getSecondaryOutputs().begin(),
7024 client->getSecondaryOutputs().end(),
7025 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007026 if (!audio_is_linear_pcm(client->config().format)) {
7027 // If the format is not PCM, the tracks should be invalidated to get correct
7028 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007029 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007030 } else {
7031 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7032 std::vector<audio_io_handle_t> secondaryOutputIds;
7033 for (const auto &secondaryDesc: secondaryDescs) {
7034 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7035 weakSecondaryDescs.push_back(secondaryDesc);
7036 }
7037 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7038 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007039 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007040 }
7041 }
7042 }
jiabin10a03f12021-05-07 23:46:28 +00007043 if (!trackSecondaryOutputs.empty()) {
7044 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7045 }
jiabinc44b3462022-12-08 12:52:31 -08007046 if (!clientsToInvalidate.empty()) {
7047 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7048 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007049 }
7050}
7051
Eric Laurent2517af32020-11-25 15:31:27 +01007052bool AudioPolicyManager::isScoRequestedForComm() const {
7053 AudioDeviceTypeAddrVector devices;
7054 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7055 for (const auto &device : devices) {
7056 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7057 return true;
7058 }
7059 }
7060 return false;
7061}
7062
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007063bool AudioPolicyManager::isHearingAidUsedForComm() const {
7064 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7065 true /*fromCache*/);
7066 for (const auto &device : devices) {
7067 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7068 return true;
7069 }
7070 }
7071 return false;
7072}
7073
7074
Eric Laurente0720872014-03-11 09:30:41 -07007075void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007076{
François Gaffie53615e22015-03-19 09:24:12 +01007077 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007078 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007079 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007080 return;
7081 }
7082
Eric Laurent3a4311c2014-03-17 12:00:47 -07007083 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007084 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7085 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007086 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007087
7088 // if suspended, restore A2DP output if:
7089 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007090 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007091 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007092 //
Eric Laurentf732e072016-08-03 19:30:28 -07007093 // if not suspended, suspend A2DP output if:
7094 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007095 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007096 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007097 //
7098 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007099 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007100 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007101 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007102 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007103
7104 mpClientInterface->restoreOutput(a2dpOutput);
7105 mA2dpSuspended = false;
7106 }
7107 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007108 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007109 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007110 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007111 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007112
7113 mpClientInterface->suspendOutput(a2dpOutput);
7114 mA2dpSuspended = true;
7115 }
7116 }
7117}
7118
François Gaffie11d30102018-11-02 16:09:09 +01007119DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7120 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007121{
François Gaffiedb1755b2023-09-01 11:50:35 +02007122 if (outputDesc == nullptr) {
7123 return DeviceVector{};
7124 }
François Gaffie11d30102018-11-02 16:09:09 +01007125
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007126 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007127 if (index >= 0) {
7128 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007129 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007130 ALOGV("%s device %s forced by patch %d", __func__,
7131 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7132 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007133 }
7134 }
7135
Dean Wheatley514b4312020-06-17 21:45:00 +10007136 // Do not retrieve engine device for outputs through MSD
7137 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7138 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7139 return outputDesc->devices();
7140 }
7141
Eric Laurent97ac8712018-07-27 18:59:02 -07007142 // Honor explicit routing requests only if no client using default routing is active on this
7143 // input: a specific app can not force routing for other apps by setting a preferred device.
7144 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007145 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007146 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007147 if (device != nullptr) {
7148 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007149 }
7150
François Gaffiea807ef92018-11-05 10:44:33 +01007151 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7152 // of setForceUse / Default Bus device here
7153 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7154 if (device != nullptr) {
7155 return DeviceVector(device);
7156 }
7157
François Gaffiedb1755b2023-09-01 11:50:35 +02007158 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007159 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7160 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7161 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307162 auto hasStreamActive = [&](auto stream) {
7163 return hasStream(streams, stream) && isStreamActive(stream, 0);
7164 };
Eric Laurent484e9272018-06-07 17:29:23 -07007165
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307166 auto doGetOutputDevicesForVoice = [&]() {
7167 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007168 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307169 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007170 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7171 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307172 };
7173
7174 // With low-latency playing on speaker, music on WFD, when the first low-latency
7175 // output is stopped, getNewOutputDevices checks for a product strategy
7176 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007177 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307178 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7179 // stream is associated to the output descriptor.
7180 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7181 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7182 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7183 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007184 // Retrieval of devices for voice DL is done on primary output profile, cannot
7185 // check the route (would force modifying configuration file for this profile)
7186 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7187 break;
7188 }
Eric Laurente552edb2014-03-10 17:42:56 -07007189 }
François Gaffiec005e562018-11-06 15:04:49 +01007190 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007191 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007192}
7193
François Gaffie11d30102018-11-02 16:09:09 +01007194sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7195 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007196{
François Gaffie11d30102018-11-02 16:09:09 +01007197 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007198
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007199 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007200 if (index >= 0) {
7201 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007202 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007203 ALOGV("getNewInputDevice() device %s forced by patch %d",
7204 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7205 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007206 }
7207 }
7208
Eric Laurent97ac8712018-07-27 18:59:02 -07007209 // Honor explicit routing requests only if no client using default routing is active on this
7210 // input: a specific app can not force routing for other apps by setting a preferred device.
7211 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007212 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7213 if (device != nullptr) {
7214 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007215 }
7216
Eric Laurentdc95a252018-04-12 12:46:56 -07007217 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007218 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007219 audio_attributes_t attributes;
7220 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007221 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007222 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7223 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007224 attributes = topClient->attributes();
7225 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007226 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007227 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007228 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7229 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007230 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007231 }
7232
Francois Gaffie716e1432019-01-14 16:58:59 +01007233 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7234 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007235 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007236 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007237 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007238 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007239
Eric Laurente552edb2014-03-10 17:42:56 -07007240 return device;
7241}
7242
Eric Laurent794fde22016-03-11 09:50:45 -08007243bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7244 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007245 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007246}
7247
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007248status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007249 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007250 if (devices == nullptr) {
7251 return BAD_VALUE;
7252 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007253
Andy Hung6d23c0f2022-02-16 09:37:15 -08007254 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007255 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7256 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007257 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007258 for (const auto& device : curDevices) {
7259 devices->push_back(device->getDeviceTypeAddr());
7260 }
7261 return NO_ERROR;
7262}
7263
Eric Laurente0720872014-03-11 09:30:41 -07007264void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007265 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007266 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007267 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007268 updateDevicesAndOutputs();
7269 break;
7270 default:
7271 break;
7272 }
7273}
7274
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007275uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007276
7277 // skip beacon mute management if a dedicated TTS output is available
7278 if (mTtsOutputAvailable) {
7279 return 0;
7280 }
7281
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007282 switch(event) {
7283 case STARTING_OUTPUT:
7284 mBeaconMuteRefCount++;
7285 break;
7286 case STOPPING_OUTPUT:
7287 if (mBeaconMuteRefCount > 0) {
7288 mBeaconMuteRefCount--;
7289 }
7290 break;
7291 case STARTING_BEACON:
7292 mBeaconPlayingRefCount++;
7293 break;
7294 case STOPPING_BEACON:
7295 if (mBeaconPlayingRefCount > 0) {
7296 mBeaconPlayingRefCount--;
7297 }
7298 break;
7299 }
7300
7301 if (mBeaconMuteRefCount > 0) {
7302 // any playback causes beacon to be muted
7303 return setBeaconMute(true);
7304 } else {
7305 // no other playback: unmute when beacon starts playing, mute when it stops
7306 return setBeaconMute(mBeaconPlayingRefCount == 0);
7307 }
7308}
7309
7310uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7311 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7312 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7313 // keep track of muted state to avoid repeating mute/unmute operations
7314 if (mBeaconMuted != mute) {
7315 // mute/unmute AUDIO_STREAM_TTS on all outputs
7316 ALOGV("\t muting %d", mute);
7317 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007318 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7319 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7320 ALOGV("\t no tts volume source available");
7321 return 0;
7322 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007323 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007324 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007325 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007326 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007327 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007328 maxLatency = latency;
7329 }
7330 }
7331 mBeaconMuted = mute;
7332 return maxLatency;
7333 }
7334 return 0;
7335}
7336
Eric Laurente0720872014-03-11 09:30:41 -07007337void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007338{
François Gaffiec005e562018-11-06 15:04:49 +01007339 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007340 mPreviousOutputs = mOutputs;
7341}
7342
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007343uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007344 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007345 uint32_t delayMs)
7346{
7347 // mute/unmute strategies using an incompatible device combination
7348 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7349 // if unmuting, unmute only after the specified delay
7350 if (outputDesc->isDuplicated()) {
7351 return 0;
7352 }
7353
7354 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007355 DeviceVector devices = outputDesc->devices();
7356 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007357
François Gaffiec005e562018-11-06 15:04:49 +01007358 auto productStrategies = mEngine->getOrderedProductStrategies();
7359 for (const auto &productStrategy : productStrategies) {
7360 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7361 DeviceVector curDevices =
7362 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7363 curDevices = curDevices.filter(outputDesc->supportedDevices());
7364 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007365 bool doMute = false;
7366
François Gaffiec005e562018-11-06 15:04:49 +01007367 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007368 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007369 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7370 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007371 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007372 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007373 }
Eric Laurent99401132014-05-07 19:48:15 -07007374 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007375 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007376 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007377 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007378 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007379 continue;
7380 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307381 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007382 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7383 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7384 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007385 if (mute) {
7386 // FIXME: should not need to double latency if volume could be applied
7387 // immediately by the audioflinger mixer. We must account for the delay
7388 // between now and the next time the audioflinger thread for this output
7389 // will process a buffer (which corresponds to one buffer size,
7390 // usually 1/2 or 1/4 of the latency).
7391 if (muteWaitMs < desc->latency() * 2) {
7392 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007393 }
7394 }
7395 }
7396 }
7397 }
7398 }
7399
Eric Laurent99401132014-05-07 19:48:15 -07007400 // temporary mute output if device selection changes to avoid volume bursts due to
7401 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007402 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007403 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007404
Eric Laurentdc462862016-07-19 12:29:53 -07007405 if (muteWaitMs < tempMuteWaitMs) {
7406 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007407 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007408
7409 // If recommended duration is defined, replace temporary mute duration to avoid
7410 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7411 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7412 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7413 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7414 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7415
François Gaffieaaac0fd2018-11-22 17:56:39 +01007416 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7417 // make sure that we do not start the temporary mute period too early in case of
7418 // delayed device change
7419 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7420 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007421 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007422 }
7423 }
7424
Eric Laurente552edb2014-03-10 17:42:56 -07007425 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7426 if (muteWaitMs > delayMs) {
7427 muteWaitMs -= delayMs;
7428 usleep(muteWaitMs * 1000);
7429 return muteWaitMs;
7430 }
7431 return 0;
7432}
7433
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307434uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7435 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007436 const DeviceVector &devices,
7437 bool force,
7438 int delayMs,
7439 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007440 bool requiresMuteCheck, bool requiresVolumeCheck,
7441 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007442{
jiabin3ff8d7d2022-12-13 06:27:44 +00007443 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307444 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7445 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7446 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007447 uint32_t muteWaitMs;
7448
7449 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307450 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007451 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307452 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007453 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007454 return muteWaitMs;
7455 }
Eric Laurente552edb2014-03-10 17:42:56 -07007456
7457 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007458 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007459 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007460 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007461
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307462 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7463 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007464
7465 if (!filteredDevices.isEmpty()) {
7466 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007467 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007468
7469 // if the outputs are not materially active, there is no need to mute.
7470 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007471 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007472 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307473 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7474 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007475 muteWaitMs = 0;
7476 }
Eric Laurente552edb2014-03-10 17:42:56 -07007477
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007478 bool outputRouted = outputDesc->isRouted();
7479
Eric Laurent79ea9582020-06-11 18:49:24 -07007480 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7481 // output profile or if new device is not supported AND previous device(s) is(are) still
7482 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007483 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307484 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7485 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007486 // restore previous device after evaluating strategy mute state
7487 outputDesc->setDevices(prevDevices);
7488 return muteWaitMs;
7489 }
7490
Eric Laurente552edb2014-03-10 17:42:56 -07007491 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007492 // the requested device is AUDIO_DEVICE_NONE
7493 // OR the requested device is the same as current device
7494 // AND force is not specified
7495 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007496 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007497 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307498 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7499 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7500 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007501 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307502 ALOGV("%s %s setting same device on routed output, force apply volumes",
7503 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007504 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7505 }
Eric Laurente552edb2014-03-10 17:42:56 -07007506 return muteWaitMs;
7507 }
7508
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307509 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7510 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007511
Eric Laurente552edb2014-03-10 17:42:56 -07007512 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007513 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007514 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007515 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007516 PatchBuilder patchBuilder;
7517 patchBuilder.addSource(outputDesc);
7518 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7519 for (const auto &filteredDevice : filteredDevices) {
7520 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007521 }
7522
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007523 // Add half reported latency to delayMs when muteWaitMs is null in order
7524 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007525 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7526 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7527 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007528 }
Eric Laurente552edb2014-03-10 17:42:56 -07007529
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007530 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7531 if (!skipMuteDelay) {
7532 // update stream volumes according to new device
7533 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7534 }
Eric Laurente552edb2014-03-10 17:42:56 -07007535
7536 return muteWaitMs;
7537}
7538
Eric Laurentc75307b2015-03-17 15:29:32 -07007539status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007540 int delayMs,
7541 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007542{
Eric Laurent6a94d692014-05-20 11:18:06 -07007543 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007544 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7545 return INVALID_OPERATION;
7546 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007547 if (patchHandle) {
7548 index = mAudioPatches.indexOfKey(*patchHandle);
7549 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007550 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007551 }
7552 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007553 return INVALID_OPERATION;
7554 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007555 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007556 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007557 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007558 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007559 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007560 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007561 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007562 return status;
7563}
7564
7565status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007566 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007567 bool force,
7568 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007569{
7570 status_t status = NO_ERROR;
7571
Eric Laurent1f2f2232014-06-02 12:01:23 -07007572 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007573 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7574 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007575
François Gaffie11d30102018-11-02 16:09:09 +01007576 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007577 PatchBuilder patchBuilder;
7578 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007579 // AUDIO_SOURCE_HOTWORD is for internal use only:
7580 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007581 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7582 auto result = usecase;
7583 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7584 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7585 }
7586 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007587 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007588 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007589 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007590 }
7591 }
7592 return status;
7593}
7594
Eric Laurent6a94d692014-05-20 11:18:06 -07007595status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7596 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007597{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007598 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007599 ssize_t index;
7600 if (patchHandle) {
7601 index = mAudioPatches.indexOfKey(*patchHandle);
7602 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007603 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007604 }
7605 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007606 return INVALID_OPERATION;
7607 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007608 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007609 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007610 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007611 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007612 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007613 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007614 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007615 return status;
7616}
7617
François Gaffie11d30102018-11-02 16:09:09 +01007618sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007619 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007620 audio_format_t& format,
7621 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007622 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007623{
7624 // Choose an input profile based on the requested capture parameters: select the first available
7625 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007626 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007627 //
7628 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7629 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007630
Atneya Nair0f0a8032022-12-12 16:20:12 -08007631 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7632 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7633 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7634
7635 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007636
jiabin2fd710d2022-05-02 23:20:22 +00007637 for (;;) {
7638 sp<IOProfile> firstInexact = nullptr;
7639 uint32_t updatedSamplingRate = 0;
7640 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7641 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7642 for (const auto& hwModule : mHwModules) {
7643 for (const auto& profile : hwModule->getInputProfiles()) {
7644 // profile->log();
7645 //updatedFormat = format;
7646 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7647 &samplingRate /*updatedSamplingRate*/,
7648 format,
7649 &format, /*updatedFormat*/
7650 channelMask,
7651 &channelMask /*updatedChannelMask*/,
7652 // FIXME ugly cast
7653 (audio_output_flags_t) flags,
7654 true /*exactMatchRequiredForInputFlags*/)) {
7655 return profile;
7656 }
7657 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7658 samplingRate,
7659 &updatedSamplingRate,
7660 format,
7661 &updatedFormat,
7662 channelMask,
7663 &updatedChannelMask,
7664 // FIXME ugly cast
7665 (audio_output_flags_t) flags,
7666 false /*exactMatchRequiredForInputFlags*/)) {
7667 firstInexact = profile;
7668 }
7669 }
7670 }
7671
7672 if (firstInexact != nullptr) {
7673 samplingRate = updatedSamplingRate;
7674 format = updatedFormat;
7675 channelMask = updatedChannelMask;
7676 return firstInexact;
7677 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7678 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7679 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7680 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7681 flags = AUDIO_INPUT_FLAG_NONE;
7682 } else { // fail
7683 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7684 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7685 samplingRate, format, channelMask, oriFlags);
7686 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007687 }
7688 }
jiabin2fd710d2022-05-02 23:20:22 +00007689
7690 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007691}
7692
François Gaffieaaac0fd2018-11-22 17:56:39 +01007693float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7694 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007695 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007696 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007697{
jiabin9a3361e2019-10-01 09:38:30 -07007698 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007699
7700 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7701 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7702 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7703 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007704 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7705 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7706 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7707 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7708 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007709 // Verify that the current volume source is not the ringer volume to prevent recursively
7710 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7711 // to the same volume group.
7712 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007713 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7714 mOutputs.isActive(ringVolumeSrc, 0)) {
7715 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007716 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007717 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007718 }
7719
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007720 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007721 if ((volumeSource != callVolumeSrc && (isInCall() ||
7722 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007723 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007724 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7725 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007726 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7727 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7728 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007729 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007730 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007731 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007732 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007733 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007734 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007735 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7736 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7737 // programmatically muted.
7738 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7739 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7740 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007741 bool exemptFromCapping =
7742 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7743 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007744 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7745 volumeSource, volumeDb);
7746 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007747 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7748 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7749 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007750 }
7751 }
Eric Laurente552edb2014-03-10 17:42:56 -07007752 // if a headset is connected, apply the following rules to ring tones and notifications
7753 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007754 // - always attenuate notifications volume by 6dB
7755 // - attenuate ring tones volume by 6dB unless music is not playing and
7756 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007757 // - if music is playing, always limit the volume to current music volume,
7758 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007759 if (!Intersection(deviceTypes,
7760 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7761 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007762 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7763 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007764 ((volumeSource == alarmVolumeSrc ||
7765 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007766 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7767 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7768 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007769 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7770 curves.canBeMuted()) {
7771
Eric Laurente552edb2014-03-10 17:42:56 -07007772 // when the phone is ringing we must consider that music could have been paused just before
7773 // by the music application and behave as if music was active if the last music track was
7774 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007775 // Verify that the current volume source is not the music volume to prevent recursively
7776 // calling to compute volume. This could happen in cases where music and
7777 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7778 if (volumeSource != musicVolumeSrc &&
7779 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7780 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007781 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007782 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007783 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7784 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007785 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007786 float musicVolDb = computeVolume(musicCurves,
7787 musicVolumeSrc,
7788 musicCurves.getVolumeIndex(musicDevice),
7789 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007790 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7791 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7792 if (volumeDb > minVolDb) {
7793 volumeDb = minVolDb;
7794 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007795 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007796 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7797 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7798 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007799 // on A2DP, also ensure notification volume is not too low compared to media when
7800 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007801 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007802 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007803 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7804 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007805 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7806 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007807 }
7808 }
jiabin9a3361e2019-10-01 09:38:30 -07007809 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007810 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007811 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007812 }
7813 }
7814
François Gaffie43c73442018-11-08 08:21:55 +01007815 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007816}
7817
Eric Laurent3839bc02018-07-10 18:33:34 -07007818int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007819 VolumeSource fromVolumeSource,
7820 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007821{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007822 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007823 return srcIndex;
7824 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007825 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7826 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007827 float minSrc = (float)srcCurves.getVolumeIndexMin();
7828 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7829 float minDst = (float)dstCurves.getVolumeIndexMin();
7830 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007831
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007832 // preserve mute request or correct range
7833 if (srcIndex < minSrc) {
7834 if (srcIndex == 0) {
7835 return 0;
7836 }
7837 srcIndex = minSrc;
7838 } else if (srcIndex > maxSrc) {
7839 srcIndex = maxSrc;
7840 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007841 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7842}
7843
François Gaffieaaac0fd2018-11-22 17:56:39 +01007844status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7845 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007846 int index,
7847 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007848 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007849 int delayMs,
7850 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007851{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007852 // do not change actual attributes volume if the attributes is muted
7853 if (outputDesc->isMuted(volumeSource)) {
7854 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7855 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007856 return NO_ERROR;
7857 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007858 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7859 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7860 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7861 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007862
Eric Laurent2517af32020-11-25 15:31:27 +01007863 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007864 bool isHAUsed = isHearingAidUsedForComm();
7865
Eric Laurente552edb2014-03-10 17:42:56 -07007866 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007867 // if sco and call follow same curves, bypass forceUseForComm
7868 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007869 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007870 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7871 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007872 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007873 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007874 // Do not return an error here as AudioService will always set both voice call
7875 // and bluetooth SCO volumes due to stream aliasing.
7876 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007877 }
jiabin9a3361e2019-10-01 09:38:30 -07007878 if (deviceTypes.empty()) {
7879 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007880 index = curves.getVolumeIndex(deviceTypes);
7881 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7882 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007883 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007884
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007885 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7886 ALOGE("invalid volume index range");
7887 return BAD_VALUE;
7888 }
7889
jiabin9a3361e2019-10-01 09:38:30 -07007890 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7891 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007892 // Force VoIP volume to max for bluetooth SCO device except if muted
7893 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007894 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007895 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007896 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007897 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007898 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7899 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007900
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007901 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007902 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007903 // 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 +01007904 if (isVoiceVolSrc) {
7905 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007906 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007907 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007908 }
Eric Laurent18fba842016-03-31 14:41:26 -07007909 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007910 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7911 mLastVoiceVolume = voiceVolume;
7912 }
7913 }
Eric Laurente552edb2014-03-10 17:42:56 -07007914 return NO_ERROR;
7915}
7916
Eric Laurentc75307b2015-03-17 15:29:32 -07007917void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007918 const DeviceTypeSet& deviceTypes,
7919 int delayMs,
7920 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007921{
jiabincd510522020-01-22 09:40:55 -08007922 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007923 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7924 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7925 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007926 curves.getVolumeIndex(deviceTypes),
7927 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007928 }
7929}
7930
François Gaffiec005e562018-11-06 15:04:49 +01007931void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7932 bool on,
7933 const sp<AudioOutputDescriptor>& outputDesc,
7934 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007935 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007936{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007937 std::vector<VolumeSource> sourcesToMute;
7938 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7939 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7940 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007941 VolumeSource source = toVolumeSource(attributes, false);
7942 if ((source != VOLUME_SOURCE_NONE) &&
7943 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7944 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007945 sourcesToMute.push_back(source);
7946 }
Eric Laurente552edb2014-03-10 17:42:56 -07007947 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007948 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007949 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007950 }
7951
Eric Laurente552edb2014-03-10 17:42:56 -07007952}
7953
François Gaffieaaac0fd2018-11-22 17:56:39 +01007954void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7955 bool on,
7956 const sp<AudioOutputDescriptor>& outputDesc,
7957 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007958 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007959{
jiabin9a3361e2019-10-01 09:38:30 -07007960 if (deviceTypes.empty()) {
7961 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007962 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007963 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007964 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007965 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007966 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007967 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007968 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7969 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007970 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007971 }
7972 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007973 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7974 // ignored
7975 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007976 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007977 if (!outputDesc->isMuted(volumeSource)) {
7978 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007979 return;
7980 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007981 if (outputDesc->decMuteCount(volumeSource) == 0) {
7982 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007983 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007984 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007985 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007986 delayMs);
7987 }
7988 }
7989}
7990
François Gaffie53615e22015-03-19 09:24:12 +01007991bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7992{
François Gaffiec005e562018-11-06 15:04:49 +01007993 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007994 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7995 return true;
7996 }
7997
7998 // has known usage?
7999 switch (paa->usage) {
8000 case AUDIO_USAGE_UNKNOWN:
8001 case AUDIO_USAGE_MEDIA:
8002 case AUDIO_USAGE_VOICE_COMMUNICATION:
8003 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8004 case AUDIO_USAGE_ALARM:
8005 case AUDIO_USAGE_NOTIFICATION:
8006 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8007 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8008 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8009 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8010 case AUDIO_USAGE_NOTIFICATION_EVENT:
8011 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8012 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8013 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8014 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008015 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008016 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008017 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008018 case AUDIO_USAGE_EMERGENCY:
8019 case AUDIO_USAGE_SAFETY:
8020 case AUDIO_USAGE_VEHICLE_STATUS:
8021 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008022 break;
8023 default:
8024 return false;
8025 }
8026 return true;
8027}
8028
François Gaffie2110e042015-03-24 08:41:51 +01008029audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8030{
8031 return mEngine->getForceUse(usage);
8032}
8033
Eric Laurent96d1dda2022-03-14 17:14:19 +01008034bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008035 return isStateInCall(mEngine->getPhoneState());
8036}
8037
Eric Laurent96d1dda2022-03-14 17:14:19 +01008038bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008039 return is_state_in_call(state);
8040}
8041
Eric Laurentf9cccec2022-11-16 19:12:00 +01008042bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008043 audio_mode_t mode = mEngine->getPhoneState();
8044 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008045 || (mode == AUDIO_MODE_CALL_SCREEN)
8046 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008047}
8048
Eric Laurentf9cccec2022-11-16 19:12:00 +01008049bool AudioPolicyManager::isInCallOrScreening() const {
8050 audio_mode_t mode = mEngine->getPhoneState();
8051 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8052}
8053
Eric Laurentd60560a2015-04-10 11:31:20 -07008054void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8055{
8056 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008057 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008058 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008059 sourceDesc->sinkDevice()->equals(deviceDesc))
8060 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008061 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008062 }
8063 }
8064
8065 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8066 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8067 bool release = false;
8068 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8069 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8070 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8071 source->ext.device.type == deviceDesc->type()) {
8072 release = true;
8073 }
8074 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008075 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008076 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8077 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8078 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008079 sink->ext.device.type == deviceDesc->type() &&
8080 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8081 || strncmp(sink->ext.device.address, address,
8082 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008083 release = true;
8084 }
8085 }
8086 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008087 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8088 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008089 }
8090 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008091
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008092 mInputs.clearSessionRoutesForDevice(deviceDesc);
8093
Francois Gaffie716e1432019-01-14 16:58:59 +01008094 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008095}
8096
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008097void AudioPolicyManager::modifySurroundFormats(
8098 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008099 std::unordered_set<audio_format_t> enforcedSurround(
8100 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008101 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008102 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008103 allSurround.insert(pair.first);
8104 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8105 }
Phil Burk09bc4612016-02-24 15:58:15 -08008106
8107 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8108 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008109 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008110 // This is the resulting set of formats depending on the surround mode:
8111 // 'all surround' = allSurround
8112 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8113 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8114 // 'manual surround' = mManualSurroundFormats
8115 // AUTO: formats v 'enforced surround'
8116 // ALWAYS: formats v 'all surround' v 'enforced surround'
8117 // NEVER: formats ^ 'non-surround'
8118 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008119
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008120 std::unordered_set<audio_format_t> formatSet;
8121 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8122 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008123 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008124 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008125 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008126 formatSet.insert(*formatIter);
8127 }
8128 }
8129 } else {
8130 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8131 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008132 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008133
jiabin81772902018-04-02 17:52:27 -07008134 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008135 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008136 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8137 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8138 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008139 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008140 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8141 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8142 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008143 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008144 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008145 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008146 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008147 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008148 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008149}
8150
jiabin06e4bab2019-07-29 10:13:34 -07008151void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8152 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008153 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8154 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8155
8156 // If NEVER, then remove support for channelMasks > stereo.
8157 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008158 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8159 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008160 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008161 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008162 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008163 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008164 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008165 }
8166 }
jiabin81772902018-04-02 17:52:27 -07008167 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8168 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8169 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008170 bool supports5dot1 = false;
8171 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008172 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008173 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8174 supports5dot1 = true;
8175 break;
8176 }
8177 }
8178 // If not then add 5.1 support.
8179 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008180 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008181 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008182 }
Phil Burk09bc4612016-02-24 15:58:15 -08008183 }
8184}
8185
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008186void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008187 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008188 const sp<IOProfile>& profile) {
8189 if (!profile->hasDynamicAudioProfile()) {
8190 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008191 }
François Gaffie112b0af2015-11-19 16:13:25 +01008192
jiabin12537fc2023-10-12 17:56:08 +00008193 audio_port_v7 devicePort;
8194 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008195
jiabin12537fc2023-10-12 17:56:08 +00008196 audio_port_v7 mixPort;
8197 profile->toAudioPort(&mixPort);
8198 mixPort.ext.mix.handle = ioHandle;
8199
8200 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8201 if (status != NO_ERROR) {
8202 ALOGE("%s failed to query the attributes of the mix port", __func__);
8203 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008204 }
jiabin12537fc2023-10-12 17:56:08 +00008205
8206 std::set<audio_format_t> supportedFormats;
8207 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8208 supportedFormats.insert(mixPort.audio_profiles[i].format);
8209 }
8210 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8211 mReportedFormatsMap[devDesc] = formats;
8212
8213 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8214 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8215 modifySurroundFormats(devDesc, &formats);
8216 size_t modifiedNumProfiles = 0;
8217 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8218 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8219 formats.end()) {
8220 // Skip the format that is not present after modifying surround formats.
8221 continue;
8222 }
8223 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8224 sizeof(struct audio_profile));
8225 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8226 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8227 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8228 modifySurroundChannelMasks(&channels);
8229 std::copy(channels.begin(), channels.end(),
8230 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8231 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8232 }
8233 mixPort.num_audio_profiles = modifiedNumProfiles;
8234 }
8235 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008236}
Eric Laurentd60560a2015-04-10 11:31:20 -07008237
Mikhail Naganovdc769682018-05-04 15:34:08 -07008238status_t AudioPolicyManager::installPatch(const char *caller,
8239 audio_patch_handle_t *patchHandle,
8240 AudioIODescriptorInterface *ioDescriptor,
8241 const struct audio_patch *patch,
8242 int delayMs)
8243{
8244 ssize_t index = mAudioPatches.indexOfKey(
8245 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8246 *patchHandle : ioDescriptor->getPatchHandle());
8247 sp<AudioPatch> patchDesc;
8248 status_t status = installPatch(
8249 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8250 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008251 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008252 }
8253 return status;
8254}
8255
8256status_t AudioPolicyManager::installPatch(const char *caller,
8257 ssize_t index,
8258 audio_patch_handle_t *patchHandle,
8259 const struct audio_patch *patch,
8260 int delayMs,
8261 uid_t uid,
8262 sp<AudioPatch> *patchDescPtr)
8263{
8264 sp<AudioPatch> patchDesc;
8265 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8266 if (index >= 0) {
8267 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008268 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008269 }
8270
8271 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8272 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8273 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8274 if (status == NO_ERROR) {
8275 if (index < 0) {
8276 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008277 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008278 } else {
8279 patchDesc->mPatch = *patch;
8280 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008281 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008282 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008283 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008284 }
8285 nextAudioPortGeneration();
8286 mpClientInterface->onAudioPatchListUpdate();
8287 }
8288 if (patchDescPtr) *patchDescPtr = patchDesc;
8289 return status;
8290}
8291
jiabinbce0c1d2020-10-05 11:20:18 -07008292bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8293{
8294 const TrackClientVector activeClients = output->getActiveClients();
8295 if (activeClients.empty()) {
8296 return true;
8297 }
8298 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8299 if (index < 0) {
8300 ALOGE("%s, no audio patch found while there are active clients on output %d",
8301 __func__, output->getId());
8302 return false;
8303 }
8304 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8305 DeviceVector routedDevices;
8306 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8307 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8308 patchDesc->mPatch.sinks[i].id);
8309 if (device == nullptr) {
8310 ALOGE("%s, no audio device found with id(%d)",
8311 __func__, patchDesc->mPatch.sinks[i].id);
8312 return false;
8313 }
8314 routedDevices.add(device);
8315 }
8316 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008317 if (client->isInvalid()) {
8318 // No need to take care about invalidated clients.
8319 continue;
8320 }
jiabinbce0c1d2020-10-05 11:20:18 -07008321 sp<DeviceDescriptor> preferredDevice =
8322 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8323 if (mEngine->getOutputDevicesForAttributes(
8324 client->attributes(), preferredDevice, false) == routedDevices) {
8325 return false;
8326 }
8327 }
8328 return true;
8329}
8330
8331sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008332 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008333 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8334 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008335{
8336 for (const auto& device : devices) {
8337 // TODO: This should be checking if the profile supports the device combo.
8338 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008339 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8340 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008341 return nullptr;
8342 }
8343 }
8344 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8345 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008346 status_t status = desc->open(halConfig, mixerConfig, devices,
8347 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008348 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008349 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008350 return nullptr;
8351 }
8352
8353 // Here is where the out_set_parameters() for card & device gets called
8354 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8355 const audio_devices_t deviceType = device->type();
8356 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008357 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008358 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8359 mpClientInterface->setParameters(output, String8(param));
8360 free(param);
8361 }
jiabin12537fc2023-10-12 17:56:08 +00008362 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008363 if (!profile->hasValidAudioProfile()) {
8364 ALOGW("%s() missing param", __func__);
8365 desc->close();
8366 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008367 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8368 // Reopen the output with the best audio profile picked by APM when the profile supports
8369 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008370 desc->close();
8371 output = AUDIO_IO_HANDLE_NONE;
8372 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8373 profile->pickAudioProfile(
8374 config.sample_rate, config.channel_mask, config.format);
8375 config.offload_info.sample_rate = config.sample_rate;
8376 config.offload_info.channel_mask = config.channel_mask;
8377 config.offload_info.format = config.format;
8378
jiabina84c3d32022-12-02 18:59:55 +00008379 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008380 if (status != NO_ERROR) {
8381 return nullptr;
8382 }
8383 }
8384
8385 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008386
baek.kim -61c20122022-07-27 10:05:32 +00008387 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8388 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8389
jiabinbce0c1d2020-10-05 11:20:18 -07008390 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8391 sp<AudioPolicyMix> policyMix;
8392 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8393 policyMix->setOutput(desc);
8394 desc->mPolicyMix = policyMix;
8395 } else {
8396 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008397 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008398 }
8399
baek.kim -61c20122022-07-27 10:05:32 +00008400 } else if (hasPrimaryOutput() && speaker != nullptr
8401 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008402 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8403 // no duplicated output for:
8404 // - direct outputs
8405 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008406 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008407 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8408
8409 //TODO: configure audio effect output stage here
8410
8411 // open a duplicating output thread for the new output and the primary output
8412 sp<SwAudioOutputDescriptor> dupOutputDesc =
8413 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8414 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8415 if (status == NO_ERROR) {
8416 // add duplicated output descriptor
8417 addOutput(duplicatedOutput, dupOutputDesc);
8418 } else {
8419 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8420 mPrimaryOutput->mIoHandle, output);
8421 desc->close();
8422 removeOutput(output);
8423 nextAudioPortGeneration();
8424 return nullptr;
8425 }
8426 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008427 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8428 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8429 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008430 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008431 }
jiabinbce0c1d2020-10-05 11:20:18 -07008432 return desc;
8433}
8434
jiabinf1c73972022-04-14 16:28:52 -07008435status_t AudioPolicyManager::getDevicesForAttributes(
8436 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8437 // Devices are determined in the following precedence:
8438 //
8439 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8440 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8441 //
8442 // If no such dynamic policy then
8443 // 2) Devices containing an active client using setPreferredDevice
8444 // with same strategy as the attributes.
8445 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8446 //
8447 // If no corresponding active client with setPreferredDevice then
8448 // 3) Devices associated with the strategy determined by the attributes
8449 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8450 //
8451 // See related getOutputForAttrInt().
8452
8453 // check dynamic policies but only for primary descriptors (secondary not used for audible
8454 // audio routing, only used for duplication for playback capture)
8455 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008456 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008457 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008458 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8459 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8460 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008461 if (status != OK) {
8462 return status;
8463 }
8464
8465 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8466 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8467 // as they are unaffected by device/stream volume
8468 // (per SwAudioOutputDescriptor::isFixedVolume()).
8469 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8470 ) {
8471 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8472 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8473 devices.add(deviceDesc);
8474 } else {
8475 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8476 // which selects setPreferredDevice if active. This means forVolume call
8477 // will take an active setPreferredDevice, if such exists.
8478
8479 devices = mEngine->getOutputDevicesForAttributes(
8480 attr, nullptr /* preferredDevice */, false /* fromCache */);
8481 }
8482
8483 if (forVolume) {
8484 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8485 // for single volume control in AudioService (such relationship should exist if
8486 // SPEAKER_SAFE is present).
8487 //
8488 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8489 DeviceVector speakerSafeDevices =
8490 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8491 if (!speakerSafeDevices.isEmpty()) {
8492 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8493 devices.remove(speakerSafeDevices);
8494 }
8495 }
8496
8497 return NO_ERROR;
8498}
8499
8500status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8501 AudioProfileVector& audioProfiles,
8502 uint32_t flags,
8503 bool isInput) {
8504 for (const auto& hwModule : mHwModules) {
8505 // the MSD module checks for different conditions
8506 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8507 continue;
8508 }
8509 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8510 : hwModule->getOutputProfiles();
8511 for (const auto& profile : ioProfiles) {
8512 if (!profile->areAllDevicesSupported(devices) ||
8513 !profile->isCompatibleProfileForFlags(
8514 flags, false /*exactMatchRequiredForInputFlags*/)) {
8515 continue;
8516 }
8517 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8518 }
8519 }
8520
8521 if (!isInput) {
8522 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8523 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8524 if (msdModule != nullptr) {
8525 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8526 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8527 for (const auto &profile: msdModule->getOutputProfiles()) {
8528 if (!profile->asAudioPort()->isDirectOutput()) {
8529 continue;
8530 }
8531 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8532 }
8533 } else {
8534 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8535 }
8536 }
8537 }
8538
8539 return NO_ERROR;
8540}
8541
jiabin3ff8d7d2022-12-13 06:27:44 +00008542sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8543 const audio_config_t *config,
8544 audio_output_flags_t flags,
8545 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008546 closeOutput(outputDesc->mIoHandle);
8547 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8548 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8549 if (preferredOutput == nullptr) {
8550 ALOGE("%s failed to reopen output device=%d, caller=%s",
8551 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008552 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008553 return preferredOutput;
8554}
8555
8556void AudioPolicyManager::reopenOutputsWithDevices(
8557 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8558 for (const auto& [output, devices] : outputsToReopen) {
8559 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8560 closeOutput(output);
8561 openOutputWithProfileAndDevice(desc->mProfile, devices);
8562 }
jiabina84c3d32022-12-02 18:59:55 +00008563}
8564
jiabinc44b3462022-12-08 12:52:31 -08008565PortHandleVector AudioPolicyManager::getClientsForStream(
8566 audio_stream_type_t streamType) const {
8567 PortHandleVector clients;
8568 for (size_t i = 0; i < mOutputs.size(); ++i) {
8569 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8570 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8571 }
8572 return clients;
8573}
8574
8575void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8576 PortHandleVector clients;
8577 for (auto stream : streams) {
8578 PortHandleVector clientsForStream = getClientsForStream(stream);
8579 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8580 }
8581 mpClientInterface->invalidateTracks(clients);
8582}
8583
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008584} // namespace android